You are on page 1of 42
Outline * Control structure > Decision Statements * If statement * if-else statement * Switch statement LPU CSE101 C Programming a —____________——@- * Program is a set of instruction executed one by one. Aa iS Se * Depending upon the circumstances sometimes it is desirable to alter the sequence of execution of statements. Program LPU CSE101 € Programming Control Statements * The C language programs until now follows a iain! farm Of ea ciition of tater ante up to £125 on your first order can Control Statements = * The C language programs until now follows a sequential form of execution of statements. * C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. * These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional. ©LPU CSE101 € Programming Control Structure * Acontrol structure refers to the way in which the programmer specifies the order of executing the statements. * Three control structures — Sequence structure * Programs are executed sequentially by default. — Selection structures - if, if..else, switch — Repetition structures (iteration) 7 + while, do..while, for. Pu. o> ©LPU CSE101 C Programming ¢ Condition Statements * The C condition statements or the decision statements, checks the given condition up to 2125 on your first order _ Condition Statements * The Ccondition statements or the decision statements, checks the given condition Based upon the state of the condition, a sub- block is executed. * Decision statements are the: — if statement — if-else statement — switch statement ©LPU CSE101 € Programming Daily routine LPU CSE101 C Pr sequence jumping procedures followed im daily Life ee + junaping a quent ® Not attending a class Based ow conditions xX quick ya | Quiz upon tor more + \ e Yes if you h ©LPU CSE101€ P: @:- Su if Statement * If statement — It is decision making statement uses keyword if. — It allows the computer to evaluate the expression first * and then, depending on whether the value is ‘true’ or ‘false’, i.e. non zero or zero it transfers the control to a particular statement. ‘A decision can be made on any expression. zero - false nonzero - true Example: 3 < 4istrue if Statement if (expression) up to 2125 on your first order CnC ee if Statement if (expression) raise statement; Body of iF if (expression) i { Statement just below af block of statements; ©LPU CSE101 C Programming if Statement * The if statement has the following syntax: The condition must be a boolean expression. It must Evaluate to either non-zero or ifisaC reserved word Ee J 5 if ( condition )/* no semi-colon */ statement; 1 If the condition is non-zero, the statement is executed. If it is zero, the statement is skipped. CLPU CSE101 € Programming Is it going to rain? nal sminlns Enenlnsals Use Code: WELCOMESO cpr cc eet a J wv Sw Rain ? ©LPU CSE101 C Programming ee @: #include void main() Pregrany te ; check int v; whether printf (“Enter the number :”); number is scanf("td”, &v); Af (v<10) less than 10. printf (“number is less than 10”); } Enter the number: 6 Number is less than 10 ©LPU CSE101 C Programming Control Flow (== ) Use Code: Z mA WELCOMES50 cen eT Control Flow CLPU CSE101 C Programming if. .else statement a ©LPU CSE101 € Programmin: 8 if..else statement * The if statement executes only when the randitian fallawiine if ie trian x > CUM er ea if..else statement * The if statement executes only when the condition following if is true. * It does nothing when the condition is false. * The if. .else statement takes care of the true and false conditions. ©LPU CSE101 € Programming if..else statement * if. .else has two blocks. * One block is for if and it is executed when condition is non-zero(true). * The other block is of else and its executed when condition is zero (false). if (expression) { block of statements; else block of statements; } if..else statement * The else statement cannot be used without if, up to 2125 on your first order SWIGGY CnC ee if..else statement * The else statement cannot be used without afi. * No multiple else statements are allowed with one if. * else statement has no expression. ¢ Number of else cannot be greater than number of if. ©LPU CSE101 € Programming Ternary conditional operator (?:) © * Ccode: if ( marks>= 60 ) printf ( "Pass\n"); else printf( "Fail\n"); * Same code using ternary operator: — Takes three arguments (condition, value if t rue, value if false) — Our code could be written: print£("%s\n", grade >= 60 ? "Pass" : "“Fail"); — Orit could have been written: grade >= 60 ? printf (“Pass\n”) printf (“Pail\n”); ©LPU CSE101 © Programming #include | a lee main () Example ; t Program to int a; printf ("Enter the number :”); check scanf (“td”, &v); whether ee) Be #include = wold ante 0 Example : t Program to int a; printf£("Enter the number :”); check scanf (“td”, &v) ; whether printf (“number is less than 10”); number is DEsnve (oumven. ts greater then 107) 7 less than 10. Number is less than 10 or Enter the number: 100 Number is greater than 10 ©LPU CSE101 C Programming Control Flow Flow INPUT VALUE OF V Ma 7 Lima / ©LPU CSE101 € Programming ESE ee —sONestedif..else if..else * In if..else statement else block is executed by default after failure of if condition. Cen ee Nested if..else = * In if..else statement else block is executed by default after failure of if condition. * The nested if...else statement is used when program requires more than one test expression. * Test for multiple cases by placing if...else selection statements inside if..else selection statement. * This kind of nesting will be unlimited. ELPU CSE101 C Programming if (condition ){ block of statements; ) else if (condition) { block of statements; } else { block of statements; ©LPU CSE101 C Programming #include Program to void main() { check int a; whether printf("Enter the number :”); x scanf ("td”, &v); number is up to £125 on your first order Co ee @:- a o Program to check whether number is less than 10. #include void main() { int a; printf (“Enter the number :”); scanf("$d", &v); if (v<10) ( printf ("number is less than 10”); } else if (v<100) ( Enter the number: 1 Number is less than 10 oF Enter the number: 56 Number is less than 100 The if statement can take any of the following forms: Forms of if if (condition ){ do this ; and this ; if (condition ) do this ; or } iff (condition ) { do this eise | : do this ; " this ; and this ; } if (condition ) do this ; if (condition) else if (condition) do this ; do this ; else else{ do this ; do this ; and this ; ) #include : : void main() Program to { float marks; scanf("t£"”, émarks) ; if (marks>90) { printf ("Grade A”) ; 7) up to £125 on your first order x > print grades of students ee ee en ‘Pinclude Se void main() Program to { . “float marks; print grades seanf("%£", &marks) ; «Af (marks>30) ( of students printf ("Grade A”) ; ) marks. else if (marks>80) { printf ("Grade B”); ' else if (marks>70)( printf ("Grade C”); = ; ai — rade | 66.70 Grade D or 78.00 Grade Cc Forms of if Deal icell Syntax Quick yar ELCs : Qui ain 2. exaeples if if (condition) Some daviy Statements; eo class is not abeenaed f doww the % attendance goes if.else if (condition) Se cet ibve Statement1; %Y tee: Grades &0 be : Uf. Ot 6 te oe cae } gesiqned ov the basts of else rt es Statement3; ee if; selection of tee Statement4;} s rp based ov enna fron Group Nested if if (conditioni ov, price and availability, Statement1;) else if(condition2): — ese parts executes. Statement2;} else LP Statement 3; @:- break statement * break is a keyword. * break allows the programmer to terminate the loop. a cae eet a break statement break is a keyword. break allows the programmer to terminate the loop. A break statement causes control to transfer to the first statement after the loop or block. The break statement can be used in nested loops. If we use break in the innermost loop then the control of the program is terminated only from the innermost loop. ©LPU CSE101 C Programming ©LPU CSE101 ¢ Programming switch Statement * The control statement that allows to make a decision from the number of choices is called switch. Use Code: WELCOME50 x pr cence ee 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. SLPU CSE101 G Programming ' , Oo switch Statement switch (expression) switch switch ( expression ) { and { case constant1: / eg case valuel : seas pease statement-list1 case constant: rowed case valued: i statements; words statement-list2 break; case value} : case constant3: statement-list3 Ifexpression statements; case... Matches value2, break; control jumps default: } tohere statements; ELPU CSE104 C Programming Rules of using switch case 1. Case label must be unique 2? Case lahel must end with ealan Use Code: x Do WELCOMES50 Pee ec Rules of using switch case Case label must be unique Case label must end with colon Case label must have constant expression Case label must be of integer, character type like case 2, case 1+1, case ‘a’ Case label should not be floating point Default can be placed anywhere in switch Multiple cases cannot use same expression Relational operators are not allowed in switch Nesting of switch is allowed. 10. Variables are not allowed in switch case label.. PWNP pon au ©LPU CSE101 € Programming a Syntax error in switch statement” switch (pt) { case count: ———_| print£("%d”", count) ; break; ease 1<8:. print£("A point”); break; case 2.5: printe("a liner _| line break; case 3+ 7.7: ee . os Te Floating point number printe ("a ee cannot be used and same expression cannot break; ease count+5: be used print£("A pentagon”); break; } ©LPU CSE101 © Programming finclude vets mia Program to | a show switch statement in printé(“\ntlo Geometry}; oe geometry Use Code: WELCOMES50 epee Pan we) @:- @ wh Program to show switch statement in geometry finclude void main) ‘ int pes print£ ("Enter the aumber cf acdes:"); (meant (ta, pe)? eam LE (\nite Geometry”): break, came 1: PEint£("\nA point); break: case 25 printe(*\na line) ; break; came 3: PEinte(\na triangle"); ‘Pincludecatdio.h> void min() Program to 1 7 | int key; in | printf ("Press 1 to turn left."); printf ("Press 2 te turn right.*); Printf ("Press 3 to increase speed."); printf ("press 4 for break: "); scant ("8d", key); case 1: printé("\nTarn left"); break: case 2: 1 to turn left. 2 to turn right. 3 to increase speed. 4 for break: 4 Use Code: WELCOMES0O x po Pe eB Enter the number of nodes: 2 A line igs | Program to printf ("\nTurn left"); break: case 2: printf ("\nTurn right”); break; case 3: printf ("\nIncrease speed”); 3 to increase speed. Press 4 for break: 4 Break Next Class: Loop control and Jump statements cse101@lpu.co.in Use Code: WELCOMES50 ©LPU CSE101 © Programming x po —do-while statement ¢ Jump Statements z — break — continue — goto —return ©LPU CSE101 C Programming ©LPU CSE101 C Programming Ve Repetition Statement * Arepetition statement allows you to specify that an action is to be repeated while some condition remains true. manne Na [/J ©60000@ eee ee Repetition Statement ¢ A repetition statement allows you to specify that an action is to be repeated while some condition remains true. 3b rinpwany Saxeaion SLPU GSE101 G Programming * What if we want to dist — Should we write 500 pr equivalent ? > Obviously not. * It means that we need facility to repeat certair ¢ Such facility is available Hem EE ee SEE statements. ©LPU CSE101 C Programming _—_—_—_—_—__e Qt Loop @ = e The main idea of a loop is to repeat an action errepenel INSTALL Connect with Groups TN TO cL ee Loop ¢ The main idea of a loop is to repeat an action or a series of actions. An action or a series of actions ‘The concept of a loop without condition ©LPU CSE101 € Programming e But, when to stop looping: ¢ Inthe following flowchart, over and over again. It nev an infinite loop ¢ Solution — put a condition continue looping or stop. An action ora series of actions CLPU CSE101 C Programming * A loop has two parts — body and condition Condition a Snapchat even Connect with Groups * A loop has two parts — body and condition * Body -—a statement ora Condition block of statements that will be repeated. True Repeated_Actions| Fase LT — * Condition - is used to control the iteration — either to continue or stop iterating. ©LPU CSE101 © Programming Loop statements * Cprovides three loop statements: loop statements while for do...while pretest loop pretest loop post-test loop @LPU CSE104 € Programming The “while” Statement inc * The syntax of while statement in C: Syntax J a Snapchat even Connect with Groups ae ee The “while” Statement inc - * The syntax of while statement in C: while (loop repetition condition){ statement; updating control; True Repeated_Actions while statement while(loop repetition condition) { Statements; } Loop repetition condition is the condition which controls the loop. *The statement is repeated as long as the loop repetition condition is true. *A loop is called an infinite loop if the loop repetition condition is always true. ©LPU CSE101 C Programming while statement Example: This while statement prints nui #include int main() ee eB while statement ~ ® Example: This while statement prints nui #include int main() a cay GAME { winen. garue has ended int n=10; te, Wife ls eon t eT while (n>0) { That is watle the choise printf("td ”, n); is not equal to ‘Woe n=n-1; ©LPU CSE101 C Programming The for Statementinc ~ @ * The syntax of for statement in C: for (initialization-expression; loop-repetition-condition; update-expression){ statement; Gi * The initialization-expression set the initial value of the loop control variable. * The loop-repetition-condition test the value of the loop control variable. * The update-expression update the loop control variable. ©LPU CSE101 © Programming for (mnitialization; Condition; Updating) Quick yak o repeat the ar loop vce eee a for statement Lor (rmitietization; Condition; Updating) { Repeated Actions; } ©LPU CSE101 © Programming for statement Example: This for statement prints numbers 10 down to 1 #include | int main () { int n; for (n=10; n>0; n=n-1){ printf (“td ”, n); } 10987654321 | DoTEN push ups = for count=1; count<=10; count++ ELPU CSE104 € Progr: Contrd Required final value of contol Required for sonable. semicclon wanable fee which __cemicnlan. Snapchat even Connect with Groups Pea eee) Contra Required final value of control Required for vanable semicolon vanable for which semicolon keyword name Separator the condibonis true separator ,;\ | \/ for ( counter = 1; counter <= 10; counter++ ) Invtal value of Increment of contrdl variable Loop-conttnuaton control variable condition ©LPU CSE101 C Programming Nested Loops * Nested loops consist of an outer loop with one or more inner loops. * Eg: for (i=1;4<=100; i++) ( for (j=1; j<=50; j++) { {ir } ¢ The above loop will run for 100*50 iterations. ©LPU CSE101 € Programming ee @ o— #include % Oo woid msia() Program to im i,3,k print tables printf ("Enter a number: ”); scanf(“td", &k); printf("the tables from 1 to td: \n”,k); meee | Snapchat even Connect with Groups luntoa ee ee ec scant ("td”, 6k); print£("the tables from 1 to td: \n”,k); for(G=1; ick; i++) { for (j=1; 3<=10; 3++){ printf ("td “,i*3): ) //end inner for loop printé("\n"); Enter a number 4 The tables from 1 to 4 12345678910 2468101214 161820 369121518 2124 2730 48 12 16 20 24 28 32 36 40 ja— finelude ‘ / void main () Program to 1 = int 14s print tables printf ("Enter a number:”); un to a Quick yar: Anctiner exaneple would be to Aisplay prince nuanbers Upto any given ywumber #include #include void main() { int i,j; printf ("Displaying right angled tri rows”); for(i=l ; i<=5 ; i++) { for(j=l ; j int main() { int n=10; dot print£ ("td ”, n); n=n-1; 10987654321 ELPU CSE101 © Programming \a— Difference between while and Ms = 1. Condition is specified at the top 1 ee om | Snapchat ene Connect with Groups coal ee 1. Condition is specified at the top 1 2. Body statements are executed when the condition is satisfied c 3. It is an entry controlled loop 4.Syntax: ‘ while (condition) ‘ Statement; ELPU CSE101 € Programming Jump statements * You have learn that, the repetition of a loop is controlled by the loop condition. * C provides another way to control the loop, by using jump statements. * There are four jump statements: J 3 I I l break | cine | retum goto ©LPU CSE101 C Programming break statement * break is a keyword. * break allows the programmer to terminate a Snapchat ene Connect with Groups vue eB break statement break is a keyword. break allows the programmer to terminate the loop. A break statement causes control to transfer to the first statement after the loop or block. The break statement can be used in nested loops. If we use break in the innermost loop then the control of the program is terminated only from the innermost loop. ELPU CSE101 € Programming i \a— break statement @ 2 ##include int main () { Program to show use of break statement. int n; for (n=10; n>0; n=n-1){ if (n<8) break; printf (“td ”, n); _ ©LPU CSE101 © Programming continue statement * continue statement is exactly opposite to hreak & Snapchat ene Connect with Groups roel continue statement continue statement is exactly opposite to break - continue statement is used for continuing the next iteration of the loop statements When it occurs in the loop, it does not terminate, but skips the statements after this statement ©LPU CSE101 C Programming continue statement * Inwhile and do...while loops, the continue statement transfers the control to the loop condition. * In for loop, the continue statement transfers the control to the updating part. while (expression) do for (expr; expr2; expr3) = a | continues | continue; continue; c=] Lx } while ( expression ) ; }/* for * 1 /* while LPU CSE101 C Programming . ‘u continue statement #include Program to vie main () show the use ; of continue Bs Snapchat eee Connect with Groups en eee ed a) continue statement = ae Program to a ee show the use ant i of continue for (n=10; n>0; n=n-1) { statement in if (n¢2==1) for loop continue; printf ("td ", n); 108642 SLPU CSE101 € Programming continue statement #include aint main () { int n = 10; while (n>0. printf ("%d”, n); if (nt2==1) Program to show the use of continue statement in for loop For n=9, loop goes to infinite execution [The loop then prints number 9 over and over again. It never stops. SLPU GSE101 G Programming —_—~o.. goto * Unconditionally transfer control. * goto may be used for transferring control from one place to another. a Snapchat ear vte Connect with Groups conc ee ja— goto ° * Unconditionally transfer control. * goto may be used for transferring control from one place to another. * The syntax is: goto identifier; Control is unconditionally transferred to the location of a local label specified by identifier. For example, Again: goto Again; ©LPU CSE101 C Programming —7~s a — goto statement Sa n=10; zs print£("%d “, n); nen -l; aif (0) Output: 10987654321 ©LPU CSE101 C Programming Hi slude- dio.h> Sey an Progra 33 ie xP show goto neere(g aha statement. if (x%2==0) Snapchat ene Connect with Groups Ke) en MT ‘#include void main() { int x; print£("enter a number: ”) ; scanf (“%d" ,&x) ; if (x%2==0) goto even; else goto odd; even: printf£(" td is even”, x); return; pes "td ds odd”, x)5 enter a number: 18 18 is even ©LPU CSE101 € Programming * Exits the function. * return exits immediate executing function to optionally returning a val * return [expression]; * For example, int sqr (int x){ return (x*x); ©LPU CSE101 C Programming = St Program to show goto statement. Snapchat Connect with Groups alae ec ee ee Outline ea ¢ Unformatted Input/Output functions z — getchar() — putchar() — getch() — putch() — gets() — puts() O©LPU CSE101 C Programming Unformatted Functions ~ ©” * Chas three types of I/C i. Character I/O ii. String 1/0 iii. File 1/0 ©LPU CSE101 C Programming getchar() * This function reads a character-type data from standard input. : x cL ee eB getchar() —s ¢ This function reads a character-type data from standard input. * It reads one character at a time till the user presses the enter key. Qu Syntax) d Variable-name = getchar (); Example: char c; c = getchar(); ©LPU CSE104 € Programming re #include void main() { char c; printf ("enter a character”) ; c=getchar () ; printf ("c = tc ",c); } ©LPU CSE101 € Programming — oT putchar() * This function prints one character on the screen at a time which is read by standard @ x HealthKart official | Open | Ue eB putchar() * This function prints one character on the screen at a time which is read by standard input. Qi Syntax) putchar( variable name); G Example: char c= ‘c’; putchar (c); ©LPU €SE101 € Programming #include void main() { char ch; printf(“enter a character: ”); scanf("%o", ch); putchar (ch) ; } r @LPU CSE101 © Programming _—_—E_~A~ANH", getch() & getche() * These functions read any ze™ fram the standard innit device | @x ec en ae getch() & getche() * These functions read any i from the standard input devi * The character entered is not function until enter is pressec * The getche() accepts and dist * The getch() accepts but character. ©LPU CSE101 € Programming #include void main () { printf (“Enter two alphabets:”); getche() ; getch () ; cls @LPU CSE101 C Programming ——_e putch() @:- This function prints any alphanumeric character taken hv the standard innit device . zm coe ec ee putch() @:- This function prints any alphanumeric character taken by the standard input device #include void main() { char ch; printf (“Press any key to continue”) ; ch = getch(); printf(" you pressed:”) ; putch (ch) ; Press any key to continue You pressed : ©LPU CSE101 C Programming gets() String |/O * This function is used for accepting any string until enter key is pressed (string will be covered later) char str [length of string in number] ; gets(str); ©LPU CSE104 € Programming #include void main () @ x HealthKart official | Open | Ue eB #include void main () { char ch[30]; printf (“Enter the string:”) ; gets (ch) ; printf (“Entered string: %s”, ch); Enter the string: Use of data! Entered string: Use of data! ©LPU CSE101 € Programming —e puts() e a * This function prints the string or character array. It is opposite to gets() char str [length of string in number] ; gets (str); OLPU CSE101 C Programming We have gone a little far beyond this...because we love PATTERNS!!! ae es ©LPU CSE101 C Programming #included \ void maj : : cy IVES See a fe ge Py Py } Enter thf Entered } ®LPU CSE104 € Progr fulltet full text @ 12 @ @ @ 2 J | | | i | Next Class: Revision @LPU CSE101 © Programmin: cse101 @

You might also like