Switch statement in Action

Let’s see an example of the switch statement in action. This program imitates a lottery with three winning numbers. Users guess a number, and if the number is correct then they win a prize.

#include <stdio.h>

int main(void){

    int choice = 0;

    printf("Pick a number between 1 and 100 and you might win a prize!\n");

    //get input
    scanf(" %d", &choice);

    //validate input
    if((choice > 100) || (choice<1)){
        printf("Choice was invalid. Sorry!\n");
        //return 1 to OS
        return 1;
    }

    switch(choice){
        case 42:
            printf("\nCongratulations! You win a towel.\n");
            break;
        case 43:
            printf("\nCongratulations! You win a hacky-sack.\n");
            break;
        case 73:
            printf("\nCongratulations! You win a Flash comic book.\n");
            break;    
        default:
            printf("You won absolutely nothing! You guessed wrong.\n");
            break;
    }

    return 0;

}

We store the user’s guess in the choice variable. Before we process the user’s choice, we make sure that the choice is within the parameters we gave. If it isn’t, we inform the user and return control to the operating system.

To process the user’s input, we use a switch statement. If the user does not guess one of the three right numbers, the default message is printed informing the user that they have lost.

Not every switch option needs to end with a break. Sometimes it is valuable to allow the execution to “fall through” to the next option. Let’s see an example of this.

#include <stdio.h>

int main(void){

        char response = 'x';

        printf("Do you agree (y/n):\t");
        scanf(" %c", &response);
        switch(response){
            case 'y':
            case 'Y':
                printf("You said yes!");
                break;
            case 'n':
            case 'N':
                printf("You said no!");
                break;
            default:
                printf("You said... I dunno what you said.");
                break;
        }

    return 0;

}

If you want to see more fun stuff, take a look at my author page: http://www.amazon.com/Al-Jensen/e/B008MN382O/

Advertisements

Basic Structure of a C Program

The basic elements of a C program are the data declarations, functions, and comments.

#include <stdio.h>

int main(void){
    
    //comments
    
    /*
     *also  
     *comments
     */
    
    //declaration statements
    int a = 5;
    char *str = "I have seen the fnords";
    
    //library function call
    printf("%d %s\n", a, str);
    
    //return statement
    return 0;
}

The main() function is special, as it is the first function called in a program. All other functions in a program are called directly or indirectly from main().

The return statement is used to inform the operating system that the program exited normally. Returning a nonzero value indicates an error.

Note that in C, an end-of-line does not indicate the end of a statement; instead, statements are delineated with semicolons.

As we have seen earlier, the standard printf() function is used to output data to standard output.

#include <stdio.h>

int main(void){
    
    int a = 7;
    int b = 9;
    double c = 1.618;
    
    /*
     * output the results
     * of some simple mathematical expressions
     */
    printf("a + b = %d\n", a + b);
    printf("b * c = %f\n", b * c);
    printf("a / c = %f\n", a / c);
    
    
    return 0;
}

Computers are of course here to do computations. A computer can quickly resolve complex mathematical expressions. The C programming language has five simple mathematical operators: multiply, divide, add, subtract, and modulus. Of these, the only one that is not commonly used in everyday arithmetic is the modulus operator, represented by a percentage sign.

#include <stdio.h>

int main(void){
    
    /*
     * lets use the modulus operator
     * to get the remainder value
     */
    printf("%d %% %d = %d\n",9, 3, 9 % 3);
    printf("%d %% %d = %d\n", 10, 3, 10 % 3);
    printf("%d %% %d = %d\n", 15, 4, 15 % 4);
    
    return 0;
    
}

With C we can store values in variables.  Each variable has a string identifier, a name, basically. In addition to the name, each variable also has a variable type. The type defines what sort of data the variable can hold.

Before we can use a variable, we must define it in a declaration statement. A variable declaration defines the name of the variable and specifies the type of data the variable is meant to store.

#include <stdio.h>

int main(void){
    
    /*
     * declare four variables
     */
    int a;
    char b;
    double c;
    long long int d;
    
    
    //see what values they store
    printf("a = %d\n", a);
    printf("b = %c\n", b);
    printf("c = %f\n", c);
    printf("d = %lld\n", d);
    
    //return zero to the
    //operating system
    return 0;
    
}

One common variable type is int, or integer. Integer numbers have no fractional part or decimal point. Instead, decimal numbers are stored in the double type. Letters are stored in the char variable type.

When a variable is created, it is given a garbage value of whatever data happened to be in memory. We can have a variable store more meaningful data via an assignment statement.

#include <stdio.h>

int main(void){
    
    //declare an int variable
    int a;
    
    printf("%d\n", a);
    
    //assign the variable a value
    a = 73;
    
    printf("%d\n", a);
    
    
    return 0;
    
}

