C: Decisions

There are numerous ways decisions can be made in C prorgamming:

  • if statement
  • Nested if statement
  • Switch ... case statement
  • Conditional operator (? :) ternary operator

Example: IF statement in C


	#include <stdio.h>
	int main()
	{
	    int age;
	
	    printf("Enter your age: ");
	    scanf("%d", &age);
	
	    if (age >= 21)
	    {
	        printf("You are old enough to vote.");
	    }
		return 0;
	}
	

Output:

  Enter your age: 21 {user input}
  You are old enough to vote.

Open in new window


Example: IF-ELSE statement in C


	#include <stdio.h>
	int main()
	{
	    int age;
	
	    printf("Enter your age: ");
	    scanf("%d", &age);
	
	    if (age >= 21)
	    {
	        printf("You are old enough to vote.");
	    }
		else
	    {
		 	printf("You are not old enough to vote.");
		}
		return 0;
	}
	

Example: SWITCH statement with an Integer in C


	#include <stdio.h>
	int main()
	{
	    int choice;
	
	 	printf("=========================\n");
		printf("1. View all customers\n");
		printf("2. Edit customer\n");
    	printf("3. Add customer\n");
    	printf("4. Exit\n");
    	printf("=========================\n\n");

    	printf("Please enter your choice: \n");
    	scanf("%d", &choice);
    
		switch(choice)
		{
			case 1 : {
 				 printf("Call view all customers function\n");
				 break;
			}
			case 2 : {
				 break;
 				 printf("Call edit customer function\n");
 		    }
		    case 3 : {
				printf("Call add customer function\n");
				break;
			}
			case 4 : {
 				 printf("Call exit function\n");
  		  		 break;
			}
		}
		return 0;
	}
	

Example: SWITCH statement with a String in C


	#include <stdio.h>
	 
	int main () {

	   char grade = 'C';

	   switch(grade) {
		  case 'A' :
			 printf("Terrific work!\n");
			 break;
		  case 'B' :
			 printf("Very good work.\n");
			 break;
		  case 'C' :
			 printf("Well done.\n");
			 break;
		  case 'D' :
			 printf("You passed.\n");
			 break;
		  case 'E' :
			 printf("You will need to work harder\n");
			 break;
		  default :
			 printf("Invalid grade\n");
	   }
	   
	   printf("Your grade is %c\n", grade);
	 
	   return 0;
	}