Вы находитесь на странице: 1из 4

C programs Note: // Comment used to write comment, not executed. \n --- Newline, prints text goto next line.

. Eg: printf(\n); \t --- Tab space , prints 5 spaces where \t is used. printf(\t); getch() can be used at last line of program. Optional. Data types are int , float, char, double. Variables of various data type %d for int , %f for float, %c for char, %s for String(char array), %lf for double int r=5; float pi=3.14; printf( r = %d , pi = %f \n , r, pi); -----------------------------------------------------------------------printf( Hello \n world); - Prints output as Hello World ----------------------------------------------------------------------Condition statement is if . Execute any one set of statements based on condition. if( condition is true) if (n>0)
{ }

C program for to check prime number or not


Prime number logic: a number(n) is prime if it is divisible only by one and itself(n). So, a number, say 6 is not a prime, if it is divisible by 2 or 3 or 4 or 5 , => 2 to n-1. For checking whether number is divisible by 2 to n-1 using for i loop. (n%i) gives reminder, if n is not a prime, then remainder is zero. Say, for number 6, 6%2 is 0, 6%3 is 0. Remember two is the only even and also the smallest prime number. First few prime numbers are 2, 3, 5, 7, 11, 13, 17....etc. To print prime, we need to check whether i is equal to n. as , if n is prime, for loop fully executes till i is n,say n=7. We need 2 variables n, i declared as int (integer).

Execute statements true condition else //condition is false


{

printf( positive number); else printf( negative number);

Execute statements false condition


}

------------------------------------------------------------------------

Looping for loop format is for (index = start_value; index < end_value; index += increment_value ) for(i=1; i<=10; i++) - counts i from 1 to 10. All statements inside for i loop is executed 10 times. Equivalent to count x = 1 to 10 ---------------------------------------------------------------------------for(j=1; j<=10; j=j+2) - counts variable j from 1 to 10, only odd numbers, 1,3,5,7,9. All statements in for j loop executed only 5 times as j values 1,3,5,7,9.
----------------------------------------------------------------------------------

#include<stdio.h> void main() { int n, i; printf("Enter a number to check if it is prime "); scanf("%d",&n); for ( i = 2 ; i <= n - 1 ; i++ ) { if ( n%i == 0 ) { printf("%d is not prime.\n", n); break; } } if ( i == n ) printf("\n %d is prime \n", n); } Output: Enter a number to check if it is prime 7 7 is prime.
To print all primes between 2 to n. Prime num between 2 to 10 are 2,3,5,7. 1st for loop to use numbers from 2 to n. 2nd for loop to check given number is prime, by dividing it by 2 to n-1. In 2nd for loop, condition can be i<=n-1 or i<n , both are same. #include<stdio.h> void main() { int n, i = 3, num; printf("Enter the number \n"); scanf("%d",&num); printf(Prime numbers till %d are,num); for ( n = 2 ; n <= num ;n++ ) { for ( i = 2 ; i <= n - 1 ; i++ ) { if ( n%i == 0 ) break; } if ( i == n ) printf("\n %d is prime ",n); } } Output: Enter the number 10 Prime numbers till 10 are 2 is prime 3 is prime 5 is prime 7 is prime

Simple program: // program gets integer a as input and prints it #include <stdio.h> Void main() { int a; printf("Enter an integer \n"); scanf("%d", &a); printf("Integer entered is %d ", a); } Output: Enter an Integer 85 Integer Entered is 85 c program to check odd or even: Decimal number system even numbers are divisible by 2 while odd are not, so we may use modulus operator(%) which returns remainder, For example 4%3 gives 1 ( remainder when four is divided by three). #include<stdio.h> void main() { int n; printf("Enter an integer "); scanf("%d", &n); if ( n%2 == 0 ) printf("\n Even"); else printf("\n Odd"); }
Output:
Enter an integer 9 Odd

Common mistakes: 1). In if condition, to check a is equal to 5 , we need to use ==. int a=5; if( a==5 ) { printf( Value of a = %d, a); } Note: here in if condition, only one statement inside if condition. So, no need to use { }. if ( a==5 )

