Skip to main content

Posts

Showing posts with the label While Loop

Find the Factorial of a number

Summary: Factorial is represented using '!', so five factorial will be written as (5!),n factorial as (n!). n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1. Using While Loop #include<stdio.h> void main() { int a,f,i; printf("Enter a number: "); scanf("%d",&a); f=1; i=1; while(i<=a) { f = f * i; i++; } printf("\nFactorial of %d is: %d",a,f); } Using For Loop #include<stdio.h> void main() { int a,f,i; printf("Enter a number: "); scanf("%d",&a); f=1; for(i=1;i<=a;i++) f = f * i; printf("\nFactorial of %d is: %d",a,f); } Using Recursion #include<stdio.h> int fact(int); int main(){ int num,f; printf("\nEnter a number: "); scanf("%d",&num); f=fact(num); printf("\nFactorial of %d is: %d",num,f); return 0; } int fact(int n){ if(n==1)

Spiral Matrix

#include <stdio.h> #define R 3 #define C 3 void spiralPrint(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { printf("%d ", a[k][i]); } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { printf("%d ", a[i][n-1]); } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { printf("%d ", a[m-1][i]); } m--; } /* Print the first column from the remaining columns */ if (l < n)

Print the Multiplication Table

#include<stdio.h> void main() { int x=1,num,res; printf("Enter a Number : "); scanf("%d",&num); while(x<=10) { res=num*x; printf("\n%d x %d = %d",num,x,res); x++; } } Output   Print   Download Code Output Enter a Number : 6 6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36 6 x 7 = 42 6 x 8 = 48 6 x 9 = 54 6 x 10 = 60