1 / 30

Loops in C

Loops in C. Loops. You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

bettybsmith
Télécharger la présentation

Loops in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Loops in C

  2. Loops • You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. • Programming languages provide various control structures that allow for more complicated execution paths. • A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages

  3. Loops flowchart

  4. Loop Type & Description • while loop • Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. • for loop • Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. • do...while loop • It is more like a while statement, except that it tests the condition at the end of the loop body. • nested loops • You can use one or more loops inside any other while, for, or do..while loop.

  5. while loop in C • A while loop in C programming repeatedly executes a target statement as long as a given condition is true. • /*condition initialization*/ while(condition) { • statement(s); • //condition update } • /*condition initialization*/ while(condition) • statement; //condition update

  6. While Example: print numbers between an interval, for example [10,20) #include<stdio.h> int main () { • /* local variable definition */ • int a =10; • /* while loop execution */ • while( a <20) • { • printf("value of a: %d\n", a); • a++; • } • return0; }

  7. Display the count of the characters of a sentence ended with an enter #include <stdio.h> int main() { printf("Enter a sentences with a dot at the end>>"); int counter=0; char ch=getche(); while(ch!='\r') { ch=getche(); counter++; } printf("\nThe count of the characters is: %d",counter); return 0; }

  8. Compute #include <stdio.h> int main() { intx,y; printf("Enter x and y to compute pow(x,y)>>"); scanf("%d,%d",&x,&y); intpow=1; while(y>0) { pow*=x; y--; } printf(“pow(%d,%d)=%d”,x,y,pow); return 0; }

  9. The Infinite Loop #include<stdio.h> int main () { • /* local variable definition */ • int a =10; • /* while loop execution */ • while( a <20) • { • printf("value of a: %d\n", a); • } • return0; } #include<stdio.h> int main () { • while( 1) • { • ; • } • return0; }

  10. for loop in C • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. for ( init; condition; increment ) { statement(s); } for ( init; condition; increment ) statement;

  11. for loop in C (cont.) • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. • After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.

  12. Example: Factorial of a Number int n, i; unsignedlonglong factorial = 1; printf("Enter an integer: "); scanf("%d",&n); // show error if the user enters a negative integer if (n < 0) printf("Error! Factorial of a negative number doesn't exist."); else { • for(i=1; i<=n; ++i) • { • factorial *= i; // factorial = factorial*i; • } • printf("Factorial of %d = %llu", n, factorial); }

  13. Factorial with a reverse loop #include <stdio.h> int main() { int x; int fact=1; scanf(“%d”,&x); for (;x>1;x--) { fact*=x; } printf(“%d! = %d“,x,fact); return 0; }

  14. Comma in forexample: A program which computes : #include <stdio.h> int main() { float sum,x; intcounter,num; printf("Enter a number >>"); scanf("%d",&num); for (sum=0,counter=1,x=1; counter<=num; counter++, x*=2) { sum+=1/x; printf("\ncount = %d, sum = %f",counter,sum); } return 0; }

  15. Infinite for inti= 0; for(;;) { • printf("%d“,i++); }

  16. do...while loop in C • Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop. do { statement(s); } while( condition ); do statement; while( condition );

  17. do…while • Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. • If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

  18. do…while example #include<stdio.h> int main () { • /* local variable definition */ • int a =10; • /* do loop execution */ • do • { • printf("value of a: %d\n", a++); • }while( a <20); • return0; }

  19. nested loops in C • C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. while(condition) { • while(condition) • { • statement(s); • } • statement(s); } for ( init; condition; increment ) { • for ( init; condition; increment ) • { • statement(s); • } • statement(s); }

  20. Using nested for to create the below output • #include <stdio.h> • void main() • { • char ch; • inti; • for (ch='A';ch<='G';ch++) • { • for (i=1;i<=7;i++) • { • printf("%c%i ",ch,i); • } • printf("\n"); • } • } A1 A2 A3 A4 A5 A6 A7 B1 B2 B3 B4 B5 B6 B7 C1 C2 C3 C4 C5 C6 C7 D1 D2 D3 D4 D5 D6 D7 E1 E2 E3 E4 E5 E6 E7 F1 F2 F3 F4 F5 F6 F7 G1 G2 G3 G4 G5 G6 G7

  21. Multiplication table for the interval [1,5], using nested while #include <stdio.h> void main() { inti=1,j; while(i<=5) { j=1; while(j<=5) { printf(“%d*%d=%2d ",i,j,i*j); j++; } printf("\n"); i++; } }

  22. Loop Control Statements • Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

  23. Control Statement & Description • break statement • Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. • continue statement • Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. • goto statement • Transfers control to the labeled statement.

  24. Flowchart of break statement

  25. Calculates sum until user enters negative number inti; double number, sum = 0.0; for(i=1;; ++i) { • printf("Enter a n%d: ",i); • scanf("%lf",&number); • // If user enters negative number, loop is terminated • if(number < 0.0) • { • break; • } • sum += number; • // sum = sum + number; • } printf("Sum = %.2lf",sum);

  26. Example: Program to Check Prime Number int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i<=sqrt(n); ++i) { • // condition for nonprime number • if(!n%i) • { • flag=1; • break; • } } if(!flag) printf("%d is a prime number.",n); else printf("%d is not a prime number.",n);

  27. Flowchart of continue Statement

  28. Example: print even numbers between [1,10] using continue inti; for (i=1;i<=10;i++) { if (i%2) continue; printf("%d\n",i); }

  29. goto statement

  30. Example goto: creating a loop using goto #include <stdio.h> int main() { int x=0; loop: x++; if (x<20) { printf("%d\n",x); goto loop; } return 0; }

More Related