Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 05: Selection and Control Structures 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice. C3: Protected
About the Author Created By: Jeyshankar Perumal (125623) Credential Information: Version and Date: Technical Skills: UNIX/C/C++/Oracle Experience: 8.5 Years PSC/PPT/1107/1.0
Icons Used Questions Tools Hands on Exercise Coding Standards Test Your Understanding Reference Try it Out A Welcome Break Contacts
Problem Solving and 'C' Programming Session 05: Overview Introduction: This session explains the various program constructs (statements) available in C. These program constructs are used to process the input data to output data.
Problem Solving and 'C' Programming Session 05: Objective Objective: After completing this Session you will be able to:» Write a simple program» Write program using conditional statements» Write program using looping and iteration
Basic Program Constructs The basic program constructs in C are statements and functions. Statements in C:» Simple statement: An expression becomes statement when it is followed by a semicolon (;) Example: a = 8; c = a + b; ; /*Null statement*/
Basic Program Constructs (Contd.)» Compound Statements / Blocks: Compound statements are used to group statements into an executable unit. It consists of one or more individual statements enclosed within the braces {}.
Sequence The statements in the program are executed in sequence by default. For example a program which consists of only declaration statements, input-output statements, and one or more simple expression statements are executed in a sequential manner. The order of execution can be changed by the use of selection and control statements.
Selection Selection statements are used to alter the normal sequential flow of control. It provides the ability to decide the order of execution. Selection constructs in C:» if statement» Conditional / ternary operator statement (? :)» switch statement
if Statement The if statement allows you to establish decision-making into your programs. Programs may require certain logical test to be carried out at some particular point. The tests and subsequent decisions are made by evaluating a given expression as either true (non zero) or false (zero). An expression may involve arithmetic, relational, logical operators.
if Statement (Contd.) The if statement has three basic forms:» Simple if-else» Nested if» if-else if ladder
Simple if-else Statements Syntax: if (expression) { statements1; } else { statements2; } Expression can be arithmetic, logical, relational expression or a variable. The else part is optional.
Simple if-else Statements (Contd.) Following is the example of simple if-else statement: if (a<b) max = b; else max = a; printf( max = %d,max);
Short-circuit Evaluation Whenever the expression using && and are evaluated, the evaluation process stops as soon as the outcome, true or false is known. For example:» expr1 && expr2 If the value of expr1 is zero, the evaluation of expr2 will not occur (0 AND anything is 0)» expr1 expr2 If expr1 has non-zero value, the evaluation of expr2 will not occur (1 OR anything is 1)
Nested if Statement if statement can contain another if statement in its body. Syntax: if (expression) { statements1; if (expression) statements-1; } else { statements2; if (expression) statements-2; }
Nested if Statement: Example Program to find the maximum of 3 numbers: if (a>b) if (a>c) printf( largest = %d, a); else printf( largest = %d, c); else if (c>b) printf ( largest = %d, c); else printf ( largest = %d, b);
if else if Ladder Statement Syntax: if (expression) statements1; else if (expression) statements2; else if (expression) statements3; else statements4;
if else if Ladder Statement (Contd.) Example: if (mark >= 75) printf( Honours\n ); else if(mark >=60) printf( First Class\n ); else if (mark >=50) printf( Second Class\n ); else if (mark >=45) printf( Third Class\n ); else printf( Fail\n );
Conditional Operator Statement Efficient form for expressing simple if statements. It takes 3 expressions / operands. Syntax: [variable =] expr1? expr2: expr3; This simply states: if (expr1 is true) then expr2 else expr3
switch Statement It is a multiway conditional statement generalizing the if-else statement. A switch statement allows a single variable to be compared with several possible case labels which are represented by constant values. If the variable matches with one of the constants, then an execution jump is made to that point.
switch Statement (Contd.) Syntax: switch (expression) { case item 1: statement 1; break; case item 2: statement 2; break; case item n: statement n; } default : break; statement;
switch Statement (Contd.) expression may contain a constant value, variable, array variable, pointer variable, or any expression but must be an integer valued expression. Items which represent the case labels must be an integer constant or character constant. Default case is optional. The break is needed to terminate the switch after the execution of particular choice. Otherwise the next case would get evaluated.
switch Statement: Example switch (op) { case + : } case - : case * : case / : default: c=a + b; break; c=a - b; break; c=a * b; break; c=a / b; break; printf ( Invalid operator );
Iteration Real world applications require some set of instructions that loops within the program, performing repetitive actions on a stream of data. C supports following loop statements:» for statement» while statement» do-while statement
for Statement This statement is used to repeat a statement or a set of statements until some condition satisfied. Syntax: for (exp1; exp2; exp3) { } statement / block of statements;
for Statement: Valid Examples for (x=0; ((x>3) && (x<9)); x++) for (x=0, y=4; ((x>3) && (y<9)); x++, y+=2) for (x=0, y=4, z=4000; z ; z/=10) for (;c<=20;c=c+2) for (c=2;;++c) /*infinite loop*/ for (;c<=20;) for (;;) /*infinite loop*/
Nested for Statement There are many situations in which it is very convenient to have a loop contained within another loop. Such loops are called nested loops. For each and every iteration through the outer loop, the inner loop runs completely.
Nested for Statement (Contd.) Example: for (i=1;i<=3;i++) { } printf( \n i = %d,i); for (j=1;j<=3; j++) printf ( \n j = %d,j); j is the inner loop variable and i is the outer loop variable.
while Statement The while is an entry controlled loop statement. Syntax: while (expression) { Statements; } Expression can be a constant value, variable or any expression. As long as the expression is true, the body of the loop is executed repeatedly.
while Statement (Contd.) Example: 1.while(x--){ }; 2.while(x = x+1){ }; 3.while(x) { }; 4.while(1); 5.while ( (ch = getche( ))!= q ) putchar(ch);
do while Statement The do.. while is an exit controlled loop statement. Syntax: do { statement (s); }while (expression); The body of the loop is executed at least once, even though the expression is false for the first time.
do while Statement (Contd.) Example: int d=1; do { printf ( %d \n, d); ++d; } while (d<=10);
break Statement break statements causes the execution of the current enclosing switch case or loop to terminate. Example: for(loop=0;loop<50;loop++) { } if (loop==10) break; /*control will come out*/ /*of the loop.*/ printf("%d\n",loop); only numbers 0 through 9 are printed.
continue Statement continue statement is used to terminate the current iteration and to continue the loop with the next iteration. Example: for (loop=0;loop<100;loop++) { } if (loop==50) continue; printf ("%d\n",loop); The numbers 0 through 99 are printed except 50.
exit() Terminates the program. Syntax: void exit( int status) Before terminating the program, it performs the following tasks:» Closes all files» Writes buffered output» Call any registered exit function Status can be EXIT_SUCESS (normal termination) or EXIT_FAILURE (abnormal termination)
Q & A Allow time for questions from participants
Try it Out - 1 Problem Statement: Write a program to print temperature in Celsius and Fahrenheit starting from 0 F incremented by 20F up to 300 fahrenheit
Try it Out - 1 (Contd.) Code: #include <stdio.h> main() { int lower, upper, step; float fahr, celsius; lower = 0 ; upper = 300; step = 20 ; fahr = lower; } while ( fahr <= upper ) { celsius = (5.0 / 9.0) * (fahr - 32.0); printf("%4.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } getchar(); Refer File Name : <ses5_1.c> for soft copy of the code
Try it Out - 1 (Contd.) How it Works: When the Program is run, The lower, upper and step variables are initialised to 0,300 and 20 Assigns the lower value to fahr variable, find out the celsius using the formula 5/9*(fahr-32) Print both celsius and fahrenheit value for 0F Increment the Fahr to 20 and again apply formula to find equivalent celsius value. The above step continues till the fahr value is greater than the upper value say 300
Q & A Allow time for questions from participants
Test Your Understanding 1. What will be the output of the following code? x=6; if (x=7) printf ( valid ); else printf ( invalid ); 2. What will be the output of the following code? a=10; (a % 2)? printf ( %d - Even,a+1) : printf ( %d Odd, a+1);
Test Your Understanding (Contd.) 3. How many asterisks will be printed if the following code is executed with x=2? switch (x) { } case 1: printf( * \n ); case 2: printf( ** \n ); case 3: printf( *** \n ); case 4: printf( **** \n );
Test Your Understanding (Contd.) 4. How many times the body of each loop will be executed? a) int i; for (i=0;i<=5;i=i+2/3) { ----; ----; } b) int m=10,n=7; while (m % n >=0) { ----; m=m+1; n=n+2; ---- }
Practice Exercises 1. Write a C program to check whether the given number is a Prime number. 2. Write a C program to find the sum of digits of a given number. 3. Write a program which accepts a number n, and then finds the sum of the integers from 1 to 2, then from 1 to 3, and so forth until it displays the sum of the integers from 1 to n.
Problem Solving and 'C' Programming Session 05: Summary if statement is a condition based decision making statement. Ternary operator is more efficient form for expressing simple if statements. switch statement is a conditional control statement that allows some particular group of statements to be chosen from several available groups. Looping allows the program to repeat a section of code any number of times or until some condition occurs. for, while, and do-while statements are repetitive control structures available in C, that are used to carry out conditional looping. break statement is used to terminate the current loop but continue statement skips the current iteration and continues the loop with the next iteration.
Problem Solving and 'C' Programming Session 05: Source C Reference Card (ANSI) C Reference Manual by Dennis Ritchie Programming in C: A Tutorial by Brian W. Kernighan, Bell Laboratories Byron Gottfried, Programming in C, Tata McGraw Hill Deitel & Deitel, C How to Program, Third Edition, Prentice Hall Disclaimer: Parts of the content of this course is based on the materials available from the Web sites and books listed above. The materials that can be accessed from linked sites are not maintained by Cognizant Academy and we are not responsible for the contents thereof. All trademarks, service marks, and trade names in this course are the marks of the respective owner(s).
You have completed the Session 05 of Problem Solving and 'C' Programming 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice.