0% found this document useful (0 votes)
4 views26 pages

CPS Module II

Module II covers managing input and output operations, conditional branching, and loops in programming. It explains various types of statements, including decision-making and looping constructs, alongside examples of I/O functions like scanf() and printf(). The module also highlights the importance of control structures in altering the flow of a program based on conditions.

Uploaded by

Thara DRTTIT
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views26 pages

CPS Module II

Module II covers managing input and output operations, conditional branching, and loops in programming. It explains various types of statements, including decision-making and looping constructs, alongside examples of I/O functions like scanf() and printf(). The module also highlights the importance of control structures in altering the flow of a program based on conditions.

Uploaded by

Thara DRTTIT
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Module II Managing Input and output operations, Conditional Branching and Loops STATEMENT > A statement is also called instruction. > As the name indicates, instruction is used to instruct computer to perform a particular task like adding two numbers reading data from keyboard. Example: sum=atb; scanf ("sd ", &n); In, the semicolon (;) is a statement terminator. Compound Statement or Block: ‘The sequence of statement enclosed within a pair of braces { and } is called a compound statement, Example: { a=l*b; printf("area =8d", a); 2 Managing Input and output operations ‘There are 2 types of I/O Functions as shown below: Console Input/Output functions ] Formatted functions ‘Unformatted functions Type | Input | Ourpur Type | Input | Output char | seanfi) | printf() char [eeteh() | puteh() getche() | putchar( ) getchar() int | seanft) int z = float | scanf() float = 5 String | seanfi) | printf) 0) __| puro) UNFORMATTED VO. Unformatted 1/0 refers to an /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= getchart ); Example: Writing a character putchar( ): > Displays a character stored in the memory-location on the screen, Syntax ‘putchar(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(); putchar(*\n’); putchar (x) ; J output: enter one letter terminated by ENTER key a a Disadvantage of Unformatted 1/0 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 ete. 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 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: scanfi"od %f %e", &x, &y, &z); Table 4.2 Commonly used scant Format Codes 1} = ast “he folowing eters may be used as prefix for certain conversion characters. for short integers | forlong integers or double for long double ina ated > A scanf( ) always contains a control string or format string in quotation marks. > Each value to be printed needs a conversion specification like Sd 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 (ie, display) in a specified format. Syntax: printf(“ControlString” li of. les or express Example printf("%ed %ef Se", x, y, 2.95 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 Yod 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 éxpressions to be printed, commas are used to separate them form the control string and each other. vv Table 4.3 Commonly used printf Format Codes print a single character print a decimal integer prin a floating point value in exponent form print a floating point value without exponent print a floating point value either e-type or f-type depending on print a signed decimal integer print an octal integer, without leading zero printa sting print an unsigned decimal integer ___| print ¢ hexadecimal integer, without leading Ox VARIATIONS IN OUTPUT FUNCTION = Table 4.4 Commonly used Output Format Flags (Output is leftjustified within the field. Remaining field will be blank. + or — will precede the signed numeric item Causes leading zeros to appear. Causes octal and hex items to be preceded by O and Ox, respectively. Causes a decimal pointto be presentin all oating pointnumbers, even itis whole number. Also prevents the truncation of trailing zeros in g-type conversion. # (with 0 oF x) # (with e, for g) Format printt-%7.4t-y) printt(“%67.27.y) print(-96-7.2F,y) printr36rsy) printf("%10.2e",y) print("%11.46",-y) printf(-%-10.26",y) printr%e"y) \ 1 - | specication | 1a) obans + (sTe [w]e] %20s GES sin cate] [+i4 %20.108 Tr I NpeTwl_ [evel eal et | 58 (wlelw] JoE >TELL ti %-20.108 [NJE[W] [> [anise sale [eet we nfe lw] fo Ts[Tefotol +) Format Output ai printf(“%d", 9876) 9 8 Zz 6 4 printf(“%6d", 9876) 9[8|[7]|6 4 printf("%2d", 9876) 91/8 [7|6 printf(“%06d" 9876) 9[s[7[é| printf("%06d" 9876) o[o,[s|,;e|7|eé CONTROL STRUCTURES > A program is nothing but the execution of sequence of one or more instructions. 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. Decision making statements i. if-statement ii, iffelse statement iii, nested if statement iv. else if ladder ¥. switch statement 2. Loop control statements i. while loop ii, for loop iii, do-while loop 3. Conditional control (jump) statements i. break statement ii, continue statement 4. 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 gi > The following flow diagram shows how conditions work in C. n conditions. 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) t True part statement; 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. The flow diagram is shown below: false statement rest of the code Program to illustrate the use of if statement. #include void main() { int n; printf ("Enter any non-zero integer: \n”) ; scanf("$d”, &n); if (n>0) printf ("Number is positive number ”); 4£(n<0) printf ("Number is negative number ”) J Output : Enter any non-zero integer: 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) £ True part Statement1; } else f False part Statement2; , 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 . true << expression - — r Ys, statement statements rest ofthe code Program to illustrate the use of if else statement. #include void main() é int n; printf("Enter any non-zero integer: \n”) ; scanf("$d”, &n) if (n>0) printf (“Number is positive number”) else printf ("Number is negative number”); J Output Enter any non-zero integer: 7 Number is positive number THE nested if STATEMENT > Anif-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 decisions. Hence, it is called as multi-way decision statement. The syntax is shown below: if (expr) t if (expr2) statement1; else statement2; } else f if (expr3) ‘statement3; else statement4; 2 Rest of the code; > Firstly, the expression is evaluated to true or false. Only if the expri is true then true part statements will be executed where again it checks for expr? otherwise false part statements are executed. \ ™ ZS me \ fae 7 This is basically a “multi-way” decision statement. > This is used when we must chooseamong many alternatives. The syntax is shown below: if (expression1) statement1; else if (expression2) statement2; else if (expression3) statement3 else if (expression4) statement4; else default statements; ‘The expressions are evaluated in order (ie. top to bottom). If an 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. VvvvYY If all the expressions are evaluated to false, the last statement4 (default case) is executed. 7s oS Statements Next starement Program to illustrate the use of else-if-ladder statement. void main ( ) t int n; printf("Enter any integer:”) ; scanf("$d", &n) if(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"); 2 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 (ie. valuel, value2, value3) then control goes to default label. > All case-values must be different. ‘The syntax & flow diagram is shown below: switch (choice) t case 1: statement1; Soression break; case 2: statement2; ot) break; case 3: statement3; [oa break; statement case i: statementi; break; 03 FO emens case N: statementN; break; <<< default: default statemetns; Statement| /* Program to simulate simple calculator by performing arithnatic operations*/ #include void main() t int op1, op2, ans; char op; print£("\n Enter an arithmatic expression"); scanf ("$dictd", €op1, 6p, 6op2) ; switch (op) t case '+ \S=opl+op2; printf ("\n Sum=$d", ans) ; break; :ans=op1-op2; print£("\n Difference=%d", ans) ; break; tans=op1*op2; printf ("\n Product= break; £ (oP! d", ans) ; 0) f print£("\n Division by zero is not possible"); break; , ans=op1/op2; print£("\n Quotient=$d", ans) ; break; case '8':ans=opltop2; print£(""\n Remainder= break; :print£("\n Invalid Operator") ; a", ans); default } } 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 repeatedh > 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 > 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) f Loop-update; statement; 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. vv > 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: 1 Test False (exit while loop Expression free Body of white i LJ Program to display N natural numbers. #include void main() t aint i=1, n; print£("\n Enter the W value"); scanf("$d", &n); while (i<=n) f printé("sd\t", i); itt; D Output: Enter the N value 5 12 3 4 «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; Jwhile (test-condition) ; > Firstly, the body of the loop is executed. i.e. 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. statementl) is executed > After executing the body of the loop, the expression is again evaluated to true or sion becomes false. false. This eycle continues until expre: The flow diagram is shown below: == sation ] ‘ Test False /- Expression (Exit white 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("$did", &x, &y); a=x; bey; while (b ! 0) = b; zatb; ty Se ged = a; Jem = (x*y)/ged; printf ("Greatest common divisor of 8d and #d = %d\n", x, y, ged); printf ("Least common multiple of $d and 8d = d\n", x, y, lem); 2 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) { statement1; vvyv v v Fi 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 (ie. 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. stly, Loop-initialization is evaluated. It is executed only once. ‘The flow diagram is shown below: Program to find the factorial of N number. #include void main() { int i, n, fact=1; print£("\n Enter the N value"); scanf("$d", &n); for (i=l; i nite (tote expression) L,: L,’ for (Antiat expression; test expression; update expression) ( seatonent/s Af (east expression) ( breaks statenents/ ) L, Program to find the given number is prime or not. #include void main() { int i, n, prime: printf("\n Enter the N value"); scanf("$d", &n); for (i=2; ixen/2; itt) € if (n8i == 0) } if( prime =: f prime=0; break; } 1) print£("\n Given number 8d is 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 necess ‘ary to skip a part of the loop based on some condition. In such cases, we use continue statement > The continue statement is used only in the loop to terminate the current iteration. ‘The syntax is shown below: 4 [—Pwnile (Rese expression) ( ‘seatenent/s statenent/ AF (East expression) ( 4€ (cost expression) (> continue} continues ‘Statenent/s ) ) Lipcniie (tose expression); for (Antial expression; test expression; update expression) ( EF (eet expression) ( _ Seatenents/ > 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 +4) t printf(* Enter an integer: scanf( “sd”, énum) ; if (num < 0) £ printf("you have entered a negative number \n”); continue ; // skip the remaining part of loop } sum=sum+num; , printf ("The sum of the Positive Integers Entered = $d”, sum); 2 output: Enter an 10 Enter an 015 You have entered a negative number Enter an 15 Enter an -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 colon( : ). > The label is placed immediately before the transferred. The syntax is shown below: fatement where the control is to be goto label; Program to find sum of N numbers using goto statement. #include void main() t int n, num, sum print£("\n Enter the N value"); scanf("$d", &n); REPEATE: if (n>0) t printf (" Enter an integer:”) scanf( “8d”, énum); sum+=num; goto REPEATE; 1 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, 11,12; print£("\n Enter three coefficients"); scanf ("$£8£8£", 6a, &b, &c) ; 4£(a==0/| b==0// c==0) print£("\n Invalid coefficients try again!!"); else f (b*b) - (4*a*c) ; 4 £(D==0) f print£("\n Roots are equal"); xl=(-b)/ (24a); print£("\n Root1=$£ \n Root2=tf \n",r1,r1); i; else if(D>0) f print£("\n Roots are real and distinct"); (-b) +8qrt (D)) / (24a) ; £2=((-b)-sqrt (D))/ (24a); print£("\n Root1=$f \n Root2=%f \n",r1,r2); , else t print£("\n Roots are real and imaginary"); -b)/(2#a) ;//Real part sqrt (fabs (D))/(24a) ;//imaginary part print£("\n Root1=8£+i8£ \n",r1,r2); print£("\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£(" mx"); for (m = 0; m <= MAX ; ++m) print£("$4d", m); print£("\n m= 0; do t print£("$2d_", m); x = 0; binom = 1, while (x <= m) t if(m == 0 || x == 0) print£("$4d", binom); else t binom = binom * (m- x + 1)/x; printf("$4d", binom) ; etd , print£("\n", m=m+1; , while (m <= MAX); printf ("~ ) output: Durpur mx 2 4 3. Program to Plot Pascal’s triangle #include void main() t int i, j,k,n, ¢7 print£("\n Enter the limit: "); scanf("$d", én) ; printé("\n for ( t yj ken~i ; kt++) printe(" "); } fox (5j=0; J<=i; j++) t print£(" 8d ",c); = (e* (G-5)/ (G41); 4 Print£("\n"); } 4. program to find the given number #include void main() s palindrome or not t int num, temp, rem, rev=0; print£(" Enter a number"); scant ("$d", num); if (num<=0) printf ("Please enter a positive number"); else t temp=num; while (num! =0) € rem=num?10; rev=(rev*10) +rem; num=num/10; } if (temp==rev) print£("\n $d is a palindrome", temp) ; else print£("\n $d is not a palindrome", temp) ; } } 5. Program to calculate electricity charges #include void main() t int unit; float charges: char name [30]; printf("\n Enter Consumer Name and number of units consumed\n"); scanf("Ss%d", name, gunit) ; if (unit<=200) charge+=0. 8*unit; else if (unit<=300) charget= 00; (0. 8*200) +0. 9* (unit-200) ; else charget= Af (charge>400) charge+=(charge*0.15); print£("\n Consumer Name Number of Units Charges"); print£("\n$s\t\t\td\t\ts.2£\n", name, unit, charge) ; J (0. 8*200) + (0. 9* (unit-200) ) + (unit-300) ; 6. Program to find the square root of a number without library function. #include void main() t float n, root, temp=0; print£("\nEnter a number") scanf ("$£", én); 4f(n<0) print£("\nPlease enter a positive number " else while (root! f temp=root; root=(n/roottroot) /2; } print£("\n Square root of %f is 8£",n, root); } emp) 7. Program to compute sinx using Taylors series #include #include void main() t int i, degree; float x, sum=0,term, numer, deno; print£("\nEnter the values in degree"); scanf ("id", °ree) ; x=degree* (3.142/180) ; numer=x; deno=1; =2; do f term=numer/deno; using deno=deno*i* (i#1); sum=sumtterm; 41; , while (fabs (term) >=0.00001) ; print£("\nThe value of sin(x) without using library function is Sin ($d) =8£\n", degree, sum) ; printf("\nThe value of sin(x) using library function is Sin (%d)=8£\n", degree, sin(x)); p 8. Program to display Fibonacci series #include void main() t int i, n, tl = 0, t2 = 1, nextTerm; printf ("Enter the number of terms: "); scanf("id", &n); print£ ("Fibonacci Series: "); for (i = 1; i <= nj +4) { print£("$d, ", t1); nextTerm = t1 + ¢: tl = t2; 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 givenitimber 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 websit hitps://sites. [Link]/view/dksbin/subjects/e-programming-for-problem- solving

You might also like