Syntax if expression Block of statements else Block of statements The if

Syntax if expression block of statements else block

This preview shows page 12 - 21 out of 25 pages.

Syntax: if (expression) { Block of statements; } else { Block of statements; }
Image of page 12
The if Statement The if statementhas the following syntax: if ( conditionstatement; ifis a C reserved word The conditionmust be a boolean expression. It must evaluate to either true or false. If the conditionis true, the statementis executed. If it is false, the statementis skipped. )
Image of page 13
Example: Program to check numbers are equal or not #include<stdio.h> void main(void) { int first, second; scanf ( “ %d %d “, &first, &second); if ( first == second ) printf ( “Both numbers are equal \ n”); else printf ( “Numbers are not equal \ n”); }
Image of page 14
Nested if - elses#include<stdio.h> void main() { int i; printf(“Enter either 1 or 2”);scanf(“%d”,&i); if(i==1) printf(“Gud morning”);else { if(i==2) printf(“Gud afternoon”);else printf(“Gud night”);} }
Image of page 15
Forms of if The if statement can take any of the following forms: if ( condition ) do this ; if ( condition ) { do this ; and this ; } if ( condition ) do this ; else do this ; if ( condition ) { do this ; and this ; } else { do this ; and this ; }
Image of page 16
) if ( condition ) do this ; else { if ( condition ) do this ; else { do this ; and this ; } } if ( condition ) { if ( condition ) do this ; else { do this ; and this ; } } else do this ;
Image of page 17
Program to print marks of students #include<stdio.h> #include<conio.h> void main() { float marks if (marks>90) { printf (“excellent”); } else if (marks>80&&marks<=90) { printf (“very good”); } else if(marks>70&& marks<=80) { printf (“good”); } else { if (marks >60 && marks<=70) { printf (“average”); } } getch(); }
Image of page 18
Switch Statement The control statement that allows to make a decision from the number of choices is called switch Also called switch-case-default The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches
Image of page 19
Rules of using switch case Case label must be unique Case label must end with colon
Image of page 20
Image of page 21

You've reached the end of your free preview.

Want to read all 25 pages?

  • Spring '19
  • C Programming, Subroutine, Control flow, Control table, Switch statement, C standard library

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture