3.fybscit Unit III

You might also like

Download as pdf
Download as pdf
You are on page 1of 22
Imperative Programming (F..B.Se.1 >, om, ss vee UNIT - lll TER 5 J) Conditional Statements and Loops @ Ngee —-—_ SyNoPSIS 5.1 Flow Controls (Selection Statements & Iteration Statements] 5.2. Infinite Loop 5.3. Comma Operator 5.4 Jump Statements Questions scanned witn vamsca conona Slatemens and Loopy pesision Making Within a Progeam en'2 iz | Decision is a word which ig i i i normally F option from the available options naw/qnen it gis eoneptis always dog cone which are cbviousy mere one i in a postion # IBF program 80 that it can take devieg reo POe. We si Pampas rad ipee ear ow Pine ser. When you are ging os HS Ovn depending ve to provide he cables 0 fave to ut some code which has to be cease Poet wil ape ete at you wil ions are eval © executed ne you wil sate a by the computer iseltwnerthe waa jet eatin wea. = 5 OLS E given by the user. in C language there = ELECTION STATEMENTS & ITERATION STATEMENTS] ‘when the program is run, the aes rwords that are used to decide the flow of the program. doe by one. This flow can be altered by secea nege oF the sour ile fo the bottom pecific keywords. Statements can be executed multiple times. Some statements are cal i Som led oF on iamet, Conditional statements. They are executed only if a specific A. Selection Statements The selection stater "ment causes the program control to be transferred to a specific flow based upon whether a certain condition is ‘tue or not. Th me 1... The ifstatement ese are also called as conditional statements. Inthese type i is type of statements, if expression is true, then respective block of code is executed. Syntax : if (expression) { statement; } eg /* Pr. 5.1 : Check whether the given number is grater than 5 or not. */ include int main) { int num; . /* Initialize and read in a value for num] */ printf("\nEnter an integer between 1 and I scanf("%d" enum); if (num > 5) printf("You entered Yd which is greater than S\n", num); return 0; } ouTPuT “Enter an integer between 1 and 10:7 You entered 7 which is greater than’ 5 In the above program, if the input value of num is greater than 5 » only then the printf( ) statement will be executed. If input value of num is 4 then no output messaBe will be displayed. So in order to get proper ousput message forall combinations of inputs, i scanned witn CamScann: ming (FYB SEAT; % ere’ nperative Programmina 7) (Sem 2. The if-else statement ee In these type of statements, group of statements are executed expression is false, then else part statements are executed. Syntax : if (expression) { wn expression is true, jp statement; } else { statement2; ie even then the if block printf.) i value of num! is evaluat Toate of num! is evaluate odd then the else block print) In the following program, if the i statement will be executed. if the input value of num statement will be executed. /* Pr. 5.2: Program to check whether the nu #include int main() { int num!; /* Initialize and read in a value for num! */ printf{"\nEnter any number ="); scanf{"%d",&num1); ‘f((oum % 20) { print{("\n %d number is even",num!); } else { printf("\n %d number is odd"num!); mber is even or odd. */ /* Checking condition for even or odd */ OUTPUT Enter any number 5 number is odd 3. Nesting of if-else statement If expression! is false, then expression? is checked and statements are executed iit s 06! expression? also gets failure, then else pait is executed. ‘Syntax : if (expression!) { if (expression2) - ~~ scanned witn FamScanni «egttonal Stteméts and Lope statements; } else { statements; else statements; } eget /* Pr. 5.3 : Program to check whether the number #include int main) { int num|; ositive, negative or zero. */ /* Initialize and read in a value for num! */ printf("\nEnter any number ="); seanf("%d",&num1); iffoum1>0) { printf("\n %d number is positive",num!);, } else iffnum!<0) ‘whether num! is less than 0 */ { printf("\n %d number is negative",num!); 3 else /* num! is 0*/ { printf("\n %d number is zero" uml); } return 0; } /* whether num! is grater than 0 */ OUTPUT Enter any number = 27 27 number is positive /*Pr. 5.4 : Different message to be displayed at various time in a day */ include int main) { float mytime; scanned witn GamScann: ing (FY.B.Se.1.7, wor Cl Mm, ea) ne ' = nitalze and rad in a vale for mytime / | printf("wEnter Time =") scanf("%P,Ae mytime); Fimysime >0)88(mytime <12)) { print("\a Good morning"); y s else if((mytime >=12)&& (mytine <18)) { print("\n Good Afternoon"); } else if{(mytime >=18)&& (mytime <24)) { printf("\n Good Evening"); } else \ print("\n Not valid time"); y return 0; } OUTPUT Enter Time = 2 Good Morning 4, The Switch Statement Switch case statements are used to execute only specific case statements based on thd expression. j ‘Syntax : switch (switch_expression) { cease constant-expression1: statement]; break; case constant-expression2: statement2; break; case constant-expressionN: statement; break; default: statément; | scannea witn CafnScann | sis bt Stents ord Loopy +: Program to aul iat opel usagi - NeF and display the month name. It number include int main ( int numt; > nitialize and read in a value for num} */ printf("Enter month number: *); scanf"\nY%ed",&numt); switch(num!) { cease 1 : print{{"January"); break case 2: printf("February"); bre case 3: printf("March"); break; case 4 : printf("April"); break; case 5: printf("May"); break: case 6 : printf("June"); break; case 7: printf("July"); break: case 8 : printf("August”); break; case 9 : printf("September"); break; case 10 printf(* October"); break; case 11 : printf("November"); break; exe breaks default : printf("lnvalid Input”): exil(0), i return 0; ) OUTPUT Enter month mumber : 3 March : 3 ll * ren" a ‘int{("December”); scanned witn Camscann ow ina rope TS TI Sem. . ime. Pr. 5.6: Program to enter character from the user and include int main) { char charl; /* Initialize and read in a value for char! */ print{{"Enter colour char (rgb) of (RGB): ")s seanf{"\n%c",&echarl); switch(charl) display the colour nm case 'R’ printf("RED Colour"); break; case's! case printf("GREEN Colour"); break; case case’ print{("BLUE Colour"); break; default: printf("Invalid Colour Input exit(O); } return 0; } ouTPUT i Enter colour char (rgb) or (RGB) : GREEN Colour B. Iteration Statements ‘We can create loops by using the iteration statements, Iteration statements causes embedded statements to be executed a number of times, subject to the loop-termination criteria, Thee statements ae executed in order, except when a jump statement is enceuntond 1, The While Statement . For repeating C statements tion i - fe ees Whiles a condition is tue,the while provides the necesssY Syntax : while (expression) { scanned witn FamScann: ree. 63 61: Program to print 1 to 10 numbers * (jude aa int main() { int noms umll; wile(oum<=10) vent %d" num); uml; } return 0; } OUTPUT 12 3 4 5 6 7 8 9 10 2, The do-while statement The do {} while statement allows a loop to continue whilst a condition evaluates as TRUE (gon-2er0 value). Syntax : do { statement; } while (expression); Pr. 5.8 : Program to use do-while loop */ include int main { int num1; numi=11; do { Printf("\t %d",num); mumi++; }while(num1<=10); return 0; 4 OurPuT nN scanned witn GamScann Imperative Programming PLESEAAT) (ony of ree Difference between while and do-while The do statement is similar to the while statement except end of the body of the loop only. If we want to execute the body of of the condition, then we have to use do construct with while. 3. The for Statement ‘The “for loop” loops from one number to another number and each time. Syntax : for (initialization; condition; step) { Statements; } where © Setting a loop counter to an initial value.( initialization) © Testing the loop (condition) © Increasing/ decreasing the value of loop counter(step) eg: Pr. 5.9 : Program to print 1 to 10 numbers */ #include {nt main( ) { int mum; for(num1=1;num1<=10;num1++) { rintf("\t 9d" num); } return 0; that its termination condition is ap the loop at least once, regardteg | increases by # specified valu, 12 3'e 5 6 7 oe os /* Pr. 5.10 : Converting lower case string to upper case letters. */ #include #include /*includes character handling functions.*/ int main() { char letter[80); int tag, count; printf("Press * to terminate loop \n while((letter[0] = getchar( )) !="*) { /* read in-a line of text */ for(count = 1; (letter{count] = getchar( )) tag = count; /* display the line of text */ in +Fcount); | SINE Camscann Re oS a Lope for(count = 0; count < tag; res e ; 18; +count) putchar(toupper(letter{count])); ; printft"\n"); } ) ourruT press *t0 terminate Loop yashashree YASHASHREE vedshree VEDSHREE Let us see some programs on conditions and flow controls. ‘npr. 5.11 : Program to find the factorial of a number.*/ include int main() ( int num, fact, i; fact=1; /* Initialize and read in a value for num */ print{("\nEnter any number ="); seanf{"%d",Senum); *Calculating factorial*/ for (i= 15 i<= num; i+) { fact = fact * is } print*Factorial of 6d = edn”, mum. fact; return 0; } OUTPUT Enter any number =4 Pr, $.12 : Progr Factorial of 4 = 24 am to check whether the entered number is prime or not.*/ #include int main() { int num,i.ps scanned witn GamScann: sing (FYB. Imperative Program sa'0 i 1+ Initialize and read in a value i printf(*Enter a number"); | scanf("%d" enum); for num */ while(i <= num/2) { iffnum’ iffp=0) printf("Prime Number"); else printf("Not Prime Number"); return 0; } OUTPUT Enter a number: 5 Prime Number /*Pr. 5.13 : Program to find the largest of three numbers. */ #include int main() { int num1, num2, num3; (/* Initialize and read in a value for num] , num2, num3 */ print{("\nEnter any three number =\n"); seanf("%d%d%d",&num| ,&num?,&num3); if(num1>num2 && num1>num3) { printf("in %d number is grater number",num1); } else if(num2>num1 && num2>num1) | ( 4 printf("\n %d number is. grater mumber,num?); | ) | else Z | | j f printf("in %d number is grater'number",num3); scannea witn varhScann itonel Stemens and Lops } retim 0; } output : Enter any three number =12 3 4 44 number is grater number Pr. $.14 : Write a program to find the sum of squares of digits of a number. */ Hinclude int main( ) { int num,i.sum = 0; /* Initialize and read in a value for num */ printf("\nEnter number ="); scanf("%d",&num); Calculating sum of square of digit*/ for(i=1;i<-num;i+) sum = sum:(i * i); } printf("\nSum of square of digits = %d" sum); return 03 } ouTPUT Enter the number = 3 Sum of square of digits = 14 Pr, 8.1 #include int main() print{("Enter an integer :\n "); seanf("%d", &num); /*Calculating reverse number*/ while(num != 0) { {. rem = numY%10; +: Program to reverse the digits of an integer. */ scanned witn Gamscann: perv Programing PXBSEIT) oy es are" suum = sum 10+ rem; nium /* 10; } print{("Reversed Number = %d" return 0; } ourrur Enter an integer : 2m Reversed Number = 1127 /* Pr, 5.16: Program to find the sum of numbers from 1 to 100.*/ #inelude int main() { int ium = 0; ‘/*Caleulating sum of 1 to 100 nurnbers*/ sum = sum+i; } printf("\nSum of number from 1 to 100 =-%d",sum); return 0; 3 ouTruT ‘Sum of number from 1 to 100 = 5050 /*Pr. 5.17 : Write a programs to print the Fibontcci series, */ include int main( ) printf("\n Enter number ="); seanf("%d",Senum); Prinf(\n Fibonacci series up to %d term \n "um; /* By default Fibonacci series starting values 0 and 1#/ printf("%d\t%d",,b); -/*Remaining Fibonacci series values calculating */ for(i=3;i<=num;i++) 3 a scanned witn CamScanni ystems ad Loops won eat; print" W6d".0); ab; be } return 0; } ouruT ter number = 5 ivonacei series upto S term Rit] 12 3 op. S18 : Program to find the reverse of a number.*/ include intmain( ) { int num, rum = 0, rem; /* Initialize and read in a value for num */ print{("Enter an integer: "); scangi("%od", &num); Calculating reverse number*/ while(oum != 0) i rem = num%10; ‘mum = mum*10 + rem; sum =num/ 10; } printf("Reversed Number = %d",mnum); return 0; } ourrur Enter an integer: 2711 Reversed Number = 1172 "Pr. 5.19 : Program to find whether a given number is palindrome or not.*/ include int main( ) { int numa, mum 0, rem, temp; /* Initialize and read in a value for num */ Printf("Enter an integer: "); 6) “BSc. (.T.) Imperative Programming (Sem-1) Cae 0 Scanned witn va | | Scann . 1 ue ee Imperative Programming (FYBSe-1.7, scanf("%d", Senum); ‘temp=num; ‘calculating reverse number */ while(num != 0) { rem = num%10; mum = mum*10 + rem; num =num/ 10; } : /*Checking palindrome number*/ if(temp==mum) { printf("%d is a palindrome number"temp); } else { printf("%6d is not a palindrome number",temp); } return 0; OUTPUT Enter an integer: 1221 1221 is a palindrome number /*Pr. 5.20 : Write a program that solve the quadratic equation */ #include #include int main( ) { float a, b,c, x1, x2, determinant, realPart, imaginaryPart; print{("Enter coefficients a, b and c: "); scani("%6f%t%t" Sa, 8b, 8c); determinant = b*b - 4*a*c; if (determinant > 0) { x1 = (b+ sqrt(determinant)) / (2a); x2 = (-b~ sqrt(determinant)) / (2*a); printf("Roots are real and different."); printf("\n x1 = %.30%x1); printf("\n x2 = %.31",x2); } else if (determinant = 0) ia. { Scanned witn CamScann a I siotements and Loops printf("Roots are real and same."); x1 = (b+ sqrt(determinant)) / (2*a); printf("\n x1 = %.36" x1); print("\n x2 = %.38"x2), else realPart = -b/(2*a); imaginaryPart =sqrt(-determinant)/(2*a); printf("\n Roots are complex and different."); printf("\n x1 =%.3 +%.3fi" realPart, imaginaryPart); printf("\n x2 =%.3. } return 0; } ourruT Enter coefficients a, b and c: 4 5 1 Roots are real and different. xl =-0.250 -%.3fi " realPart, imaginaryPart); wee a Pr, 5.21 : Program to check whether the entered number is Armstrong or not */ ¥include int main( ) { int num, i, sum=0,temp; /* Initialize and read in a value for num */ printf("Enter a number: "); seanf("%d", enum); temp=num; /*Calculating sum of cubes*/ while(aum!=0) { isnumi%10; num=num/10;. sum=sum-+(i*i*i); } /*Checking for Armstrong number*/ if(sum—temp) { Printf("%d is an Armstrong number",temp); scanned with Camscann 4 . ive Programming (F.Y.B.Se.1-7, n : a'r's’ Imperative: hy i else C i printf('%d is not an Armstrong number",temp); } return 0; ourPuT Enter a number: 153 153 isan Armstrong number Pr, §.22 : Program to count the digit in a number */ #include {nt main( ) { int mum; int count=0; 1 Tnitialize and read in a value for num */ printi("\wEnter an integer ‘\n "); scanf("%d", num); 1 counting the digits in a number */ while(aum!=0) { ‘num=num/10; +reount; } printf("Number of digits : %d",count); : return 0; i } ourpur Enter an integer: 1322 ‘Number of digits : 4 /*Pr, 5.23 : Programs on different patterns. */ ‘A. Print Following Pattern 1 12 123 #include int main) scanned witn CamScann: e jqutEnter the number of rows: ert: jp for used as ro foie oe HD) ise */ ( peintt"26d Ds y print"); ) retum 0; ' ovTruT Enter the number of rows: 3 1 12 123 Print Following Pattern 12345 1234 13 n 1 Finclude forijmlijcnigit+) 1 Printf(“¥"j)s 1 printfi"'n"); ) tetum 0; aes B scanned with Camscann ive Programniing (F.Y.B So. E ud ves a Gem, | C. Print Following Pattern 1 21 321 4321 54321 include int main() { inti, js for(i=1;i<=5;i++) { forg=ij>=1j—) { printf("%d"j); : ; printf("\n"); | 3 return 0; | ouTPUT ; | 2 321 | 821 | 4321 D. Print Following Pattern 1 1 234 56789 lude int main() scannea witn amScann ree = printf("\n"); } | | } ourPUT 1 234 56789 (s2_ INFINITE LOOP This can be also referred as endless loop. It is a sequence of instructions in a computer progam which will never terminate, either due to the loop having no terminating condition, having ‘one that can never be met, or one that causes the loop to start over. [53 COMMA OPERATOR “The comma operator ( ) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value and type. ‘The use of the comma operator (,) as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator. eg int a,b,c; void add(int a,int b) forfi=0j0;i<5:i-+) Pr. 5.24 : Use of comma operator in for loop*/ #include int main( ) ( intij, for(i=0 j=0;i: { Printf("\nValue of J: %d"3)s ity scanned witn Camscann srogramming (F-¥.B Se. imperative Pr Tay, , OUTPUT Value of Value of J: Value of Value of 1:3 Value of [5.4 JUMP STATEMENTS ‘which cause an immediate transfer of Branching is performed using jump statements, program control. . he ik ‘ Te aa —_ by while, for or sig statements, ‘Syntax : break; 2, The continue statements ‘The continue statement is used to e the loop. It can be used in combination with for and while skip a part ofthe loop and continue with the next iterating statements. Syntax: continue; eg. Program to demonstrate use of break and continue statement. 3. The goto statement “The goto statement transfers the program control directly to a labeled statement. Syntax: As 2010 label; label: statements; } Eg. /*Pr, 5.25 : Use of infinite loop, break, continue and goto sts | include daha int main( ) { int n; i for (53) /* infinite loop */ scanned witn FamScann: jpnot Statements and Loops : oe'8" u printf("Enter any number seanf("%d, 8); if(@—=35) goto ap; /* use of goto y RE) ‘goto statement*/ continue; /* use of conti a Kansan tinue statement */ break; . /* use of break statement */ . printf("Inside loop ");, } ap: ' printf("Outside loop "); return 0; ne OUTPUT Enter any number: 2 Enter any number: 3 Outside loop [ QUESTIONS 1, What is meant by branching? 2. Whatis meant by selection? 3, What is meant by looping? Describe two different forms of looping. | 4, Describe the two different forms of if - else statement. How do they differ? | 5. How isthe execution ofa while loop tenminated? | 6. What is the purpose of the do - while statement? “How does it differ from the while statement? | 1. What is the minimum number of times that a do - while loop can be executed? Compare with a while loop and explain the reasons for the differences. 8. Describe for loop with suitable example. What is the difference between ‘break’ and ‘continue’ statement? | 10. Whats the use of ‘eo to’ statement? | 11. Are there any restrictions that apply | program? Fea wit fo te perp of tn seems Geert? WAR control statement does the comma | operator usually appear? . 13, What is the use of switch state . wee Give example. to where control can be transferred within a given C ment? Give example. scanner amscann

You might also like