You are on page 1of 26
Managing Input and output operations, Conditional Branching and Loops STATEMENT > A statement is also called instruction. \icates, instruction is used to instruct computer to perform a particular task like adding two numbers reading data from keyboard. Example: sum=a+b; scanf ("8d ", &n); In C, the semicolon (;) is a statement terminator. Compound Statement or Block: ‘The sequence of statement enclosed within a pa tatement. Example: t a=1*b; printf("area =%d", a); } of braces ( and } is called a compound Managing Input and output operations There are 2 types of I/O Functions as shown below: Console Input/Output functions ] Formatted functions Unformatted functions Output g pate) | etche() | putchan() | getchar() int | seanfi’) | printi() - : float | seanfi’) | printi() > ; string | seanfi) | printi() string [ gets) [ puts) UNFORMATTED 1/0 Unformatted 1/0 refers to an 1/O data has not been arranged in any order and user don’t have control on the arrangement of data. Reading a character getchar( ) > Read a character from the keyboard and store this character into a memory-location. You have to press ENTER key after typing a character. Syntax variable_name=getchar( ); char name; name= getchar{ ); Example: Writing a character putchar( ): > Displays a character stored in the memory-location on the screen. Syntax puichar(variable_name); putchar(name ); Example: Program example to read a character and display it. #include Void main() t char x; printf ("enter one letter terminated by ENTER key \n”); x = getchar(); putehar("\n’); putchar (x); } Output : enter one letter terminated by ENTER key a a Disadvantage of Unformatted /O It is not possible to read/print any other data except characters ie. it is not possible to read/print integer numbers, floating point numbers etc. ‘The “ctype.h” supports for character with many inbuilt function and the table 4.1 lists the some of the functions available in it. Table 4.1. Character Test Functions _|!scan alphanumeric character? FORMATTED VO seanf(): ‘The scanf( ) standard library function is used to read one or more values from the standard input (keyboard) and assign them to specified variables. Syntax: seanf(“Controlstring or format specifier” ,address_of variables) Example: scanf("Sed %ef Yee", &x, Bey, &2); Table 4.2 Commonly used scant Format Codes SEEKS LESSEE following letters may be used as prefix for certain for short integers for long integers or double L_forlong double Th > A sscanf{ ) always contains a control string or format string in quotation marks. > Bach value to be printed needs a conversion specification like Yd to hold its place in the control string. > There should be a comma (, ), between the control string and the addresses of variables. printf) ‘The printf () standard library function is used to print the values of expressions on standard output (i.e, display) in a specified format, Syntax: if“ControlS les or expressions) Example printt("Zed %f Yee", x, ¥, 2); > printf (jalways contains a control string or format string in quotation marks. > The control string may or may not be followed by some variables or expressions whose value we want printed. > Each value to be printed needs a conversion specification like Yd to hold its place in the control string, > There should be a comma (,) between the control string and the list of variables. > The symbol “\n” (called newline character) in the control string tells the machine to jump to a new line. If there are variables or expressions to be printed, commas are used to separate them form the control string and each other. Table 4.3 Commonly used printf Format Codes print single character "| print a decimal integer prin fcting point value in exponent form print a floating pont value without exponent print floating pont value either e-ype or type depending on print a signed decimal integer print an octal integer, without leading zero printa string print an unsigned decimal integer print a hexadecimal integer, without leading Ox VARIATIONS IN OUTPUT FUNCTION Table 4.4 Commonly used Output Format Flags ‘Output is leftjustitied within the field. Remaining field will be blank. + + or - will precede the signed numeric item. 0 Causes leading zeros to appear. # (with oor) | Causes octal and hex items to be preceded by O and Ox, respectively. 4 wth e,f0rg) | Causes decimal pointtobe presentinalfloating pointnumbers, evenfitis whole number. Also prevents the truncation of trailing zoos in g-ype conversion. L Format printt(“%67.41"y) print(-%7.2F-y) printf-%6-7.2F.y) printrsery) printt(“% 10.20" print-%611.4e",-y) print(%4-10.26"y) print2%e"y) \ specication 123456708 0012345678 90 . = (Te [wl TeTeleTHTt[ [s[sfelofols Las a N[elw] [ole[clH]t] [+|t\olojo\) fxs CODE EEC De terete %58 iG : : Liz 20.108 [N/E |w] [D[efe Ea vss njelw] [olele TL aleclaay Format Output | printf(“%d", 9876) Og eGu ara | printf("%6d”, 9876) 9 8 [2 eee printf("%2d", 9876) 9 8 ae, 6 ] printf("%06d" 9876) oa ;8i[7|e6 printf("%06d" 9876) ofo[s|;s|7]e CONTROL STRUCTURES > vv ov v nyt A program is nothing but the execution of sequence of one or more instruction Quite often, it is desirable to change the order of execution of statements based on certain conditions or This involves a kind of decision making to see whether a particular condition has occurred or not and direct the computer to execute certain statements accordingly. Based on application, it is necessary / essential To alter the flow of a program Test the logical conditions Control the flow of execution as per the selection these conditions can be placed in the program using decision-making statements. (C SUPPORTS MAINLY FOUR TYPES OF CONTROL STATEMENTS 1. i, ii, iv, i iii, 3. i, ii, 4. Decision making statements if statement if else statement nested if statement else if ladder switch statement Loop control statements while loop for loop do-while loop Conditional control (jump) statements break statement continue statement goto statement (unconditional jump) BASIC CONCEPT OF DECISION STATEMENTS > > > Decision making is critical to computer programming, There will be many situations when you will be given 2 or more options and you will have to select an option based on the given conditions. The following flow diagram shows how conditions work in C. 1. Decision making statements i, THE if STATEMENT > This is basically a “one-way” decision statement. > This is used when we have only one alternative. The syntax is shown below: if (expression) C True part statement1; } Rest of the code; > Firstly, the expression is evaluated to true or false. Only if the expression is true then true part statements will be executed. The flow diagram is shown below: statement rest of the code Program to illustrate the use of if statement. #include void main() t int n; printf (“Enter any non-zero integer: \n") ; scanf("td”, én); i£(n>0) printf ("Number is positive number “); if(n<0) printf ("Number is negative number ”); 2 Output : Enter any non-zero intege: 7 Number is positive number THE if-else STATEMENT > This is basically a “two-way” decision statement. > This is used when we must choose between two alternatives. The syntax is shown below: if (expression) t True part Statement1; 2 else t False part Statement2; 2 Rest of the code; > Firstly, the expression is evaluated to true or false. Only if the expression is true then true part statements will be executed otherwise false part statements are executed. The flow diagram is shown below: ¥ false a. expression ¥ ¥ statement2 | statement y rest of the code Program to illustrate the use of if else statement. #include void main() f int n; printf ("Enter any non-zero integer: \n") seanf("td”, &n) i£(n>0) printf ("Number is positive number”); else printf ("Number is negative number”); } Output : Enter any non-zero integer: 7 Number is positive number ‘THE nested if STATEMENT. > An if-else statement within another if-else statement is called nested if statement. > This is used when an action has to be performed based on many decisio called as multi-way decision statement. ‘The syntax is shown below: s. Hence, it is if (exprl) i if (expr2) statement1; else statement2; , else t if (expr3) statement3; else statement4; 2 Rest of the code; > Firstly, the expression is evaluated to true or false. Only if the expr/ is true then true part statements will be executed where again it checks for expr2 otherwise false part statements are executed, (| Program to select and print the largest of the 3 numbers using nested “if-else” statements. void main() £ int a,b,c; print£("Enter Three Values: \n”, scanf ("td #d td”, 6a, &b, &¢); printf ("Largest Value is: ”) ; if (a>b) t if(a>c) print£(" td", a); else print£(" td", ¢); 2 else t Af (b>c) print£(" $d”, b); else print£(" #d”, ¢); } } output : Enter Three Values: 786 Largest Value is: 8 THE else if LADDER STATEMENT > This is basically a “multi-way” decision statement. > This is used when we must choose among many alternatives. The syntax is shown below: if (expression!) statement1; else if(expression2) statement2; else if (expression3) statement3 else if (expression4) statement4; else default statement5; The expressions are evaluated in order (ie. top to bottom), Ifan expression is evaluated to true, then statement associated with the expression is executed & control comes out of the entire else if ladder For ex, if exprression| is evaluated to true, then statement! is executed, If all the expressions are evaluated to false, the last statement4 (default case) is executed. vvv v vv | default statement J ‘statement Program to illustrate the use of els void main ( ) t int n; printf (“Enter any integer:”) ; scanf("8d”, én) i£(n>0) printf ("Number is Positive"); else if(n< 0) printf ("Number is Negative"); else if(n== 0) printf ("Number is Zero"); else printf ("Invalid input") , Output: Enter any integer: 7 Number is Positive THE switch STATEMENT > This is basically a “multi-way” decision statement. > This is used when we must choose among many alternatives. > Here, choice can be either any integer value or a character. > Based on this integer value, the control is transferred to a particular case-value where necessary statements are executed, During executing, if break statement is encountered, then the control comes out of the switch block. > If the value of the choice does not match with any of the case values (i. valuel, value2, value3) then control goes to default label. > All-case-values must be different. ‘The syntax & flow diagram is shown below: — switch (choice) ¢ case 1: statement; SS break; case 2: statement2; seamen break; case 3: statement3; core eos tatement2 case i: statementi; break; sememanes case N: — statementN; break; deft default: default statemetns; =" } /* Program to simulate simple calculator by performing arithmatic operations*/ #include void main() t int op1, op2, ans; char op; print£("\n Enter an arithmatic expression"); scanf("$d8c8d", 6op1, 0p, 60p2) ; switch (op) f case '+!:ans=opl+top2; print£("\n Sum=td", ans); break, case '~':ans=op1-op2; print£("\n Difference=$d", ans); break; case '*':ans=opl*op2; print£("\n Product=8d", break; ":4£ (op! i case ») print£("\n Division by zero is not possible"); break; 2 ans=op1/op2; print£("\n Quotient=$d", ans); break; case ‘8! :ans=op1top2; print£("\n Remainder=8a",ans) ; break; default :printf, } \n Invalid Operato: } BASIC CONCEPT OF LOOP Let's consider a situation when you want to write same message N times. C language provides a concept called loop, which helps in executing one or more statements up to desired number of times Loops are used to execute one or more statements repeatedly. Every loop statements has three main part in it, ie. Loop initialization, Loop test- condition and Loop update. The flow diagram is shown below: Start vv v Program continues. THE while LOOP A while loop statement can be used to execute a set of statements repeatedly as long as a given condition is true. ‘The syntax is shown below: Loop-initialization; while (test-condition) t Loop-update; statement1; statement2; > Firstly, the expression is evaluated to true or false. > If the expression is evaluated to false, the control comes out of the loop without executing the body of the loop. > If the expression is evaluated to true, the body of the loop (ie. statement!) is executed. > After executing the body of the loop, control goes back to the beginning of the while statement and expression is again evaluated to true or false. This cycle continues until expression becomes false. The flow diagram is shown below: { Test False (exit white tor Expression y [ree Body of white loop Program to display N natural numbers. #include void main() f int isl, n; printf£("\n Enter the N value scanf("$d", &n); while (i<=n) € printf (“éd\t”, i); itt; } } output: Enter the N value 5 2a siyar 5 ‘THE do while STATEMENT. When we do not know exactly how many times a set of statements have to be repeated, do- while statement can be used. The syntax is shown below: Loop-initialization; do € Loop-update; statement1; }while (test-condition) ; > Firstly, the body of the loop is executed. ie. the body of the loop is executed at least once. > Then, the expression is evaluated to true or false. > If the expression is evaluated to true, the body of the loop (ie. statement!) is executed > After executing the body of the loop, the expression is again evaluated to true or false. This cycle continues until expression becomes false. The flow diagram is shown below: Body of loop Test False Expression ~(Exit while loop True Program to find HCF (GCD) and LCM (Euclidian Technique) #include void main() € int a, b, x, y, t, ged, lem; printf ("Enter two integers\n’ scanf("$d8d", &x, &y); bey; while (b ! ged = a; lem (xty) /ged; printf ("Greatest common divisor of éd and ¢d = $d\n", x, y, ged); printf("Least common multiple of td and td = td\n", x, y, lem); , Output: Enter two integers 9 24 Greatest common divisor of 9 and 24 = 3 Least common multiple of 9 and 24 = 72 THE for LOOP > A for loop statement can be used to execute s set of statements repeatedly as long as a given condition is true. The syntax is shown below: for (Loop-initialization; test-condition; Loop-update) t statement1; v Firstly, Loop- initialization is evaluated. It is executed only once. Then, test-condition is evaluated to true or false. If loop-update is evaluated to false, the control comes out of the loop without executing the body of the loop. If test-condition is evaluated to true, the body of the loop (i.e. statement!) is executed. > After executing the body of the loop, loop-update is evaluated. Then test-condition is again evaluated to true or false. This cycle continues until expression becomes false. The flow diagram is shown below: v v v Tattiitzation Program to find the factorial of N number. #include void main() t int i, n, fact=1; print£("\n Enter the N value scanf("8d", én); ; itt) fact=fact*i; for(i=1; ic C Programming for Problem Solving (17CPS13/23): Module IL Santhosh Kumar D K print£("\n Factorial of td = %d", n, fact); } Output: Enter the N value 5 Factorial of 5 = 120 Comparison of looping statements: ‘for loop while loop do...while loop A for loop is used to execute and repeat a statement block depending ona condition at the beginning of the loop. Example for(i=l; i<= ‘Awhile loop is used to execute ‘and repeat a statement block depending on a condition which is evaluated at the beginning of the loop. Example 1s while(i<=10) it i A do...while loop is used t0 execute and repeat A statement block depending on a condition which is evaluated at the end of the loop. Example itt; }while(ic=10); A variable value is initialized at the beginning of the loop and is used in the condition. A variable value is initialized at the beginning or before the loop and is used in the condition. ‘A variable value is initialized before the loop or assigned inside the loop and is used in the condition. ‘A statement to change the value of the condition or to| increment the value of the variable is given at the beginning of the loop. ‘A statement to change the value of the condition or to increment the value of the variable is given at the inside of the loop. "A statement to change the value of the condition or to increment the value of the variable is given at the inside of the loop. ‘The statement block will not be executed when the value of the condition is, false. ‘The statement block will not be executed when the value of the condition is false. The statement block will not be executed when the value of the condition is false, but the block is executed at least once irrespective of the value of the condition. A for loop is commonly used by many programmers, A while loop is also widely used| by many programmers. ‘A do...while loop is used in some cases where the condition need to be checked at the end of the loop. Conditional control statements THE break STATEMENT The break statement is jump statement which can be used in switch statement and loops. The break statement works as shown below: If break is executed in a switch block, the control comes out of the switch block and the statement following the switch block will be executed. If break is executed in a loop, the control comes out of the loop and the statement following the loop will be executed. v vv 04 wntte (test expression) ( statenent/s statenent/s A (Eest expression) ( Le (lest expression) (break breaks > ‘statenent/s Statenent/s > > nite (cere expression); Ly,’ Ly’ for (intial expression; test expression; update expression) ( statenent/s A (eest expression) ( break statenents/ ? ad Program to find the given number is prime or not. #include void main() t int i, n, prime=1; print£("\n Enter the N value"); scanf("$d", én); /2; i++) if( prime == 1) print£("\n Given number dis a prime number”, n); else print£("\n Given number $d is not a prime number", n); } Output : Enter the N value 5 Given number 5 is a prime number THE continue STATEMENT > During execution of a loop, it may be necessary to skip a part of the loop based or some condition, In such cases, we use continue statement. The syntax is shown below: oo [while (test expression) ¢ ‘statenent/s statenent/s AF (Eest expression) ( Af (Rest expression) (continue; continue; ? > statenent/s Statenent/s > > Lp vintte (rest expression): [> for (intial expression; test expression; update expression) ( > The continue statement is used only in the loop to terminate the current iteration, Program to read and add only positive numbers using continue statement. #include void main() t int i=1, num, sum =0; for(i=0; i <5; i ++) print£(" Enter an integer:”); scanf( “8d”, énum); if (num < 0) t printf£("you have entered a negative number \n”); continue ; // skip the remaining part of loop printf ("The sum of the Positive Integers Entered = $d”, } Output : Enter an integer: 10 Enter an integer:-15 You have entered a negative number Enter an integer: 15 Enter an integer: -100 You have entered a negative number Enter an integer: 30 The sum of the positive integers entered = 55 THE goto statement goto statement can be used to branch unconditionally from one point to another in the program. > The goto requires a label in order to identify the place where the branch is to be made. > A label is any valid variable name and must be followed by a colont : ) > The label is placed immediately before the statement where the control is to be transferred. ‘The syntax is shown below: goto label; label: Program to find sum of N numbers using goto statement. #include void main() G int n, num, sum =0; printf ("\n Enter the N value scanf("8d", én); REPEATE: if (n>0) { printf (* Enter an integer:”); scanf( “$d”, énum); sum+=num; goto REPEATE; } print£(" \n Sum =¢d”, sum); } Output : Enter the N value 3 Enter an integer: 10 Enter an integer: 15 Enter an integer: 20 ‘Sum = 45 PROGRAM EXAMPLES 1. Program to find roots of the quadratic equation #include #include void main() t float a,b,c,D,r1,22; print£("\n Enter three coefficients"); scan ("$£%£%£", 6a, &b, &¢) ; i£(a==0/| b==0/| c==0) printf("\n Invalid coefficients try again!! else t = (b*b) ~ (44a*c) ; if ( t printf("\n Roots are equal"); l= (~b)/(2*a); printf ("\n Root1=8f \n Root2=$f \n",rl,r1); } else if(D>0) t printf("\n Roots are real and distinct"); 1=((-b) +sqrt (D))/(2*a); £25 ((-b)-sqrt (D))/ (24a); print£("\n Rooti=sf \n Root2=8f \n", rl, r2); , else t printf£("\n Roots are real and imaginary"); 1=(-b)/(2*a);//Real part r2=sqrt (fabs (D))/(2*a) ;//imaginary part printf ("\n Rooti=s£+i8f \n",rl,r2); printf("\n Root2=8£-i8f \n",r1,r2); } 2. Program to compute binomial coefficients #include define MAX 10 Void main() t int m, x, binom; print£("m x"); for (m= 0; m <= MAX ; ++m) print£("$4d", m); printf ("\n—— m= 0; do t printf ("$2d_ ", m); x = 0; binom while (x <= m) t if(m == 0 || x == 0) print£("84d", binom) ; else t binom = binom * (m ~ x + 1)/x; print£("$4d", binom) ; } waxed; } print£("\n"); m=m+4i; } while (m <= MAX); print£( \a"); } output : dutpur x 345 67 3. Program to Plot Pascal’s triangle #include void main() € int i,j,k,n,¢; printf("\n Enter the limit: ") scant ("6d", &n) ; print£("\n "); for (i=0; i void main() £ int num, temp, rem, rev=0; print£(" Enter a number"); seanf("$d", num) ; Af (num<=0) printf ("Please enter a positive number") else f temp=num; while (num! { rem=nums10; rev=(rev*10) trem; num=num/10; 2 if (temp==rev) printf("\n %d is a palindrome", temp) ; else print£("\n $d is not a palindrome", temp) ; y, } 5. Program to calculate electricity charges #include void main() t int unit; float char char name [30]; printf("\n Enter Consumer Name and number of units consumed\n") scanf ("$s%d", name, gunit); if (unit<=200) charge+=0.8*tunit; else if(unit<=300) charget= (0. 84200) +0. 9* (unit-200) ; else charget= if (charge>400) charge+=(charge*0. 15); print£("\n Consumer Name Number of Units Charges print£("\n$s\t\t\t$d\t\t.2£\n", name, unit, charge); } (0. 8*200) + (0. 9* (unit-200) ) + (unit-300) ; 6. Program to find the square root of a number without using library function. #include void main() £ float n, root, temp=0; print£("\nEnter a number", scant ("8£", én); if (n<0) print£("\nPlease enter a positive number ", else t root=n/2; while (root !=temp) t temp=root ; root=(n/root+root) /2; 2 print£("\n Square root of 8f is %£",n, root); } 7. Program to compute sinx using Taylors series #include #include void main() t int i,degree; float x, sum=0, term, numer, deno; printf£("\nEnter the values in degree"); scanf ("td", degree) ; x=degree* (3.142/180) ; deno=1; i=2; do € term=numer/deno; numer=-numer*x*x; deno=deno*i* (i+1) ; sum=sum+term; it; } while (fabs (term)>=0.00001) ; print£("\nThe value of sin(x) without using library function is Sin (%d)=$£\n", degree, sum) ; print£("\nThe value of sin(x) using library function is Sin (%d)=£\n", degree, sin(x)) ; , 8. Program to display Fibonacci series #include void main() t int i, n, tl = 0, t2 = 1, nextTerm; printf ("Enter the number of terms: ") seanf("$d", &n); printf ("Fibonacci Series: "); for (i = 1; i <= nj +44) t print£("$d, ", 1); next Term = t1 + t2; t1 = £2; t2 = next Term; , Question Bank 1, Explain the Syntax of nested if...else statement. Write a C program to find largest of three numbers using nested if....else statement. 2. Explain the syntax of do-while statement, Write a C program to find the factorial of a number using while loop, where the number n is entered by the user. 3. Write a calculator program in C language to do simple operations like addition, subtraction, multiplication and division. Use switch statement in your program. 4. Write a C program to find the roots of quadratic equation. 5. Explain syntax of while statement. Write a C program to check the given number is palindrome or not 6. Explain break and continue statements with respect to do-while, while and for loop with suitable examples. 7. Print the following series: 1 12 123 1234 8, Explain ternary operator with suitable example. 9. Write a program to compute sinx using Taylors series. 10, Write a program to find the square root of a number without using library function. 11. Write a program to calculate electricity charges. 12, Write a program to find the given number is palindrome or not. 13, Write a program to Plot Pascal’s triangle. 14, Write a program to compute binomial coefficients. 15. Explain break, continue and goto statements with example, 16, Write the difference between while and do-while statement. 17. Write a program to find GCD and LCM of two numbers, 18. Write a program to generate Fibonacci series. 19, Explain looping statements with example. Reference: 1. E Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw-Hill Education. For more Program Examples refer my website: hutps://sites. google.com/view/dksbin/subjects/e-programming-for-problem- solving

You might also like