Nesting Loops, Factorial
Nesting Loops, Factorial
2.
3.
include <stdio.h> int main() { int k, j, i,l, m, n; for(i=0; i<1; i++) for(k=1; k<9; k++) printf("%d", k);
4. 5. 6.
7.
8. 9.
10.
11. printf("\n\n");
12.
13. for(j=2;
14.
15. printf("\n\n");
16.
17. for(l=3;
18.
19. printf("\n\n");
20.
21. for(m=4;
22.
23. printf("\n\n");
24.
25. for(n=5;
26. 27.
28. return
29.
0;
30. }
NESTED LOOP
These loops are the loops which contain another looping statement in a single loop. These types of loops are used to create matrix. Any loop can contain a number of loop statements in itself. If we are using loop within loop that is called nested loop. In this the outer loop is used for counting rows and the internal loop is used for counting columns SYNTAX:for (initializing ; test condition ; increment / decrement) { statement; for (initializing ; test condition ; increment / decrement) { body of inner loop;
} statement; } PROGRAM
#include void main ( ) { int i, j; clrscr ( ); for (j=1; j<=4; j++) { for (i=1; i<=5; i++) { printf (*) } printf (\n); } getch ( ); }
recursive factorial The classic factorial function, recursively defined in terms of itself. iterative factorial The classic factorial function, implemented as a while() loop.
printf( "Enter n: " ); scanf( " %i", &N ); f = factorial( N ); printf( "factorial of %i is %i\n", N, f);
return 0; }
} return fact; }
printf( "Enter n: " ); scanf( " %i", &N ); f = factorial( N ); printf( "factorial of %i is %i\n", N, f);
return 0; }
Factorial Function #include <stdio.h> #include <conio.h> long int factorial(int n); void main() { int n,i; float s,r; char c; clrscr(); repeat : printf(" You have this series:- 1/1! + 2/2! + 3/3! + 4/4! .."); printf(" To which term you want its sum? "); scanf("%d",&n); s=0; for (i=1;i<=n;i++) { s=s+((float)i/(float)factorial(i)); } printf(" The sum of %d terms is %f",n,s); fflush(stdin); printf (" Do you want to continue?(y/n):- "); scanf("%c",&c); if (c=='y') goto repeat; getch(); }
Factorial
[edit]
Exercise 3.2
Write a program to calculate the factorial of a given integer. The integer should be inputted from the keyboard. Investigate what the largest number for which factorial can be correctly calculated is. Modify your program so that it rejects an inputted number that is too large and demands a new value. [edit]
Solution
#include <stdio.h> #include<stdlib.h> int main(void) { // program to calculate factorial of integer inputted from keyboard long int i,j,result; i=-1; // first get a positive integer while (i<0) { printf("Input a positive integer:"); // note no \n scanf("%d",&i); // the & is needed } // now calculate the factorial result = 1; for (j=i;j>=1;j--) result = result*j; printf("%d! = %d\n",i,result); system ("pause"); return 0; }
For the second part of the problem, the while condition will have to be modified to stop integers greater than 13, i.e.