printf( Value of a = %d, a);


C program to sum first n numbers: sum = 1 + 2 +3 + +n Here we need 3 variables sum, i, n. Variable i to count i from 1 to n using for loop. Sum to calculate total. Since, sum is used , it should be initialized to 0. No need to use { } in for i loop as only one statement inside for i loop. #include<stdio.h> void main() { Explanation int n, i, sum=0; n=3 printf ( Enter number n); First i=1, sum=0 scanf (%d, &n); . Sum=sum+i sum=0+1=1 for ( i=1; i <=n; i++) i incrmentes to 2, i=2, sum = sum + i ; . sum = sum +i sum=1+2=3 printf( Sum = %d, sum); Next, i=3, (previous)sum =3 } . sum=sum+i, sum=3+3 = 6 Output: Output: sum =6 Enter number n : 3 Sum = 6 Note: 1. Sum of series 12 + 22 + 32 + .. +n2 Replace sum = sum + i with sum = sum + ( i *i ) 2.For product of first n numbers. 1 * 2 * 3 * * n int product =1; in for loop, product = product * i; 3.Sum of series 1 + 3 + 5 + 7 + . +n Replace for loop with for ( i=1; i <=n; i=i+2) 4. sum of series Declare sum as float, float sum=0; Changes in for loop, sum = sum + (float) (1/i) ; C program to add n numbers, input by user Firstly user will enter a number indicating how many numbers user wishes to add and then user will enter n numbers. In the first c program to add numbers we are not using an array, and using array in the second code. Here we need 3 variables sum, i, num. Sum to calculate total. Variable i to count i from 1 to n. #include <stdio.h> void main() { int n, sum = 0, i, value; printf("Enter number of integers to add \n"); scanf("%d", &n); printf("Enter %d integers \n",n); for (i = 1; i <= n; i++) { scanf("%d",&value); sum = sum + value; } printf("Sum of entered integers = %d \n",sum); } Output: Enter number of integers to add \n); 3 Enter 3 integers 1 5 10 Sum of entered integers = 16. Using array to add n numbers , input by user. #include <stdio.h> void main() { int n, sum = 0, i, array[100]; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &array[i]); sum = sum + array[i]; }

printf("Sum = %d\n",sum); } C program to Check Armstrong Number A positive integer is called an Armstrong number if the sum of cubes of individual digit is equal to that number itself. For example: 153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number. 12 is not equal to 1*1*1+2*2*2 // 12 is not an Armstrong number. Here, we need to get 3,5 and 1 separately. So, to get 3 we apply modulus 153%10 gives 3. So, remainder of 153 %10 as 3, remainder of 15 %10 as 5 , and reminder of 1 %10 as 1. In order to get 15 from 153, we divide 153 by 10 gives 15. 153 /10 15. Variables needed n, rem(remainder), sum (to sum 13 +53+33 ). /* C program to check a number entered by user is Armstrong or not. */ #include <stdio.h> int main() { int n, temp, rem, sum=0; printf("Enter a positive integer: "); scanf("%d", &n); temp=n; while ( temp!=0 ) { rem = temp%10; sum = sum + rem*rem*rem; temp = temp /10; } if(sum == n) printf("%d is an Armstrong number.",n); else printf("%d is not an Armstrong number.",n); } output: Enter a positive integer: 153 153 is an Armstrong number Consider the pattern. Program to print below pattern * ** *** **** ***** First for i loop to count each line. Here we need another for j loop to print stars in a line. Number of stars in each line is equal to line number. So, j loop will count till i (line number) #include <stdio.h> void main() { int n, i, j; printf("Enter number of rows\n"); scanf("%d",&n); for ( i = 1 ; i <= n ; i++ ) { for( j = 1 ; j <= i ; j++ ) printf("*"); printf("\n"); } }

note: for loop and its equivalent while loop


