Selection Statement in C programming



C if Selection Statement

The if statement is called a single-selection statement because it selects or ignores a single action. The if selection statement either selects an action if a condition is true or skips the action if the condition is false.


   #include <stdio.h>
        // function main begins program execution
   int main( void )    {
   int num1; // first number to be read from user
   int num2; // second number to be read from user
   
   printf( "Enter two integers: " );
   scanf( "%d%d", &num1, &num2 ); // read two integers
   
   if ( num1 == num2 ) {                          
      printf( "%d is equal to %d\n", num1, num2 );
   } // end if                                    
   if ( num1 != num2 ) {
      printf( "%d is not equal to %d\n", num1, num2 );
   } // end if
   if ( num1 < num2 ) {
      printf( "%d is less than %d\n", num1, num2 );
   } // end if
   if ( num1 > num2 ) {
      printf( "%d is greater than %d\n", num1, num2 );
   } // end if
   if ( num1 <= num2 ) {
      printf( "%d is less than or equal to %d\n", num1, num2 );
   } // end if
   if ( num1 >= num2 ) {
      printf( "%d is greater than or equal to %d\n", num1, num2 );
   } // end if
   } // end function main

    Output:
    Enter two integers: 5 10
    5 is not equal to 10
    5 is less than 10
    5 is less than or equal to 10

C if else Selection Statement

The if else selection statement allows you to specify that different actions are to be performed when the condition is true and when it’s false.


    #include <stdio.h>
    int main(void)	{
    initialize variables in definitions // 
	int result; // exam result
    // prompt user for input and obtain value from user 
	printf("%s", "Enter result ( 1=pass,2=fail ): ");
	scanf("%d", &result);
    // if result 1passes 
	if (result == 1) {
		printf("Passed \n");
	}
	else { // otherwise failures 
		printf("Failed \n");
	} end else
} // end function main 

    Output:
    Enter result (1=pass,2=fail) : 1
    Passed
    or the else action
    Enter result (1=pass,2=fail) : 2
    Failed

Ads Right