We use the standard library function printf() to display data. The printf() function uses special characters called conversion specifiers to output the value stored in a variable. The %d characters make up the integer conversion specifier, and the %f characters are the float or double conversion specifier.  The variables that we want displayed are listed after the format string; these variables and the format string make up the parameter list for the printf() function.

If you are interested in learning more about C and you have an Amazon Kindle or a Kindle app for your smartphone or tablet, take a look at my book http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M

 

 

 

 

 

 

 

Introduction to File Streams in C

A string is a linear sequence of elements. Only one element of the stream is accessible at any given moment. C deals with files in terms of streams of bytes. Each stream is indicated by a file descriptor, which essentially is a number that labels the file in a table of open files. However, in C we rarely work with file descriptors directly, as their implementation is specific to the operating system on which the program is running; in standard C we instead use what is known as a file pointer. A file pointer is a pointer to a C library construct that wraps the file descriptor, thereby giving us an common interface for accessing file. 

The relationship between a file and  a stream is one to one. To create a file stream, we use the fopen() function.

#include <stdio.h>

int main(void){
    
    FILE *fp;
    
    //open the file stream
    if((fp=fopen(“testfile.txt”, “w”))==NULL){
        printf(“Problem opening the file.\n”);
    } else {
        printf(“File opened successfully.\n”);
    }
    
    if(fclose(fp)!=0){
        printf(“There was a proble closing the file.\n”);
    } else {
        printf(“File closed successfully.\n”);
    }
    
    return 0;
}

We should always check to make sure that a file stream has opened successfully. If the file stream has not been opened, then the FILE pointer variable will contain NULL. The fclose() function returns a zero if it has executed successfully.

The file mode is a string that tells C how we intend to use the file. The ‘r’ mode opens the file for reading. The ‘w’ mode creates a new text file if one does not exist, and overwrites an existing file. The ‘a’ mode opens a text file for adding text to a pre-existing file.

#include <stdio.h>

int main(void){
    
    FILE *fp;
    
    /*
     * create new file with fopen using the w mode
     */
    
    if((fp=fopen("newfile.txt", "w"))==NULL){
        printf("Could not create a new file.\n");
    } else {
        printf("The file newfile.txt has been created.\n");
    }
    
    if(fclose(fp)!=0){
        printf("Problem closing the file stream.\n");
    }
    
    return 0;
    
}

There are three predefined streams in C, the standard input stream, the standard output stream, and the standard error stream. These stream are opened automatically when the main() function of a program is invoked.

#include <stdio.h>

int main(void){
    
    FILE *fp = stdout;
    
    char *str = "Hello world!";
    
    /*
     * write "Hello World!"
     * to our screen
     */
    fwrite(str, 1, 12, fp);
    
    return 0;
    
}

To learn more about C, take a look at my Kindle book http://www.amazon.com/dp/B00A4JGE0M/

 

Char Functions in C

The C Standard Library has a useful set of functions for handling characters and strings. The string functions require the header <string.h> and the character functions require the header <ctype.h>.

Character functions automatically convert their arguments to the unsigned char type.

The isalnum() function returns nonzero if its argument is either a letter of the alphabet or a digit.

#include <ctype.h>
#include <stdio.h>

int main(void){
    
    char ch;
    
    while(1){
        printf("Enter a character or enter ! to quit:\t");
        ch = getchar();
        if(ch=='!'){
            break;
        }
        
        //use isalnum() function
        if(isalnum(ch)){
            printf("%c is alphanumeric\n", ch);
        } else {
            printf("%c is not alphanumeric\n", ch);
        }
        
        //flush standard input
        while((ch = getchar())!='\n'){}
    }
    
    return 0;
    
}

The isalpha() function returns nonzero if the char value is a letter of the alphabet; otherwise zero is returned.

#include <ctype.h>
#include <stdio.h>

int main(void){
    
    char ch;
    
    while(1){
        printf("Enter a character (Enter ! to exit):\t");
        ch = getchar();
        if(ch!='!'){
            if(isalpha(ch)){
                printf("%c is a letter of the alphabet\n", ch);
            } else {
                printf("%c is not a letter of the alphabet\n", ch);
            }
            
        } else {
            break;
        }
        
        /*
         * slightly more optimal method
         * of clearing input buffer
         */
        while(getchar()!='\n'){}
        
    }
    
    return 0;
    
}

The isblank() function returns nonzero if the value is a whitespace character.

#include <stdio.h>
#include <ctype.h>

int main(void){
    
    char ch;
    
    while(1){
        
        printf("Enter a character (enter ! to exit): ");
        
        if((ch=getchar())=='!'){
            break;
        }
        
        if(isblank(ch)){
            printf("%c is a whitespace character\n", ch);
        } else {
            printf("%c is not a whitespace character\n", ch);
        }
        
        //clear stdin
        while(getchar()!='\n'){}
        
    }
    
    return 0;
    
}

The isupper() function returns nonzero if the value is an uppercase letter; the islower() function returns nonzero if the value is a lowercase letter.

#include <stdio.h>
#include <ctype.h>

int main(void){
    
    char ch;
    
    while(1){
        printf("Enter a character (! to exit):\t");
        ch=getchar();
        
        if(ch=='!'){
            break;
        }
        
        //test char value using
        //isupper() and islower()
        if(isupper(ch)){
            printf("%c is an uppercase letter.\n", ch);
        } else if (islower(ch)){
            printf("%c is a lowercase letter.\n", ch);
        } else {
            printf("%c is not a letter.\n", ch);
        }
        
        //clears stdin
        while(getchar()!='\n'){}
        
    }
    
    return 0;
    
}

Please visit my author page on Amazon.com: http://www.amazon.com/Al-Jensen/e/B008MN382O/

 

 

Revisiting the While Loop in C

Computers’ ability to process large amounts of data is partly due to their ability to repeat a task endlessly, and without complaint.

The while loop enables our programs to repeat a series of statements, over and over, so long as a certain test condition is met before each repetition.

The while statement is a looping statement that controls the execution of an associated series of statements. Looping statements cause delineated areas of a program to execute repeatedly, as long as certain conditions are being met.

#include <stdio.h>


int main(void){
    
    int a=73;
    int b=42;
    int c = 0;
    
    while(a-- > b){
        printf("repeating this loop for the %d time\n",
                ++c);
    }
    
    
    return 0;
    
}

It is required to put parentheses around the test expression. As long as this expression resolves to True, the code block will be executed repeatedly, until the expression becomes False. Braces are required around the body of the while loop, unless the body is only one single statement.

#include <stdio.h>

int main(void){
    
    //1 is always true
    while(1){
        printf("This loop would go on forever\n");
        break;
    }
    
    printf("...were it not for the break statement.\n");
    
    
    return 0;
    
}

The body of the loop must in some way change the values used in the test expression, otherwise the loop will execute forever; this is what is known as an infinite loop. Although, the break statement can also be used as an alternative way to end the loop.

The body of a while loop can contain one or more C statements, including additional while loops.

#include <stdio.h>

int main(void){
    
    char a='a';
    int x;
    
    while(a!='z'){
        putchar(a++);
        x = 1;
        while(x<11){
            printf("%3d", x++);
        }
        putchar('\n');
    }
       
    return 0;
    
}

A while loop can be used to ensure valid user keyboard input. We can include both a prompt and a scanf() function within the body of the while loop to ensure that the user is prompted for input until the test expression resolves to False.

#include <stdio.h>

int main(void){
    
    char answer='x';
    
    while((answer!='y') && (answer!='n')){
        printf("Should we continue? (y/n)\n");
        scanf(" %c", &answer);
    }
    
    return 0;
    
}

The while loop tests that test expression at the top of the loop; this is why we set the value to be tested before starting the loop, so that we could be sure the expression would evaluate to be True at least once, so that the prompt would be displayed.

If you want to learn more about C, get my book http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/.

It is filled with completely new content not seen on this blog.

 

 

The Switch Statement

The switch statement enables us to choose one course of action from a set of possible actions based on the evaluation of an expression.

#include <stdio.h>

int main(void){
 
  int num = 8;
 
  switch(num){
    
    case 4:
      printf("The number is four.\n");
break;
    case 6:
      printf("The number is six.\n");
break;
    case 8:
      printf("The number is eight.\n");
     break;
  }
 
  return 0;
 
}

As we have seen above, the value of the expression in parentheses following the keyword switch determines which of the statements between the braces will be executed.

The break statement causes switch to skip over the other statements within that block and continue with whatever statement follows the closing brace. If we do not put a break statement in, then a switch statement can end up giving us multiple results. Sometimes, that’s a good thing, and sometimes, that’s a bad thing.

#include <stdio.h>

int main(void){
 
  int a = 16;
 
  switch(--a){
    
    case 15:
      printf("a == 15\n");
    case 16:
      printf("a == 16\n");
    case 17:
      printf("a == 17\n");
 
  }
 
  return 0;
 
}

We can associate several case values with one group of statements.

#include <stdio.h>

int main(void){
 
  char a;
 
  printf("Enter a letter:\n");
  switch((a=getchar())){
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U':
    printf("The character is a vowel.");
    break;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    printf("The character is a number.");
    break;
    default:
    printf("The character is a consonant.");
    break;
  }
        
  return 0;
 
}

Note that placing a break statement after the default case is not, strictly speaking, necessary.

If you have an Amazon Kindle or Kindle app, take a look at my book on C:

http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/

As well as my book on Linux:

http://www.amazon.com/Big-Als-Linux-Fedora-CLI-ebook/dp/B00GI25V30/

Arrays and Pointers in C

Pointers and arrays are closely related; an array name without an index is functionally a pointer to the first element in the array.

#include <stdio.h>


int main(void){
 
  char arrayEmp[10];
 
  printf("&arrayEmp[0] = %p\n", &arrayEmp[0]);
  printf("arrayEmp = %p\n", arrayEmp);
 
 
  return 0;
 
}

As we have seen above, an array identifier without an index generates a pointer. Likewise, we can use offsets to index a pointer to an array.

#include <stdio.h>

int main(void){
 
  int i;
 
  int arrayEmp[5];
  int *arrayPtr;
  arrayPtr = arrayEmp;
 
  *(arrayPtr+0) = 42;
  *(arrayPtr+1) = 73;
  *(arrayPtr+2) = 1138;
  *(arrayPtr+3) = 1701;
  *(arrayPtr+4) = 8086;
 
 
  for(i=0;i<5;i++){
    printf("arrayEmp[%d] = %d\n", i, arrayEmp[i]);
  }
 
 
  return 0;
 
}

Remember, arrays start at zero. To access the fifth element, we must use the index number 4. Thanks to pointer arithmetic, we have two different ways to access an array element.

#include <stdio.h>

void printString1(const char *str);
void printString2(const char *str);
void printString3(const char *str);

int main(void){
 
 
  char str[30]={'T','h','e',' ','c','a','k','e',' ','i','s',' ','a',' ','l','i','e','\n',''};

 
  printString1(str);
  printString2(str);
   printString3(str);
  return 0;
 
}


void printString1(const char *str){
  int i;
  for(i=0; str[i]; i++){
    putchar(str[i]);
  }
}


void printString2(const char *str){
  while(*str){
    putchar(*str++);
  }
}

void printString3(const char *str){
  int i = 0;
  while(*(str+i)){
    putchar(*(str+i));
    i++;
  }
}

C allows for arrays of more than two dimensions; although, arrays of more than three dimensions are relatively rare. In multidimensional arrays, it takes the computer time to compute each index. This means that accessing an element in an multidimensional array can be slower than accessing an element in a single-dimension array.

When passing multidimensional arrays into functions, we must declare all but the leftmost dimension.

Pointers are sometimes used to access array elements because pointer arithmetic is faster than array indexing.

#include <stdio.h>

#define LINELENGTH 5

void printLine(int *intArray, int size);

void printArray(int *intArray, int size);

int main(void){
 
  int intArray[3][LINELENGTH];
 
  int *arrayPtr;
 
  int i, j;
 
  for(i=0; i<3; i++){
   for(j=0; j<5; j++){
     intArray[i][j]=i+j;
   }
  }
 
  printLine(intArray[0], LINELENGTH);
 
  putchar('\n');
 
  printLine(intArray[1], LINELENGTH);
 
  putchar('\n');
 
  printLine(intArray[2], LINELENGTH);
 
  printf("\n\n");
 
  arrayPtr = &intArray[0][0];
 
  printArray(arrayPtr, 3*LINELENGTH);
   
  putchar('\n');
 
  return 0;
 
}



void printLine(int *intArray, int size){
  while(size-->0){
      printf("%d\t", *intArray++);
  }
}


void printArray(int *intArray, int size){
  while(size-->0){
    printf("%d\t", *intArray++);
  }
}

A two dimensional array can be reduced to a pointer to an array of one-dimensional arrays. We can use a separate pointer variable as a way to use pointers to access elements within a row of a two-dimensional array.

#include <stdio.h>


int main(void){
 
  int intArray[5][7];
 
  int i = 0;
  int j = 0;
  int *ptr;
 
  //set pointer to second row
  ptr = &intArray[2][0];
 
  for(i=0; i<7; i++){
    *(ptr+i) = i * 2;
  }
 
 
  for(i=2, j=0; j<7; j++){
    printf("%d\t", *(intArray[i]+j));
  }
 
  putchar('\n');
 
  for(i=0; i<5; i++){
      ptr = &intArray[i][0];
      for(j=0; j<7; j++){
    *ptr++ = i + j;
      }
  }
 
  //set pointer to fourth row
  ptr = &intArray[4][0];
 
  for(i=0; i<7; i++){
    printf("%d\t", *(ptr+i));
  }
 
  putchar('\n');
 
  for(i=0; i<7; i++){
    printf("%d\t", *ptr++);
  }
 
  return 0;
 
}

For a more thorough look at pointers and the C language, check out my book http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/