To print numbers 1 to 5 for( i=1 ; i<=5 ; i++) printf(\n %d, i); output: 1 2 3 To print numbers 1 to 5 i=1; while(i<=5) { printf("\n %d", i); i++; //or i=i+1 }

4 5 Program to print below pattern * ** *** **** ***** 3 loops needed. 1 loop for each line. 2nd loop for spaces. 3rd loop for printing stars. For spaces last line has zero or no spaces. First line has 4 spaces. Number of lines be n. Number of spaces = n - line number 5 1 =1 (for 1st line has one space). #include<stdio.h> void main() { int n, line, j, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( line = 1 ; line <= n ; line++ ) { for(k = 1 ; k <= n-line ; k++ ) printf(" "); for( j = 1 ; j <= line ; j++ ) printf("*"); printf("\n"); } } Pascal Triangle 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 This triangle can be constructed by adding 1 to first and last element of each row. Other elements can be calculated by adding the number above and to the left with the number above and to the right to find the new value. To calculate a[6][3]=a[5][2] + a[5][3] 10, where a[5][2] =4, a[5][3]=6 So, a[i][j]=a[i-1][j-1]+a[i-1][j] #include<stdio.h> void main() { int a[10][10]; int no , i, j, k; printf("Enter the number of rows for pascal triangle : "); scanf("%d", &n); //taking input for(i=1; i<=n; i++) { for(j=1; j<=i; j++) { if( j==1 || j==i ) { a[i][j]=1; //first and last value in triangle is 1 } else // taking arrays value , i is row/line. J is val ue position { // sum of previous row 2 num a[i][j]=a[i-1][j-1]+a[i-1][j]; } } } for(i=1; i<=n; i++) { for(k=1; k<=n-i; k++) { printf(" "); } for(j=1; j<=i ; j++) { printf("%d ",a[i][j]); //printing pascal triangle

} printf("\n"); } } Output: Enter the number of rows for pascal triangle : 6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1

// program for merge sort #include<stdio.h> #include<conio.h> void mergesort(int *,int,int); void merge(int *,int,int,int); void main() { int i,n; int a[20]; clrscr(); printf("\n Merge Sort"); printf("\n Enter number of elements"); scanf("%d",&n); printf("\n Enter the elements "); for(i=0;i<n;i++) scanf("%d",&a[i]); mergesort(a,0,n-1); printf("\n Sorted list"); for(i=0;i<n;i++) printf("%d \t",a[i]); } void mergesort(int a[], int low, int high) { if (low < high) { int m = (high + low)/2; mergesort(a, low, m); mergesort(a, m + 1, high); merge(a, low, m, high); } }

/* We need 2 arrays 'a' and 'b', of equal size *Here 'a' is the primary array (i.e which contains initial input, and final output) and 'b' is the temporary array,used for merging 2 sorted half's in 'a' */ void merge(int a[], int low, int mid, int high) { int b[10000]; int i = low, j = mid + 1, k = low; while (i <= mid && j <= high) { if (a[i] <= a[j]) b[k++] = a[i++]; else b[k++] = a[j++]; } while (i <= mid) b[k++] = a[i++]; while (j <= high) b[k++] = a[j++]; for(k=low;k<=high;k++) a[k]=b[k]; }

First 4 levels is mersgesort() function operation Last 4 levels is merge operation

C[i][j] = A[i][j] + B[i][j]

Matrix multiplication

Fibonacci recursive function executes as

3 for loops For I to 1 to row1 For j = 1 to col2 For k 1 to row2 C[i][j] = c[i][j] + a[i][k] + b[k][j] For loop vs While loop. While loop -> initialize done outside the loop. For loop initialize done inside the loop at first time.

Matrix transpose

B[i[][j] = A[j][i] Matrix addition

Eg: to print numbers 1 to 5. For(int i=1;i<=5;i++) { Printf(\n i= %d, i); }

i=1; while(i<=5) { printf(\n i = %d,i); i++; }

Prepared by Dr.B.Surendiran Anna university FOCP Computer programming subject notes. Subject Code : GE6151

Вам также может понравиться