C, C++ & Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 297

C Language

1. C Hello world program C hello world program: - code to print hello world. This program prints hello world, printf function is used to display text on screen, '\n' places cursor on the beginning of next line. This may be your first c code while learning programming. #include<stdio.h> int main() { printf("Hello world\n"); return 0; } Compiling and running the above code. Compiling and running c programs in gcc compiler 1. Save the code in a file say hello.c 2. To compile open terminal type gcc hello.c 3. To execute type ./a.out You can also specify the output file name as follows: gcc hello.c -o hello.out hello.out is name of output file. Turbo C compiler 1. Copy and paste above code in a file and save it. 2. Compile by pressing Alt+F9. 3. Execute by pressing Ctrl+f9 4. For output of this program press (Alt+f5). We may store "hello world" in a character array and then print it. #include<stdio.h> int main() { char string[] = "Hello World"; printf("%s\n", string); return 0; } Output:

2. C program print integer This c program first inputs an integer and then prints it. Input is done using scanf function and number is printed on screen using printf. #include<stdio.h> main() { int a; printf("Enter an integer\n"); scanf("%d", &a); printf("Integer that you have entered is %d\n", a); return 0; } Output:

3.C program to add two numbers C program to add two numbers: This c language program perform the basic arithmetic operation of addition on two numbers and then prints the sum on the screen. For example if the user entered two numbers as 5, 6 then 11 ( 5 + 6 ) will be printed on the screen. #include<stdio.h> #include<conio.h> main() { int a, b, c; printf("Enter two numbers to add "); scanf("%d%d",&a,&b); c = a + b; printf("Sum of entered numbers = %d\n",c); getch(); return 0; } Output:-

Addition without using third variable #include<stdio.h> main() { int a = 1, b = 2; /* Storing result of addition in variable a */ a = a + b; /* Not recommended because original value of a is lost * and you may be using it some where in code considering it * as it was entered by the user. */ printf("Sum of a and b = %d\n", a); return 0; } Adding numbers in c using function We have used long data type as it can handle large numbers. #include<stdio.h> long addition(long, long); main() { long first, second, sum; scanf("%ld%ld", &first, &second); sum = addition(first, second); printf("%ld\n", sum); return 0; } long addition(long a, long b) {

long result; result = a + b; return result; }

4. C program to perform addition, subtraction, multiplication and division This c program perform basic arithmetic operations i.e. add , subtract, multiply and divide two numbers. Numbers are assumed to be integers and will be entered by the user. #include<stdio.h> #include<conio.h> main() { int first, second, add, sub, mul, div; printf("Enter two numbers "); scanf("%d%d",&first,&second); add = first + second; sub = first - second; mul = first * second; div = first / second; printf("Sum of two numbers = %d\n",add); printf("Difference of two numbers = %d\n",sub); printf("Multiplication of two numbers = %d\n",mul); printf("Division of two numbers = %d",div); getch(); return 0; }

Output:

5. C program to multiply numbers without using multiplication sign #include<stdio.h> main() { int x, y, c, temp, temp1, result = 0; scanf("%d%d",&x,&y); temp = x; temp1 = y; if ( temp < 0 ) temp = -temp;

/* If x is negative*/

for ( c = 1 ; c <= temp ; c++) result = result + temp1; if( x < 0 && y < 0 ) /* to print proper sign */ result = -result; printf("%d\n",result); return 0; }

6. C program to check whether input alphabet is a vowel or not

This code checks whether an input alphabet is a vowel or not. Both lower-case and uppercase are checked. #include<stdio.h> main() { char ch; printf("Enter a character\n"); scanf("%c",&ch); if ( ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U') printf("%c is a vowel.\n", ch); else printf("%c is not a vowel.\n", ch); return 0; } Output:

Check vowel using switch statement #include<stdio.h> main() { char ch; printf("Enter a character\n"); scanf("%c",&ch); switch(ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U':

printf("%c is a vowel.\n", ch); break; default: printf("%c is not a vowel.\n", ch); } return 0; } Function to check vowel int check_vowel(char a) { if ( a >= 'A' && a <= 'Z' ) a = a + 'a' - 'A'; /* Converting to lower case */ if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return 1; return 0; }

7. C program to check leap year C program to check leap year: c code to check leap year, year will be entered by the user. #include<stdio.h> main() { int year; printf("Enter a year to check if it is a leap year\n"); scanf("%d", &year); if ( year%400 == 0) printf("%d is a leap year.\n", year); else if ( year%100 == 0) printf("%d is not a leap year.\n", year); else if ( year%4 == 0 ) printf("%d is a leap year.\n", year); else printf("%d is not a leap year.\n", year); return 0; }

8. Add digits of number in C

C programming code to find sum of digits of a number. Here we are using modulus operator to extract individual digits of number and adding them. #include<stdio.h> #include<conio.h> main() { int num, sum = 0, rem; printf("Enter a number\n"); scanf("%d",&num); while( num != 0 ) { rem = num % 10; sum = sum + rem; num = num / 10; } printf("Sum of digits of entered number = %d\n",sum); getch(); return 0; } Output:-

9. Factorial program in C Factorial program in c: c code to find and print factorial of a number, three methods are given, first one uses a for loop, second uses a function to find factorial and third using recursion. Factorial is represented using !, so five factorial will be written as 5!, n factorial as n!. Also n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0!=1. Factorial program using for loop #include<stdio.h> #include<conio.h> main() {

int c, n, fact = 1; printf("Enter a number to calculate it's factorial\n"); scanf("%d",&n); for( c = 1 ; c <= n ; c++ ) fact = fact*c; printf("Factorial of %d = %d\n",n,fact); getch(); return 0; } Output:-

Factorial program using function #include<stdio.h> long factorial(int); main() { int number; long fact = 1; printf("Enter a number to calculate it's factorial\n"); scanf("%d",&number); printf("%d! = %ld\n", number, factorial(number)); return 0; } long factorial(int n) { int c; long result = 1; for( c = 1 ; c <= n ; c++ ) result = result*c; return ( result ); }

Factorial program using recursion #include<stdio.h> long factorial(int); main() { int num; long f; printf("ENTER A NUMBER TO FIND FACTORIAL :"); scanf("%d",&num); if(num<0) printf("NEGATIVE NUMBERS ARE NOT ALLOWED"); else { f = factorial(num); printf("%d!=%ld",num,f); } return(0); } long factorial(int n) { if(n==0) return(1); else return(n*factorial(n-1)); } 10. C program to add n numbers This c program add n numbers which will be entered by the user. Firstly user will enter a number indicating how many numbers user wishes to add and then user will enter n numbers.In our c program to add numbers we are not using an array, if you wish you can use an array. #include<stdio.h> #include<conio.h> main() { int n, sum = 0, c, var; printf("Enter the number of integers you want to add\n"); scanf("%d",&n); printf("Enter %d numbers\n",n);

for ( c = 1 ; c <= n ; c++ ) { scanf("%d",&var); sum = sum + var; } printf("Sum of entered numbers = %d\n",sum); getch(); return 0; } Output:

11. C program to swap two numbers C program to swap two numbers with and without using third variable, swapping in c using pointers and functions (Call by reference) , swapping means interchanging. For example if in your c program you have taken two variable a and b where a = 4 and b = 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4 In our c program to swap numbers we will use a temp variable to swap two numbers. Swapping is used in sorting that is when we wish to arrange numbers in a particular order either in ascending order or in descending order. Swaping of two numbers #include<stdio.h> #include<conio.h>

main() { int x, y, temp; printf("Enter the value of x and y "); scanf("%d%d",&x, &y); printf("Before Swapping\nx = %d\ny = %d\n",x,y); temp = x; x = y; y = temp; printf("After Swapping\nx = %d\ny = %d\n",x,y); getch(); return 0; } Swapping of two numbers without third variable You can also swap two numbers without using temp or temporary or third variable. In that case c program will be as shown :#include<stdio.h> main() { int a, b; printf("Enter two numbers to swap "); scanf("%d%d",&a,&b); a = a + b; b = a - b; a = a - b; printf("a = %d\nb = %d\n",a,b); return 0; } To understand above logic simply choose a as 7 and b as 9 and then do what is written in program. You can choose any other combination of numbers as well. Sometimes it's a good way to understand a program. Swap two numbers using pointers #include<stdio.h> main() {

int x, y, *a, *b, temp; printf("Enter the value of x and y "); scanf("%d%d",&x,&y); printf("Before Swapping\nx = %d\ny = %d\n", x, y); a = &x; b = &y; temp = *b; *b = *a; *a = temp; printf("After Swapping\nx = %d\ny = %d\n", x, y); return 0; } Swapping numbers using call by reference In this method we will make a function to swap numbers. #include<stdio.h> void swap(int*, int*); main() { int x, y; printf("Enter the value of x and y\n"); scanf("%d%d",&x,&y); printf("Before Swapping\nx = %d\ny = %d\n", x, y); swap(&x, &y); printf("After Swapping\nx = %d\ny = %d\n", x, y); return 0; } void swap(int *a, int *b) { int temp; temp = *b; *b = *a; *a = temp; }

Output:-

12. C program to reverse a number C Program to reverse a number :- This program reverse the number entered by the user and then prints the reversed number on the screen. For example if user enter 123 as input then 321 is printed as output. In our program we use modulus(%) operator to obtain the digits of a number. To invert number look at it and write it from opposite direction or the output of code is a number obtained by writing original number from right to left. #include<stdio.h> main() { int n, reverse = 0; printf("Enter a number to reverse\n"); scanf("%d",&n); while( n != 0 ) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; } printf("Reverse of entered number is = %d\n", reverse); return 0; }

Output:-

13. Palindrome Numbers Palindrome number in c: A palindrome number is a number such that if we reverse it, it will not change. For example some palindrome numbers examples are 121, 212, 12321, 454. To check whether a number is palindrome or not first we reverse it and then compare the number obtained with the original, if both are same then number is palindrome otherwise not. C program for palindrome number is given below. Palindrome number algorithm 1. Get the number from user. 2. Reverse it. 3. Compare it with the number entered by the user. 4. If both are same then print palindrome number 5. Else print not a palindrome number. #include<stdio.h> main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or not\n"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10; } if ( n == reverse ) printf("%d is a palindrome number.\n", n); else printf("%d is not a palindrome number.\n", n); return 0; }

14. C program to print patterns of numbers and stars These program prints various different patterns of numbers and stars. These codes illustrate how to create various patterns using c programming. Most of these c programs involve usage of nested loops and space. A pattern of numbers, star or characters is a way of arranging these in some logical manner or they may form a sequence. Some of these patterns are triangles which have special importance in mathematics. Some patterns are symmetrical while other are not. Please see the complete page and look at comments for many different patterns. * *** ***** ******* ********* We have shown five rows above, in the program you will be asked to enter the numbers of rows you want to print in the pyramid of stars. #include<stdio.h> #include<conio.h> main() { int row, c, n, temp; printf("Enter the number of rows in pyramid of stars you wish to see "); scanf("%d",&n); temp = n; for ( row = 1 ; row <= n ; row++ ) { for ( c = 1 ; c < temp ; c++ ) printf(" "); temp--; for ( c = 1 ; c <= 2*row - 1 ; c++ ) printf("*"); printf("\n"); } getch(); return 0; }

Output:

Consider the pattern * ** *** **** ***** to print above pattern see the code below: #include<stdio.h> main() { int n, c, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) printf("*"); printf("\n"); } return 0; } Consider this pattern 12345 1234 123 12 1

to print above pattern see the code below: #include<stdio.h> main() { int n, c, k, space; scanf("%d", &n); space = 0; for ( k = n ; k >= 1 ; k-- ) { for ( c = 1 ; c <= space ; c++ ) printf(" "); space++; for ( c = 1 ; c <= k ; c++) printf("%d", c); printf("\n"); } return 0; } Consider this pattern ABCDEFGH ABCDEFG ABCDEF ABCDE ABCD ABC AB A to print above pattern see the code below: #include<stdio.h> main() { char ch = 'A'; int n, c, k, space = 0; scanf("%d", &n); for ( k = n ; k >= 1 ; k-- )

{ for ( c = 1 ; c <= space ; c++) printf(" "); space++; for ( c = 1 ; c <= k ; c++ ) { printf("%c ", ch); ch++; } printf("\n"); ch = 'A'; } return 0; }

Consider this pattern 1 01 010 1010 10101 to print above pattern see the code below: #include<stdio.h> main() { int n, c, k, num = 1; scanf("%d", &n); for ( c = 1 ; c <= n ; c++ ) { for ( k = 1 ; k <= c ; k++ ) { printf("%d", num); if ( num == 0 ) num = 1; else num = 0;

} printf("\n"); } return 0; } Consider this pattern p pr pro prog progr progra program to print above pattern see the code below: Just input the string and press enter, corresponding pattern will be printed. #include<stdio.h> #include<string.h> main() { char string[100]; int c, k, length; printf("Enter a string\n"); gets(string); length = strlen(string); for ( c = 0 ; c < length ; c++ ) { for( k = 0 ; k <= c ; k++ ) { printf("%c", string[k]); } printf("\n"); } return 0; } Consider this pattern 1 121 12321

1234321 123454321 to print above pattern see the code below: #include<stdio.h> main() { int n, c, k, x = 1; scanf("%d", &n); for ( c = 1 ; c <= n ; c++ ) { for ( k = 1 ; k <= c ; k++ ) { printf("%d", x); x++; } x--; for ( k = 1 ; k <= c - 1 ; k++ ) { x--; printf("%d", x); } printf("\n"); x = 1; } return 0; } Consider this pattern 1 232 34543 4567654 567898765 to print above pattern see the code below: #include<stdio.h> main() { int n, c, d, num = 1, space;

scanf("%d",&n); space = n - 1; for ( d = 1 ; d <= n ; d++ ) { num = d; for ( c = 1 ; c <= space ; c++ ) printf(" "); space--; for ( c = 1 ; c <= d ; c++ ) { printf("%d", num); num++; } num--; num--; for ( c = 1 ; c < d ; c++) { printf("%d", num); num--; } printf("\n"); } return 0; } Consider this pattern ******* ***S*** **SSS** *SSSSS* where S represents Space ******* *** *** ** ** * * to print above pattern see the code below: #include<stdio.h>

main() { int n, c, k, space, r; printf("Enter number of rows\n"); scanf("%d",&n); space = 1; r = n-1; for( c = 1 ; c <= 2*n - 1 ; c++ ) printf("*"); printf("\n"); for ( k = 2 ; k <= n ; k++ ) { for( c = 1 ; c <= r ; c++ ) printf("*"); for ( c = 1 ; c <= space ; c++ ) printf(" "); space = 2*k-1; for( c = 1 ; c <= r ; c++ ) printf("*"); r--; printf("\n"); } return 0; } Consider this pattern * ** *** **** ***** to print above pattern see the code below: #include<stdio.h> main() { int n, c, k, space;

printf("Enter number of rows\n"); scanf("%d",&n); space = n; for ( k = 1 ; k <= n ; k++ ) { for ( c = 1 ; c < space ; c++ ) printf(" "); space--; for( c = 1 ; c <= k ; c++ ) printf("*"); printf("\n"); } return 0; } Consider this pattern 1 22 333 4444 55555 to print above pattern see the code below: #include<stdio.h> main() { int n, c, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) printf("%d", c); printf("\n"); } return 0; }

Consider this pattern * ** *** **** *** ** * to print above pattern see the code below: #include<stdio.h> main() { int n, c, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++) { for ( k = 1 ; k <= c ; k++ ) printf("*"); printf("\n"); } for ( c = n - 2 ; c >= 0 ; c-- ) { for ( k = c ; k >= 0 ; k-- ) printf("*"); printf("\n"); } return 0; }

Consider this pattern * *A* *A*A* *A*A*A* to print above pattern see the code below: #include<stdio.h>

main() { int n, c, k, space, count = 1; printf("Enter number of rows\n"); scanf("%d",&n); space = n; for ( c = 1 ; c <= n ; c++) { for( k = 1 ; k < space ; k++) printf(" "); for ( k = 1 ; k <= c ; k++) { printf("*"); if ( c > 1 && count < c) { printf("A"); count++; } } printf("\n"); space--; count = 1; } return 0; }

Consider this pattern ***** *** ** * to print above pattern see the code below: #include<stdio.h> main() { int n, c, k, temp;

printf("Enter number of rows\n"); scanf("%d",&n); temp = n; for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= temp ; k++ ) printf("* "); temp--; printf("\n"); } return 0; } Consider this pattern * ** *** **** to print above pattern see the code below: #include<stdio.h> main() { int n, c, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) printf("* "); printf("\n"); } return 0; } Consider this pattern 1 12 123 1234

to print above pattern see the code below: #include<stdio.h> main() { int number = 1, n, c, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) { printf("%d ", number); number++; } number = 1; printf("\n"); } return 0; } Number pattern code You are right there is no need to use variable number you can use k directly as in code below: #include<stdio.h> main() { int n, c, k; printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) printf("%d ", k); printf("\n"); } return 0; }

Consider this pattern * * * * * * * * * * to print above pattern see the code below: #include<stdio.h> main() { int n, c, k = 2, j; printf("Enter number of rows\n"); scanf("%d",&n); for ( j = 1 ; j <= n ; j++ ) { for ( c = 1 ; c <= 2*n-k ; c++) printf(" "); k = k + 2; for ( c = 1 ; c <= j ; c++) printf("* "); printf("\n"); } getch(); return 0; } 15. C program to print diamond pattern Diamond pattern in c: This code print diamond pattern of stars. Diamond shape is as follows: * *** ***** *** * #include<stdio.h> main() { int n, c, k, space = 1; printf("Enter number of rows\n");

scanf("%d",&n); space = n - 1; for ( k = 1 ; k <= n ; k++ ) { for ( c = 1 ; c <= space ; c++ ) printf(" "); space--; for ( c = 1 ; c <= 2*k-1 ; c++) printf("*"); printf("\n"); } space = 1; for ( k = 1 ; k <= n - 1 ; k++ ) { for ( c = 1 ; c <= space; c++) printf(" "); space++; for ( c = 1 ; c <= 2*(n-k)-1 ; c++ ) printf("*"); printf("\n"); } return 0; }

16. Prime numbers program in C This program generate prime numbers and then prints them, number of prime numbers required are entered by the user. #include<stdio.h> #include<conio.h> #include<math.h> main() { int n, status = 1, num = 3, count, c;

printf("Enter the number of prime numbers you want "); scanf("%d",&n); if ( n >= 1 ) { printf("First %d prime numbers are :-\n",n); printf("2\n"); } for ( count = 2 ; count <=n ; ) { for ( c = 2 ; c <= sqrt(num) ; c++ ) { if ( num%c == 0 ) { status = 0; break; } } if ( status != 0 ) { printf("%d\n",num); count++; } status = 1; num++; } getch(); return 0; } Output:

17. Armstrong number program in C Armstrong number c program: c programming code to check whether a number is armstrong or not. A number is armstrong if the sum of cubes of individual digits of a number is equal to the number itself. For example 371 is an armstrong number as 33 + 73 + 13 = 371. Some other armstrong numbers are: 0, 1, 153, 370, 407. #include<stdio.h> #include<conio.h> main() { int number, sum = 0, temp, remainder; printf("Enter a number\n"); scanf("%d",&number); temp = number; while( temp != 0 ) { remainder = temp%10; sum = sum + remainder*remainder*remainder; temp = temp/10; } if ( number == sum )

printf("Entered number is an armstrong number."); else printf("Entered number is not an armstrong number."); getch(); return 0; } Output:

18. C program to generate and print armstrong numbers armstrong number in c: This program prints armstrong number. In our program we ask the user to enter a number and then we use a loop from one to the entered number and check if it is an armstrong number and if it is then the number is printed on the screen. Remember a number is armstrong if the sum of cubes of individual digits of a number is equal to the number itself. For example 371 is an armstrong number as 33 + 73 + 13 = 371. Some other armstrong numbers are 0, 1, 153, 370, 407. #include<stdio.h> #include<conio.h> main() { int r; long number = 0, c, sum = 0, temp; printf("Enter the maximum range upto which you want to find armstrong numbers "); scanf("%ld",&number); printf("Following armstrong numbers are found from 1 to %ld\n",number); for( c = 1 ; c <= number ; c++ ) { temp = c; while( temp != 0 ) { r = temp%10; sum = sum + r*r*r; temp = temp/10; }

if ( c == sum ) printf("%ld\n", c); sum = 0; } getch(); return 0; } Output of program

19. C program for fibonacci series C program for fibonacci series: c code to generate Fibonacci series without and with recursion. You can print as many number of terms of series as desired. Numbers of fibonacci sequence are known as fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc. C program for fibonacci series #include<stdio.h> #include<conio.h> main() { int n, first = 0, second = 1, next, c; printf("Enter the number of terms "); scanf("%d",&n);

printf("First %d terms of fibonacci series are :-\n",n); for ( c = 0 ; c < n ; c++ ) { if ( c <= 1 ) next = c; else { next = first + second; first = second; second = next; } printf("%d\n",next); } getch(); return 0; } Output:

Fibonacci series using recursion #include<stdio.h> int fibonacci(int); main() { int n, i = 0, c; scanf("%d",&n);

printf("Fibonacci series\n"); for ( c = 1 ; c <= n ; c++ ) { printf("%d\n", fibonacci(i)); i++; } return 0; } int fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( fibonacci(n-1) + fibonacci(n-2) ); }

20. C program to print Floyd's triangle C program to print Floyd's triangle:- This program prints Floyd's triangle. Number of rows of Floyd's triangle to print is entered by the user. First four rows of Floyd's triangle are as follows :1 23 456 7 8 9 10 It's clear that in Floyd's triangle nth row contains n numbers. #include<stdio.h> #include<conio.h> main() { int n, i, c, a = 1; printf("Enter the number of rows of Floyd's triangle to print\n"); scanf("%d",&n); for ( i = 1 ; i <= n ; i++ ) { for ( c = 1 ; c <= i ; c++ ) { printf("%d ",a);

a++; } printf("\n"); } getch(); return 0; } Output:-

Consider this pattern EDCBA DCBA CBA BA A to print above pattern see the code below: #include<stdio.h> main() { int n, c, k, space = 0; char ch, temp; scanf("%d", &n); ch = 'A'+n-1; temp = ch; for ( k = n ; k >= 1 ; k-- ) { for ( c = 1 ; c <= space; c++) printf(" "); space++; for ( c = 1 ; c <= k ; c++ ) { printf("%c",temp); temp--;

} printf("\n"); ch--; temp = ch; } return 0; } Consider this pattern A BB CCC DDDD EEEEE and so on. to print above pattern see the code below: #include<stdio.h> main() { int c, n, k; char ch = 'A';

printf("Enter number of rows\n"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for ( k = 1 ; k <= c ; k++) printf("%c ", ch); printf("\n"); ch++; } return 0; }

21. C program to print Pascal triangle This program prints Pascal triangle which you might have studied in Binomial Theorem in Mathematics. Number of rows of Pascal triangle to print is entered by the user. First four rows of Pascal triangle are shown below :-

1 11 121 1331 Pascal triangle in c programming. #include<stdio.h> #include<conio.h> #include<math.h> long factorial(int); main() { int i, n, c; printf("Enter the number of rows you wish to see in pascal triangle\n"); scanf("%d",&n); for ( i = 0 ; i < n ; i++ ) { for ( c = 0 ; c <= ( n - i - 2 ) ; c++ ) printf(" "); for( c = 0 ; c <= i ; c++ ) printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c))); printf("\n"); } getch(); return 0; } long factorial(int n) { int c; long result = 1; for( c = 1 ; c <= n ; c++ ) result = result*c; return ( result ); }

Output:-

Consider this pattern 1 121 12321 1234321 Pyramid of numbers source code: #include<stdio.h> main() { int n, c, k, number = 1, space = n; printf("Enter number of rows\n"); scanf("%d",&n); space = n; for ( c = 1 ; c <= n ; c++ ) { for ( k = space ; k > 1 ; k-- ) printf(" "); space--; for ( k = 1 ; k <= 2*c - 1 ; k++ ) { if ( k <= c) { printf("%d", number); if ( k < c ) number++; } else { number--;

printf("%d", number); } } number = 1; printf("\n"); } return 0; }

22. C program to add two numbers using pointers This program performs addition of two numbers using pointers. In our program we have two two integer variables x, y and two pointer variables p and q. Firstly we assign the addresses of x and y to p and q respectively and then assign the sum of x and y to variable sum. Note that & is address of operator and * is value at address operator. #include<stdio.h> main() { int first, second, *p, *q, sum; printf("Enter two integers to add\n"); scanf("%d%d", &first, &second); p = &first; q = &second; sum = *p + *q; printf("Sum of entered numbers = %d\n",sum); return 0; } Output:-

23. C program to find maximum element in array

This code find maximum or largest element present in an array. It also prints the location or index at which maximum element occurs in array. This can also be done by using pointers (see both codes). #include<stdio.h> main() { int array[100], maximum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); maximum = array[0]; for ( c = 1 ; c < size ; c++ ) { if ( array[c] > maximum ) { maximum = array[c]; location = c+1; } } printf("Maximum element is present at location number %d and it's value is %d.\n", location, maximum); return 0; } C code using pointers #include<stdio.h> main() { int array[100], *maximum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); maximum = array;

*maximum = *array; for ( c = 1 ; c < size ; c++ ) { if ( *(array+c) > *maximum ) { *maximum = *(array+c); location = c+1; } } printf("Maximum element is present at location number %d and it's value is %d.\n", location, *maximum); return 0; }

24. C program to find minimum element in array C code to find minimum or smallest element present in an array. It also prints the location or index at which minimum element occurs in array. This can also be done by using pointers (see both the codes). #include<stdio.h> main() { int array[100], minimum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array[0]; for ( c = 1 ; c < size ; c++ ) { if ( array[c] < minimum ) { minimum = array[c]; location = c+1; } }

printf("Minimum element is present at location number %d and it's value is %d.\n", location, minimum); return 0; } C code using pointers #include<stdio.h> main() { int array[100], *minimum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array; *minimum = *array; for ( c = 1 ; c < size ; c++ ) { if ( *(array+c) < *minimum ) { *minimum = *(array+c); location = c+1; } } printf("Minimum element is present at location number %d and it's value is %d.\n", location, *minimum); return 0; }

25. Linear search in C Linear search in c programming: The following code implements linear search ( Searching algorithm ) which is used to find whether a given number is present in an array and if it is present then at what location it occurs.It is also known as sequential search. It is very simple and works as follows: We keep on comparing each element with the element to search until the desired element is found or list ends. Linear search using for multiple occurrences and using function.

#include<stdio.h> main() { int array[100], search, c, number; printf("Enter the number of elements in array\n"); scanf("%d",&number); printf("Enter %d numbers\n", number); for ( c = 0 ; c < number ; c++ ) scanf("%d",&array[c]); printf("Enter the number to search\n"); scanf("%d",&search); for ( c = 0 ; c < number ; c++ ) { if ( array[c] == search ) /* if required element found */ { printf("%d is present at location %d.\n", search, c+1); break; } } if ( c == number ) printf("%d is not present in array.\n", search); return 0; } Output:-

Linear search for multiple occurrences In the code below we will print all the locations at which required element is found and also the number of times it occur in the list. #include<stdio.h>

main() { int array[100], search, c, n, count = 0; printf("Enter the number of elements in array\n"); scanf("%d",&n); printf("Enter %d numbers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter the number to search\n"); scanf("%d",&search); for ( c = 0 ; c < n ; c++ ) { if ( array[c] == search ) { printf("%d is present at location %d.\n", search, c+1); count++; } } if ( count == 0 ) printf("%d is not present in array.\n", search); else printf("%d is present %d times in array.\n", search, count); return 0; } Output:-

C program for linear search using function #include<stdio.h>

int linear_search(int*, int, int); main() { int array[100], search, c, n, position; printf("Enter the number of elements in array\n"); scanf("%d",&n); printf("Enter %d numbers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter the number to search\n"); scanf("%d",&search); position = linear_search(array, n, search); if ( position == -1 ) printf("%d is not present in array.\n", search); else printf("%d is present at location %d.\n", search, position+1); return 0; } int linear_search(int *pointer, int n, int find) { int c; for ( c = 0 ; c < n ; c++ ) { if ( *(pointer+c) == find ) return c; } return -1; }

26. C program for binary search C program for binary search: This code implements binary search in c language. It can only be used for sorted arrays, bu it's fast as compared to linear search. If you wish to use binary search on an array which is not sorted then you must sort it and then use binary search algorithm to find the desired element in the list. #include<stdio.h>

main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter value to find\n"); scanf("%d",&search); first = 0; last = n - 1; middle = (first+last)/2; while( first <= last ) { if ( array[middle] < search ) first = middle + 1; else if ( array[middle] == search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if ( first > last ) printf("%d is not present in the list.\n", search); return 0; }

27. C program to reverse an array C program to reverse an array :- This program reverses the array elements. For example if a is an array of integers with three elements such that a[0] = 1

a[1] = 2 a[2] = 3 then on reversing the array will be a[0] = 3 a[1] = 2 a[0] = 1 In the program swapping is done to reverse the array elements. Simple or alternative method to reverse array elements is given in comments below. Given below is the c code to reverse an array . #include<stdio.h> #include<conio.h> main() { int n, c, j, temp, a[100]; printf("Enter the number of elements in array\n"); scanf("%d",&n); printf("Enter the array elements\n"); for ( c = 0 ; c < n ; c++ ) scanf("%d",&a[c]); if( n%2 == 0 ) c = n/2 - 1; else c = n/2; for ( j = 0 ; j < c ; j++ ) { temp = a[j]; a[j] = a[n -j - 1]; a[n-j-1] = temp; } printf("Reverse array is\n"); for( c = 0 ; c < n ; c++ ) printf("%d\n", a[c]); getch(); return 0; }

Output:-

Easy method to reverse an array #include<stdio.h> main() { int a[5] = {1, 2, 3, 4, 5}, c, count = 4, b[5]; for ( c = 0 ; c < 5 ; c++ ) { b[count] = a[c]; count--; } for ( c = 0 ; c < 5 ; c++ ) { a[c] = b[c]; printf("%d\n", a[c]); } return 0; }

28. C program to insert an element in an array This code will insert an element into an array, For example consider an array a[10] having three elements in it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you want to insert a number 45 at location 1 i.e. a[0] = 45, so we have to move elements one step below so after insertion a[1] = 1 which was a[0] initially, and a[2] = 2 and a[3] = 3. Array insertion does not mean increasing its size i.e array will not be containing 11 elements. #include<stdio.h>

main() { int array[100], position, c, n, value; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); printf("Enter the location where you wish to insert an element\n"); scanf("%d", &position); printf("Enter the value to insert\n"); scanf("%d", &value); for ( c = n - 1 ; c >= position - 1 ; c-- ) array[c+1] = array[c]; array[position-1] = value; printf("Resultant array is\n"); for( c = 0 ; c <= n ; c++ ) printf("%d\n", array[c]); return 0; }

29. C program to delete an element from an array This program delete an element from an array. Deleting an element does not affect the size of array. It is also checked whether deletion is possible or not, For example if array is containing five elements and you want to delete element at position six which is not possible. #include<stdio.h> main() { int array[100], position, c, n;

printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); printf("Enter the location where you wish to delete element\n"); scanf("%d", &position); if ( position >= n+1 ) printf("Deletion not possible.\n"); else { for ( c = position - 1 ; c < n - 1 ; c++ ) array[c] = array[c+1]; printf("Resultant array is\n"); for( c = 0 ; c < n - 1 ; c++ ) printf("%d\n", array[c]); } return 0; }

30. Bubble sort in C Bubble sort in c: c program for bubble sort to sort numbers or arrange them in ascending order. /* Bubble sort code */ #include<stdio.h> main() { int array[100], n, c, d, swap; printf("Enter number of elements\n"); scanf("%d", &n);

printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); for ( c = 0 ; c < ( n - 1 ) ; c++ ) { for ( d = 0 ; d < n - c - 1 ; d++ ) { if ( array[d] > array[d+1] ) { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; }

31. Insertion sort in C Insertion sort in c: c program for insertion sort to sort numbers. This code implements insertion sort algorithm to arrange numbers of an array in ascending order. With a little modification it will arrange numbers in descending order. /* insertion sort ascending order */ #include<stdio.h> main() { int array[100], n, c, d, swap, k; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n);

for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); for ( c = 1 ; c <= n - 1 ; c++ ) { for ( d = 0 ; d <= c - 1 ; d++ ) { if ( array[c] < array[d] ) { swap = array[d]; array[d] = array[c]; for ( k = c ; k > d ; k-- ) array[k] = array[k-1]; array[k+1] = swap; } } } printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; } 32. Selection sort in C Selection sort in c: c program for selection sort to sort numbers. This code implements selection sort algorithm to arrange numbers of an array in ascending order. With a little modification it will arrange numbers in descending order. #include<stdio.h> main() { int array[100], n, c, d, swap; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); for ( c = 0 ; c < ( n - 1) ; c++ ) { for ( d = ( c + 1 ) ; d <= ( n - 1 ) ; d++ )

{ if ( array[c] > array[d] ) { swap = array[c]; array[c] = array[d]; array[d] = swap; } } } printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; }

33. C program to add two matrix This c program add two matrices i.e. compute the sum of two matrices and then print it. Firstly user will be asked to enter the order of matrix ( number of rows and columns ) and then two matrices. #include<stdio.h> #include<conio.h> main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; printf("Enter the number of rows and columns of matrix "); scanf("%d%d",&m,&n); printf("Enter the elements of first matrix\n"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) scanf("%d",&first[c][d]); printf("Enter the elements of second matrix\n"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) scanf("%d",&second[c][d]); for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ ) sum[c][d] = first[c][d]+ second[c][d]; printf("Sum of entered matrices:-\n"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) printf("%d\t",sum[c][d]); printf("\n"); } getch(); return 0; } Sample output of the above program is shown in image below :-

34. Subtract matrices C code to subtract matrices of any order. This program finds difference between corresponding elements of two matrices and then print the resultant matrix. #include<stdio.h> #include<conio.h> main() {

int m, n, c, d, first[10][10], second[10][10], difference[10][10]; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d",&m,&n); printf("Enter the elements of first matrix\n"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) scanf("%d",&first[c][d]); printf("Enter the elements of second matrix\n"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) scanf("%d",&second[c][d]); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) difference[c][d] = first[c][d] - second[c][d]; printf("difference of entered matrices:-\n"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) printf("%d\t",difference[c][d]); printf("\n"); } getch(); return 0; }

35. Matrix multiplication in C C program to multiply matrices:- This program multiplies two matrices which will be entered by the user. Firstly user will enter the order of a matrix. If the entered orders of two matrix is such that they can't be multiplied then an error message is displayed on the screen. #include<stdio.h> #include<conio.h> main() { int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], mul[10][10];

printf("Enter the number of rows and columns of first matrix\n"); scanf("%d%d",&m,&n); printf("Enter the elements of first matrix\n"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) scanf("%d",&first[c][d]); printf("Enter the number of rows and columns of second matrix\n"); scanf("%d%d",&p,&q); if ( n != p ) printf("Matrices with entered orders can't be multiplied with each other.\n"); else { printf("Enter the elements of second matrix\n"); for ( c = 0 ; c < p ; c++ ) for ( d = 0 ; d < q ; d++ ) scanf("%d",&second[c][d]); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { for ( k = 0 ; k < p ; k++ ) { sum = sum + first[c][k]*second[k][d]; } mul[c][d] = sum; sum = 0; } } printf("Product of entered matrices:-\n"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < q ; d++ ) printf("%d\t",mul[c][d]); printf("\n"); } } getch(); return 0; }

Output of program

36. C program to transpose a matrix This c program prints transpose of a matrix. It is obtained by interchanging rows and columns of a matrix. When we transpose a matrix then the order of matrix changes, but for a square matrix order remains same. #include<stdio.h> #include<conio.h> main() { int m, n, c, d, matrix[10][10], transpose[10][10]; printf("Enter the number of rows and columns of matrix "); scanf("%d%d",&m,&n); printf("Enter the elements of matrix \n"); for( c = 0 ; c < m ; c++ ) { for( d = 0 ; d < n ; d++ ) { scanf("%d",&matrix[c][d]); } } for( c = 0 ; c < m ; c++ ) {

for( d = 0 ; d < n ; d++ ) { transpose[d][c] = matrix[c][d]; } } printf("Transpose of entered matrix :-\n"); for( c = 0 ; c < n ; c++ ) { for( d = 0 ; d < m ; d++ ) { printf("%d\t",transpose[c][d]); } printf("\n"); } getch(); return 0; } Output:

37. C program to print string This program print a string. String can be printed by using various functions such as printf, puts. #include<stdio.h> main() {

char array[20] = "Hello World"; printf("%s\n",array); return 0; } To input a string we use scanf function. #include<stdio.h> main() { char array[100]; printf("Enter a string\n"); scanf("%s",&array); printf("You entered the string %s\n",array); return 0; } Note that scanf can only input single word strings, to receive strings containing spaces use gets function.

38. String length This program prints length of string, for example consider the string "c programming" it's length is 13. Null character is not counted when calculating string length. To find string length we use strlen function of string.h. #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[100]; int length; printf("Enter a string to calculate it's length "); gets(a); length = strlen(a); printf("Length of entered string is = %d\n",length); getch();

return 0; } Output of program:

You can also find string length using pointer or without strlen function. Following program shows how to achieve this. String length without strlen #include<stdio.h> #include<conio.h> main() { char array[100]; char *ptr; int length = 0; printf("Enter a string "); gets(array); ptr = array; while(*ptr) { length++; ptr++; } printf("Length of entered string = %d\n",length); getch(); return 0; }

39. C program to compare two strings This c program compares two strings using strcmp function. For comparing strings without using library function see another code below. Using strcmp #include<stdio.h> #include<conio.h>

#include<string.h> main() { char a[100], b[100]; printf("Enter the first string "); gets(a); printf("Enter the second string "); gets(b); if( strcmp(a,b) == 0 ) printf("Entered strings are equal.\n"); else printf("Entered strings are not equal.\n"); getch(); return 0; } Without using strcmp In this method we will make our own function to perform string comparison, we will use character pointers in our function to manipulate string. #include<stdio.h> int compare_string(char*, char*); main() { char first[100], second[100], result; printf("Enter first string\n"); gets(first); printf("Enter second string\n"); gets(second); result = compare_string(first, second); if ( result == 0 ) printf("Both strings are same.\n"); else printf("Entered strings are not equal.\n"); return 0; } int compare_string(char *first, char *second)

{ while(*first) { if (*first == *second) { first++; second++; } else return -1; } return 0; }

40. String copying in c programming This program copy string using library function strcpy, to copy string without using strcpy see source code below in which we have made our own function to copy string. With strcpy #include<stdio.h> #include<conio.h> #include<string.h> main() { char source[] = "C program"; char destination[50]; strcpy(destination, source); printf("Source string: %s\n", source); printf("Destination string: %s", destination); getch(); return 0; } Without strcpy : here we copy string by creating our own function which uses pointers. #include<stdio.h> void copy_string(char*, char*);

main() { char source[100], target[100]; printf("Enter source string\n"); gets(source); copy_string(target, source); printf("Target string is \"%s\"\n", target); return 0; } void copy_string(char *target, char *source) { while(*source) { *target = *source; source++; target++; } *target = '\0'; }

41. C program to concatenate strings This program concatenates strings, for example if the first string is "c " and second string is "program" then on concatenating these two strings we get the string "c program". To concatenate two strings we use strcat function of string.h, to concatenate without using library function see another code below which uses pointers. With strcat #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[100], b[100]; printf("Enter the first string\n"); gets(a); printf("Enter the second string\n"); gets(b);

strcat(a,b); printf("String obtained on concatenation is %s\n",a); getch(); return 0; } Output:

Without strcat #include<stdio.h> void concatenate_string(char*, char*); main() { char original[100], add[100]; printf("Enter source string\n"); gets(original); printf("Enter string to concatenate\n"); gets(add); concatenate_string(original, add); printf("String after concatenation is \"%s\"\n", original); return 0; } void concatenate_string(char *original, char *add) { while(*original) original++; while(*add) { *original = *add; add++; original++; }

*original = '\0'; }

42. Reverse string This program reverses a string entered by the user. For example if a user enters a string "reverse me" then on reversing the string will be "em esrever". We show you two different methods to reverse string the first one uses strrev library function of string.h header file and in second we make our own function to reverse string using pointers. If you are using first method then you must include string.h in your program. /* First Method */ #include<stdio.h> #include<conio.h> #include<string.h> main() { char arr[100]; printf("Enter a string to reverse\n"); gets(arr); strrev(arr); printf("Reverse of entered string is \n%s\n",arr); getch(); return 0; }

/* Second method */

Inverting string using pointer : Now we will invert string using pointer or without using library function strrev. #include<stdio.h> #include<string.h> void reverse(char*); main() { char string[100]; printf("Enter a string\n");

gets(string); reverse(string); printf("Reverse of entered string is \"%s\".\n", string); return 0; } void reverse(char *string) { int length, c; char *begin, *end, temp; length = strlen(string); begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp; begin++; end--; } } Output of program:

43. C palindrome program Palindrome in c programming: palindrome program in c language, c code to check if a string is a palindrome or not and for palindrome number. This program works as follows :- at first we copy the entered string into a new string, and then we reverse the new string and then compares it with original string. If both of them have same sequence of characters i.e. they are identical then the entered string is a palindrome otherwise not. To perform copy, reverse and compare operations we use strcpy, strrev and strcmp functions

of string.h respectively, if you do not wish to use these functions see another code below in which we create our own functions to check palindrome. Some palindrome strings examples are "dad", "radar", "madam" etc. #include<stdio.h> #include<conio.h> #include<string.h> main() { char a[100], b[100]; printf("Enter the string to check if it is a palindrome\n"); gets(a); strcpy(b,a); strrev(b); if( strcmp(a,b) == 0 ) printf("Entered string is a palindrome.\n"); else printf("Entered string is not a pailndrome.\n"); getch(); return 0; } Output of program:

Palindrome number in C #include<stdio.h> main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or not\n"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10;

} if ( n == reverse ) printf("%d is a palindrome number.\n", n); else printf("%d is not a palindrome number.\n", n); return 0; } C program check palindrome #include<stdio.h> int is_palindrome(char*); void copy_string(char*, char*); void reverse_string(char*); int string_length(char*); int compare_string(char*, char*); main() { char string[100]; int result; printf("Enter a string\n"); gets(string); result = is_palindrome(string); if ( result == 1 ) printf("\"%s\" is a palindrome string.\n", string); else printf("\"%s\" is not a palindrome string.\n", string); return 0; } int is_palindrome(char *string) { int check, length; char *reverse; length = string_length(string); reverse = (char*)malloc(length+1); copy_string(reverse, string); reverse_string(reverse); check = compare_string(string, reverse);

free(reverse); if ( check == 0 ) return 1; else return 0; } int string_length(char *string) { int length = 0; while(*string) { length++; string++; } return length; } void copy_string(char *target, char *source) { while(*source) { *target = *source; source++; target++; } *target = '\0'; } void reverse_string(char *string) { int length, c; char *begin, *end, temp; length = string_length(string); begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++;

for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp;

begin++; end--; } } int compare_string(char *first, char *second) { while(*first) { if (*first == *second) { first++; second++; } else return -1; } return 0; }

44. Remove vowels in string Remove vowels string c: c program to remove or delete vowels from a string, if the input string is "c programming" then output will be "c prgrmmng". In the program we create a new string and process entered string character by character, and if a vowel is found it is not added to new string otherwise the character is added to new string, after the string ends we copy the new string into original string. Finally we obtain a string without any vowels. #include<stdio.h> #include<stdlib.h> #include<string.h> #define TRUE 1 #define FALSE 0 int check_vowel(char); main() { char string[100], *temp, *pointer, ch, *start; printf("Enter a string\n"); gets(string); temp = string; pointer = (char*)malloc(100);

start = pointer; while(*temp) { ch = *temp; if ( !check_vowel(ch) ) { *pointer = ch; pointer++; } temp++; } *pointer = '\0'; pointer = start; strcpy(string, pointer); /* If you wish to convert original string */ free(pointer); printf("String after removing vowel is \"%s\"\n", string); return 0; } int check_vowel(char a) { if ( a >= 'A' && a <= 'Z' ) a = a + 'a' - 'A'; if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return TRUE; return FALSE; }

45. C substring C substring: c programming code to find a substring from a given string and for all substrings of a string (see below), For example substrings of string "the" are "t", "th", "the", "h", "he" and "e" to find substring we create our own c substring function which returns a pointer to string. String address, length of substring required and position from where to extract substring are the three arguments passed to function. String.h does not contain any library function to directly find substring. #include<stdio.h> #include<malloc.h> char* substring(char*, int, int); main()

{ char string[100], *pointer; int position, length; printf("Enter a string\n"); gets(string); printf("Enter the position and length of substring\n"); scanf("%d%d",&position, &length); pointer = substring( string, position, length); printf("Required substring is \"%s\"\n", pointer); return 0; } /* C substring function code: It returns a pointer to the substring */ char *substring(char *string, int position, int length) { char *pointer, *temp; int c; pointer = malloc(length+1); temp = pointer; for( c = 0; c < position -1 ; c++ ) string++; for( c = 0 ; c < length ; c++ ) { *pointer = *string; pointer++; string++; } *pointer='\0'; pointer = temp; return pointer; }

Code output:

C code for all substrings of a string #include<stdio.h> #include<string.h> #include<malloc.h> char* substring(char*, int, int); main() { char string[100], *pointer; int position = 1, length = 1, temp, string_length; printf("Enter a string\n"); gets(string); temp = string_length = strlen(string); printf("Substring of \"%s\" are\n", string); while ( position <= string_length ) { while ( length <= temp ) { pointer = substring(string, position, length); printf("%s\n", pointer); length++; } temp--; position++; length = 1; } return 0; } char *substring(char *string, int position, int length) { char *pointer, *temp; int c; pointer = malloc(length+1);

temp = pointer; for( c = 0 ; c < position -1 ; c++ ) string++; for( c = 0 ; c < length ; c++ ) { *pointer = *string; pointer++; string++; } *pointer = '\0'; pointer = temp; return pointer; } Substring code output:

46. C program to sort a string in alphabetic order

C program to sort a string in alphabetic order: For example if user will enter a string "programming" then output will be "aggimmnoprr" or output string will contain characters in alphabetical order. #include<stdio.h> #include<stdlib.h> #include<string.h> main() { char string[100], ch, *pointer, *result, *temp; int c, length; printf("Enter a string\n"); gets(string); length = strlen(string); temp = result = (char*)malloc(length+1); pointer = string; for ( ch = 'a' ; ch <= 'z' ; ch++ ) { for ( c = 0 ; c < length ; c++ ) { if ( *pointer == ch ) { *result = *pointer; result++; } pointer++; } pointer = string; } *result = '\0'; result = temp; strcpy(string, result); free(result); printf("%s\n", string); return 0; }

47. C program remove spaces, blanks from a string C code to remove spaces or excess blanks from a string, For example consider the string "c programming" there are two spaces in this string, so our program will print a string "c programming". It will remove spaces when they occur more than one time consecutively in string anywhere. #include<stdio.h> #include<string.h> #include<malloc.h> #define SPACE ' ' main() { char string[100], *blank, *start, *end; int length; printf("Enter a string\n"); gets(string); length = strlen(string); blank = string; end = start = (char*)malloc(length+1); while(*blank) { if ( *blank == SPACE && *(blank+1) == SPACE ) {} else { *start = *blank; start++; } blank++; } *start='\0'; start = end; printf("%s", start); return 0; }

48. strlwr, strupr in c

Here we will change string case with and without strlwr, strupr functions. stwlwr in c #include<stdio.h> #include<string.h> int main() { char string[] = "Strlwr in C"; printf("%s\n",strlwr(string)); return 0; } strupr in c #include<stdio.h> #include<string.h> main() { char string[] = "strupr in c"; printf("%s\n",strupr(string)); return 0; } Change string to upper case without strupr #include<stdio.h> void upperString(char*); main() { char string[100]; printf("Enter a string to convert it into upper case\n"); gets(string); upperString(string); printf("Entered string in upper case is \"%s\"\n", string); return 0; } void upperString(char *string)

{ while(*string) { if ( *string >= 'a' && *string <= 'z' ) { *string = *string - 32; } string++; } } Change string to lower case without strlwr #include<stdio.h> void lowerString(char*); main() { char string[100]; printf("Enter a string to convert it into lower case\n"); gets(string); lowerString(string); printf("Entered string in lower case is \"%s\"\n", string); return 0; } void lowerString(char *string) { while(*string) { if ( *string >= 'A' && *string <= 'Z' ) { *string = *string + 32; } string++; } }

49. C program to swap two strings C program to swap strings.

#include<stdio.h> #include<string.h> #include<malloc.h> #include<conio.h> main() { char first[100], second[100], *temp; printf("Enter the first string "); gets(first); printf("Enter the second string "); gets(second); printf("\nBefore Swapping\n"); printf("First string: %s\n",first); printf("Second string: %s\n\n",second); temp = (char*)malloc(100); strcpy(temp,first); strcpy(first,second); strcpy(second,temp); printf("After Swapping\n"); printf("First string: %s\n",first); printf("Second string: %s\n",second); getch(); return 0; }

Output of program

50. Program to find frequency of characters in a string This program computes frequency of characters in a string i.e. which character is present how many times in a string. For example in the string "code" each of the character 'c', 'o', 'd', 'e' has occured one time. To make things easy we have first convert the entered string into lower case using strlwr function #include<stdio.h> #include<conio.h> #include<string.h> main() { char string[100], ch; int c, num[26], length; printf("Enter a string\n"); gets(string); strlwr(string); for ( c = 0 ; c < 26 ; c++ ) num[c] = 0; length = strlen(string); for ( c = 0 ; c < length ; c++ ) { for (ch = 'a' ; ch <= 'z' ; ch++ ) { if ( string[c] == ch ) num[ch-'a']++; }

} for ( c = 0 ; c < 26 ; c++ ) printf("%c occurs %d times in the entered string.\n",c+'a',num[c]); getch(); return 0; } Output of program:

51. Program to copy files This program copies a file, firstly you will specify the file to copy and then you will enter the name of target file, You will have to mention the extension of file also. We will open the file that we wish to copy in read mode and target file in write mode. #include<stdio.h>

#include<conio.h> #include<stdlib.h> int main() { char ch, file1[20], file2[20]; FILE *fs,*ft; printf("Enter name of file to copy "); gets(file1); fs = fopen(file1,"r"); if( fs == NULL ) { perror("Error "); printf("Press any key to exit...\n"); getch(); exit(EXIT_FAILURE); } printf("Enter name of target file "); gets(file2); ft = fopen(file2,"w"); if( ft == NULL ) { perror("Error "); fclose(fs); printf("Press any key to exit...\n"); getch(); exit(EXIT_FAILURE); } while( ( ch = fgetc(fs) ) != EOF ) fputc(ch,ft); printf("File copied successfully.\n"); getch(); fclose(fs); fclose(ft); return 0; }

Output of the above program is shown in image below :-

52. C program to merge two files This c program merges two files and store their contents in an another file. The files which are to be merged are opened in read mode and the file which contains content of both the files is opened in write mode. To merge two files first we open a file and read it character by character and store the read contents in another file then we read the contents of another file and store it in file, we read two files until EOF ( end of file ) is reached. #include<stdio.h> #include<conio.h> #include<stdlib.h> main() { FILE *fs1, *fs2, *ft; char ch, file1[20], file2[20], file3[20]; printf("Enter name of first file "); gets(file1); printf("Enter name of second file "); gets(file2); printf("Enter name of file which will store contents of two files "); gets(file3);

fs1 = fopen(file1,"r"); fs2 = fopen(file2,"r"); if( fs1 == NULL || fs2 == NULL ) { perror("Error "); printf("Press any key to exit...\n"); getch(); exit(EXIT_FAILURE); } ft = fopen(file3,"w"); if( ft == NULL ) { perror("Error "); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while( ( ch = fgetc(fs1) ) != EOF ) fputc(ch,ft); while( ( ch = fgetc(fs2) ) != EOF ) fputc(ch,ft); printf("Two files were merged into %s file successfully.\n",file3); fclose(fs1); fclose(fs2); fclose(ft); getch(); return 0; } .

Output of above program is shown in image below :-

53. C program to list files in directory This program list all files present in a directory/folder in which this executable file is present. For example if this executable file is present in C:\\TC\\BIN then it will lists all the files present in C:\\TC\\BIN. #include<stdio.h> #include<conio.h> #include<dir.h> main() { int done; struct ffblk a; printf("Press any key to view the files in the current directory\n"); getch(); done = findfirst("*.*",&a,0); while(!done) { printf("%s\n",a.ff_name); done = findnext(&a); }

getch(); return 0; } Output c program to list files is shown in image below :-

Obviously you will get a different output when you will execute this file on your computer.

54. C program to delete a file This c program deletes a file which is entered by the user, the file to be deleted should be present in the directory in which the executable file of this program is present. Extension of the file should also be entered, also note that deleted file doesn't go to recycle bin, remove macro is used to delete the file. If there is an error in deleting the file then an error will be displayed using perror function. #include<stdio.h> #include<conio.h> int main() { int status; char fname[25]; printf("Enter the name of file you wish to delete "); gets(fname); status = remove(fname);

if( status == 0 ) printf("%s file deleted successfully\n",fname); else { printf("Unable to delete the file\n"); perror("Error "); } getch(); return 0; } Sample output of the above program is shown in image below :-

55. C program to play media file If you wish to play file in Windows Media Player use #include<stdlib.h> main() { char *pointer = "\"C:\\Program Files\\Windows Media Player\\wmplayer.exe\" e:\\songs\\brazil.mp3"; system(pointer); return 0; }

If using VLC Media Player use the following code: #include<stdlib.h> main() { char *pointer = "\"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\" e:\\songs\\brazil.mp3"; system(pointer); return 0; }

56. C program to generate random numbers This c program generates random numbers using random function, randomize function is used to initialize random number generator. If you don't use randomize function then you will get same random numbers each time you run the program. #include<stdio.h> #include<conio.h> #include<stdlib.h> main() { int n, max, num, c; printf("Enter the number of random numbers you want "); scanf("%d",&n); printf("Enter the maximum value of random number "); scanf("%d",&max); printf("%d random numbers from 0 to %d are :-\n",n,max); randomize(); for ( c = 1 ; c <= n ; c++ ) { num = random(max); printf("%d\n",num); } getch(); return 0; }

57. C program to add two complex numbers c program to add two complex numbers :- This program calculate the sum of two complex numbers which will be entered by the user and then printed their sum. User will have to enter the real and imaginary parts of two complex numbers. Then on our program we will add real parts and imaginary parts of complex numbers and then we add them and prints the complex number, i is the symbol used for iota. For example if user entered two complex numbers as (1 + 2i) and (4 + 6 i) then output of program will be (5+8i). #include<stdio.h> #include<conio.h> #include<stdlib.h> struct complex { int real; int img; }; main() { struct complex a, b, c; printf("Enter a and b where a + ib is the first complex number."); printf("\na = "); scanf("%d", &a.real); printf("b = "); scanf("%d", &a.img); printf("Enter c and d where c + id is the second complex number."); printf("\nc = "); scanf("%d", &b.real); printf("d = "); scanf("%d", &b.img); c.real = a.real + b.real; c.img = a.img + b.img; if ( c.img >= 0 ) printf("Sum of two complex numbers = %d + %di",c.real,c.img); else printf("Sum of two complex numbers = %d %di",c.real,c.img); getch(); return 0; }

Output of c program to add two complex numbers is shown in image below :-

58. C program to print date This c program prints current system date. To print date we will use getdate function. #include<stdio.h> #include<conio.h> #include<dos.h> main() { struct date d; getdate(&d); printf("Current system date is %d/%d/%d",d.da_day,d.da_mon,d.da_year); getch(); return 0; }

Output of program

59. C program to get ip address This c program prints ip (internet protocol) address of your computer, system function is used to execute the command ipconfig which prints ip address, subnet mask and default gateway. The code given below works for Windows xp and Windows 7. If you are using turbo c compiler then execute program from folder, it may not work when you are working in compiler and press Ctrl+F9 to run your program. #include<stdlib.h> main() { system("C:\\Windows\\System32\\ipconfig"); system("pause"); return 0; }

Output of program: ( In Windows XP )

60. C program to shutdown or turn off computer C Program to shutdown your computer :- This program turn off i.e shutdown your computer system. Firstly it will asks you to shutdown your computer if you press 'y' the your computer will shutdown in 30 seconds, system function of "stdlib.h" is used to run an executable file shutdown.exe which is present in C:\WINDOWS\system32 in windows-xp. You can use various options while executing shutdown.exe for example -s option shutdown the computer after 30 seconds, if you wish to shutdown immediately then you can write "shutdown -s -t 0" as an argument to system function. If you wish to restart your computer then you can write "shutdown -r". C programming code for Windows XP #include<stdio.h> #include<stdlib.h> main() { char ch; printf("Do you want to shutdown your computer now (y/n) "); scanf("%c",&ch);

if( ch == 'y' || ch == 'Y' ) system("C:\\WINDOWS\\System32\\shutdown -s"); return 0; } C programming code for Windows 7 #include<stdio.h> #include<stdlib.h> main() { char ch; printf("Do you want to shutdown your computer now (y/n)\n"); scanf("%c",&ch); if( ch == 'y' || ch == 'Y' ) system("C:\\WINDOWS\\System32\\shutdown /s"); return 0; } To shutdown immediately use "C:\\WINDOWS\\System32\\ shutdown /s /t 0". To restart use /r instead of /s.

Function of Conio.h
1. clrscr in C clrscr function clears the screen amd move the cursor to upper left hand corner of screen. #include<stdio.h> #include<conio.h> main() { printf("Press any key to clear the screen.\n"); getch(); clrscr(); printf("This appears after clearing the screen.\n"); printf("Press any key to exit...\n"); getch(); return 0; }

In the above program first we display the message "Press any key to clear the screen." using printf and then ask the user to press a key. When user will press a key screen will be cleared and another message will be printed. clrscr function does not work in Dev C++ compiler. Also do not use clrscr in graphics mode instead use cleardevice.

2. delline delline function deletes the line containing the cursor and move all lines below it one line up. #include<stdio.h> #include<conio.h> main() { printf("This line will be deleted when you press a key."); getch(); delline(); printf("Line deleted successfully."); getch(); return 0; }

3. getch in c getch in c language: getch function prompts the user to press a character and that character is not printed on screen. #include<stdio.h> #include<conio.h> main() { printf("Waiting for a character to be pressed from the keyboard to exit.\n"); getch(); return 0; } When you will run this program, the program will exit only when you press a character, note that we are talking about a character so try pressing numlock, shift key etc (program will not exit if you press these keys) as these are not characters. Also try the above program by removing getch(), in this case program will exit without waiting for a character being pressed from keyboard. Common use of getch is that you can view the

output (if any) of your program without having to open the output window if you are using turbo c compiler or if you are not running your program from command prompt. getch in c++ #include<iostream.h> #include<conio.h> main() { cout<<"Enter a character"; getch(); } getch in Dev C++ compiler getch works in dev c++ compiler, also note that it doesn't support all functions of conio.h as turbo c does.

4. getche in c getche function prompts the user to press a character and that character is printed on screen. #include<stdio.h> #include<conio.h> main() { printf("Waiting for a character to be pressed from the keyboard to exit."); getche(); return 0; } Run this program and press a character. Then view the user screen (Alt+F5) if using turbo c. You will find the character printed on the screen if you pressed a printable character. Try pressing enter or tab key (non printable) characters also.

5. gotoxy in c gotoxy in c: gotoxy function places cursor at a desired location on screen i.e. we can change cursor position using gotoxy function. Declaration : void gotoxy( int x, int y); where (x, y) is the position where we want to place the cursor.

#include<stdio.h> #include<conio.h> main() { int x, y; x = 10; y = 10; gotoxy(x, y); printf("C program to change cursor position."); getch(); return 0; } Output:

6. kbhit in C kbhit in c: kbhit function is used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file "conio.h". If a key has been pressed then it returns a non zero value otherwise returns zero. Declaration : int kbhit(); #include<stdio.h>

#include<conio.h> main() { while(!kbhit()) printf("You haven't pressed a key.\n"); return 0; } As long as in the above program user doesn't presses a key kbhit() return zero and (!0) i.e. 1 the condition in while loop is true and "Better Late Than Never" will be printed again and again. As a key is pressed from the keyboard the condition in while loop become false as now kbhit() will return a non-zero value and ( !(non-zero) = 0), so the control will come out of the while loop.

7. wherex in c wherex function return current horizontal cursor position. Declaration :- int wherex(); #include<stdio.h> #include<conio.h> main() { int x; printf("Hello"); x = wherex(); printf("Horizontal cursor position from where this text appears = %d\n",x); getch(); return 0; }

8. wherey in c wherey function return current vertical cursor position. Declaration :- int wherey(); #include<stdio.h> #include<conio.h>

main() { int y; printf("Hello\n"); y = wherey(); printf("Vertical cursor position from where this text appears = %d",y); getch(); return 0; }

9. textcolor in C textcolor function is used to change the color of drawing text in c programs. Declaration :- void textcolor(int color); where color is an integer variable. For example 0 means BLACK color, 1 means BLUE, 2 means GREEN and soon. You can also use write appropriate color instead of integer. For example you can write textcolor(YELLOW); to change text color to YELLOW. But use colors in capital letters only. #include<stdio.h> #include<conio.h> main() { textcolor(RED); cprintf("C programming"); getch(); return 0; } Code for blinking text #include<stdio.h> #include<conio.h> main() { textcolor(MAGENTA+BLINK); cprintf("C programming"); getch(); return 0; }

Note that we have used cprintf function instead of printf. This is because cprintf send formatted output to text window on screen and printf sends it to stdin. Output:

10. textbackground in C textbackground function is used to change of current background color in text mode. See available colors. Declaration : void textbackground(int color); #include<stdio.h> #include<conio.h> main() { textbackground(RED); cprintf("C program to change background color."); getch(); return 0; }

Functions of Math.h
1. abs in C - math.h abs is not a function but is a macro and is used for calculating absolute value of a number. C programming code for abs

#include<stdio.h> #include<math.h> main() { int number, result; printf("Enter a number to calculate it's absolute value "); scanf("%d",&number); result = abs(number); printf("Absolute value of %d = %d", number, result); getch(); return 0; } Output:

2. ceil in c - math.h #include<stdio.h> #include<math.h> main() { double number, result; printf("Enter a number to round it up\n"); scanf("%lf",&number);

result = ceil(number); printf("Original number = %lf\n", number); printf("Number rounded up = %lf\n", result); return 0; }

3. cos in c - math.h #include<stdio.h> #include<math.h> main() { double result, x = .25; result = cos(x); printf("The cos(%lf) = %lf\n", x, result); getch(); return 0; }

4. floor function Declaration :- double floor(double x); C programming code for floor #include<stdio.h> #include<math.h> main() { double number, result; printf("Enter a number to round it down "); scanf("%lf",&number); result = floor(number); printf("Original number = %lf\n", number); printf("Number rounded down = %lf", result); return 0;

} Output:

5. log function log function returns natural logarithm (base is e) of a number, where e is the exponential number. Declaration :- double log(double number); C programming code for log #include<stdio.h> #include<math.h> main() { double number, result; printf("Enter a number to calculate it's natural log (base is e) "); scanf("%lf",&number); result = log(number); printf("Natural log of %lf = %lf", number, result); return 0; }

Output:

6. log10 log10 function returns common logarithm (base is 10) of a number. Declaration :- double log10(double number); C programming code for log10 #include<stdio.h> #include<math.h> main() { double number, result; printf("Enter a number to calculate it's log (base is 10) "); scanf("%lf",&number); result = log10(number); printf("Common log of %lf = %lf", number, result); return 0; }

7. pow function pow function returns x raise to the power y where x and y are variables of double datatype. Declaration :- double pow(double a, double b); C programming code for pow #include<stdio.h> #include<math.h> main() { double a, b, result; printf("Enter a and b to calculate a^b "); scanf("%lf%lf",&a, &b); result = pow(a, b); printf("%lf raised to %lf = %lf", a, b, result); return 0; } Output:

8. sin function in C #include<stdio.h> #include<math.h> main() { double result, x = .75; result = sin(x); printf("The sin(%lf) = %lf\n", x, result); return 0; }

9. sqrt function sqrt function returns square root of a number. Declaration :- double sqrt(double number); C programming code for sqrt #include<stdio.h> #include<math.h> main() { double number, result; printf("Enter a number to calculate it's square root "); scanf("%lf",&number); result = sqrt(number); printf("Square root of %lf = %lf", number, result); return 0; }

Output:

Functions of Dos.h
1. delay function in C Delay in c: delay function is used to suspend execution of a program for a particular time. Declaration :- void delay(unsigned int); Here unsigned int is the number of milliseconds ( remember 1 second = 1000 milliseconds ). To use delay function in your program you should include the dos.h header file. C programming code for delay #include<stdio.h> #include<stdlib.h> main() { printf("This c program will exit in 10 seconds.\n"); delay(10000); return 0; } Above c program exits in ten seconds, after the printf function is executed the program waits for 10000 milliseconds or 10 seconds and then program termination occurs.

Delay in C program : If you don't wish to use delay function then you can use loops to produce delay in c program. #include<stdio.h> main() { int c = 1, d = 1; for ( c = 1 ; c <= 32767 ; c++ ) for ( d = 1 ; d <= 32767 ; d++ ) {} return 0; } We don't write any statement in the loop body. 2. getdate in C Program to print the current system date, getdate c code below explain how to use this function to print computer date. Getdate example C programming code to print date #include<stdio.h> #include<dos.h> main() { struct date d; getdate(&d); printf("Current system date is %d/%d/%d\n",d.da_day,d.da_mon,d.da_year); return 0; }

3. gettime in C gettime in c: gettime function is used to find current system time. We pass address of a structure varibale of type ( struct time ). C programming code for gettime

#include<stdio.h> #include<dos.h> main() { struct time t; gettime(&t); printf("Current system time is %d : %d : %d\n",t.ti_hour,t.ti_min,t.ti_sec); return 0; }

4. nosound in C nosound function turn off the PC speaker. Declaration : void nosound(); C programming code for nosound #include<dos.h> main() { sound(400); delay(1000); nosound(); return 0; } 5. setdate in C setdate function is used to change system date. C programming code for setdate #include<stdio.h> #include<conio.h> #include<dos.h> main() { struct date d; printf("Enter the new date ( day, month and year ) as integers "); scanf("%d%d%d",&d.da_day,&d.da_mon,&d.da_year);

setdate(&d); printf("Current system date is %d/%d/%d\n",d.da_day,d.da_mon,d.da_year); getch(); return 0; }

6. sleep in C Sleep function delays program execution for a given number of seconds. Declaration: void sleep(unsigned seconds); C programming code for sleep #include<stdio.h> #include<dos.h> main() { printf("Wait for 5 seconds to exit.\n"); sleep(5); return 0; } 7. sound in C Sound function produces the sound of a specified frequency. Used for adding music to c program, try to use some random values in loop, vary delay and enjoy. Declaration:- void sound(unsigned frequency); C programming code for sound #include<dos.h> main() { int a; for ( a = 200 ; a <= 1000 ; a = a + 20 ) { sound(a); delay(25); } nosound(); return 0;

Functions of Graphics.h
C graphics using graphics.h functions or WinBGIM (Windows 7 ) can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h in turbo c compiler you can make graphics programs, animations, projects and games.You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them. Following is a list of functions of graphics.h header file. Every function is discussed with the arguments it needs, its description, possible errors while using that function and a sample c graphics program with its output. 1. arc function in C Declaration :- void arc(int x, int y, int stangle, int endangle, int radius); arc function is used to draw an arc with center (x,y) and stangle specifies starting angle, endangle specifies the end angle and last parameter specifies the radius of the arc. arc function can also be used to draw a circle but for that starting angle and end angle should be 0 and 360 respectively. C programming source code for arc #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); arc(100, 100, 0, 135, 50); getch(); closegraph(); return 0; } In the above program (100,100) are coordinates of center of arc, 0 is the starting angle, 135 is the end angle and 50 specifies the radius of the arc. Output of program:

2. bar function in C Declaration :- void bar(int left, int top, int right, int bottom); bar function is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner are required to draw the bar. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the Xcoordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner.Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color use setfillstyle. C program #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI");

bar(100, 100, 200, 200); getch(); closegraph(); return 0; } Output of program:

3. bar3d function in C Declaration :- void bar3d(int left, int top, int right, int bottom, int depth, int topflag); bar3d function is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner of bar are required to draw the bar. left specifies the Xcoordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner, depth specifies the depth of bar in pixels, topflag determines whether a 3 dimensional top is put on the bar or not ( if it is non-zero then it is put otherwise not ).

Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color use setfillstyle. C program of bar3d #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); bar3d(100, 100, 200, 200, 20, 1); getch(); closegraph(); return 0; } Output of program:

4. circle function in C Declaration :- void circle(int x, int y, int radius); circle function is used to draw a circle with center (x,y) and third parameter specifies the radius of the circle. The code given below draws a circle. C program for circle #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); circle(100, 100, 50); getch(); closegraph(); return 0; } In the above program (100, 100) are coordinates of center of the circle and 50 is the radius of circle.

Output of program:

5. cleardevice function in C Declaration :- void cleardevice(); cleardevice function clears the screen in graphics mode and sets the current position to (0,0). Clearing the screen consists of filling the screen with current background color. C program for cleardevice #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); outtext("Press any key to clear the screen."); getch(); cleardevice(); outtext("Press any key to exit...");

getch(); closegraph(); return 0; } Note : Don't use clrscr in graphics mode.

6. closegraph function in C closegraph function closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph. Declaration :- void closegraph(); C code of closegraph #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); outtext("Press any key to close the graphics mode..."); getch(); closegraph(); return 0; }

7. drawpoly function in C drawpoly function is used to draw polygons i.e. triangle, rectangle, pentagon, hexagon etc. Declaration :- void drawpoly( int num, int *polypoints ); num indicates (n+1) number of points where n is the number of vertices in a polygon, polypoints points to a sequence of (n*2) integers . Each pair of integers gives x and y coordinates of a point on the polygon. We specify (n+1) points as first point coordinates should be equal to (n+1)th to draw a complete figure. To understand more clearly we will draw a triangle using drawpoly, consider for example the array :int points[] = { 320, 150, 420, 300, 250, 300, 320, 150};

points array contains coordinates of triangle which are (320, 150), (420, 300) and (250, 300). Note that last point(320, 150) in array is same as first. See the program below and then its output, it will further clear your understanding. C program for drawpoly #include<graphics.h> #include<conio.h> main() { int gd=DETECT,gm,points[]={320,150,420,300,250,300,320,150}; initgraph(&gd, &gm, "C:\\TC\\BIN"); drawpoly(4, points); getch(); closegraph(); return 0; } Output of program:

8. ellipse function in C Declarations of ellipse function :void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius); Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, stangle is the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies the X and Y radius of the ellipse. To draw a complete ellipse strangles and end angle should be 0 and 360 respectively. C program of ellipse #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BIN"); ellipse(100, 100, 0, 360, 50, 25); getch(); closegraph(); return 0; }

Output of program:

9. fillellipse function in C Declaration of fillellipse function :void fillellipse(int x, int y, int xradius, int yradius); x and y are coordinates of center of the ellipse, xradius and yradius are x and y radius of ellipse respectively. C program for fillellipse #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm;

initgraph(&gd, &gm, "C:\\TC\\BGI"); fillellipse(100, 100, 50, 25); getch(); closegraph(); return 0; } Output of program:

10. fillpoly function in C fillpoly function draws and fills a polygon. It require same arguments as drawpoly. Declaration :- void drawpoly( int num, int *polypoints ); For details of arguments see drawpoly. fillpoly fills using current fill pattern and color which can be changed using setfillstyle. C code #include<graphics.h> #include<conio.h>

main() { int gd=DETECT,gm,points[]={320,150,440,340,230,340,320,150}; initgraph(&gd, &gm, "C:\\TC\\BIN"); fillpoly(4, points); getch(); closegraph(); return 0; } Output of program :-

11. floodfill function Declaration :- void floodfill(int x, int y, int border); floodfill function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area.(x, y) is any point on the screen if (x,y) lies inside the area then inside will be filled otherwise outside will be filled,border specifies the color of boundary of area.

To change fill pattern and fill color use setfillstyle. Code given below draws a circle and then fills it. C code #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); setcolor(RED); circle(100,100,50); floodfill(100,100,RED); getch(); closegraph(); return 0; } In the above program a circle is drawn in RED color. Point (100,100) lies inside the circle as it is the center of circle, third argument to floodfill is RED which is color of boundary of circle. So the output of above program will be a circle filled with WHITE color as it is the default fill color. Output:-

12. getarcoords function in C

Declaration :- void getarccoords(struct arccoordstype *var); getarccoords function is used to get coordinates of arc which is drawn most recently. arccoordstype is a pre defined structure which is defined as follows :struct arccoordstype { int x, y; /* center point of arc */ int xstart, ystart; /* start position */ int xend, yend; /* end position */ }; address of a structure variable of type arccoordstype is passed to function getarccoords. C program of getarccoords #include<graphics.h> #include<conio.h> #include<stdio.h> main() { int gd = DETECT, gm; struct arccoordstype a; char arr[100]; initgraph(&gd, &gm,"C:\\TC\\BGI"); arc(250,200,0,90,100); getarccoords(&a); sprintf(arr,"(%d, %d)",a.xstart,a.ystart); outtextxy(360,195,arr); sprintf(arr,"(%d, %d)",a.xend,a.yend); outtextxy(245,85,arr); getch(); closegraph(); return 0; } In the above program we have drawn an arc and then we get the coordinates of end points of arc using getarccoords.Coordinates so obtained are displayed using outtextxy.

13. getbkcolor function in C getbkcolor function returns the current background color

Declaration : int getbkcolor(); e.g. color = getbkcolor(); // color is an int variable if current background color is GREEN then color will be 2. C program for getbkcolor #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, bkcolor; char a[100]; initgraph(&gd,&gm,"C:\\TC\\BGI"); bkcolor = getbkcolor(); sprintf(a,"Current background color = %d", bkcolor); outtextxy( 10, 10, a); getch(); closegraph(); return 0; } 14. getcolor function getcolor function returns the current drawing color. Declaration : int getcolor(); e.g. a = getcolor(); // a is an integer variable if current drawing color is WHITE then a will be 15. See colors in c graphics. C programming code for getcolor #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, drawing_color; char a[100]; initgraph(&gd,&gm,"C:\\TC\\BGI"); drawing_color = getcolor();

sprintf(a,"Current drawing color = %d", drawing_color); outtextxy( 10, 10, a ); getch(); closegraph(); return 0; } 15. getdrivername function getdrivername function returns a pointer to the current graphics driver. C program for getdrivername #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; char *drivername; initgraph(&gd, &gm, "C:\\TC\\BGI"); drivername = getdrivername(); outtextxy(200, 200, drivername); getch(); closegraph(); return 0; } 16. getimage function in c getimage function saves a bit image of specified region into memory, region can be any rectangle. Declaration:- void getimage(int left, int top, int right, int bottom, void *bitmap); getimage copies an image from screen to memory. Left, top, right, and bottom define the area of the screen from which the rectangle is to be copied, bitmap points to the area in memory where the bit image is stored. 17. getmaxcolor function getmaxcolor function returns maximum color value for current graphics mode and driver. Total number of colors available for current graphics mode and driver are ( getmaxcolor() + 1 ) as color numbering starts from zero. Declaration :- int getmaxcolor();

C program of getmaxcolor #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, max_colors; char a[100]; initgraph(&gd,&gm,"C:\\TC\\BGI"); max_colors = getmaxcolor(); sprintf(a,"Maximum number of colors for current graphics mode and driver = %d",max_colors+1); outtextxy(0, 40, a); getch(); closegraph(); return 0; } 18. getmaxx function in C getmaxx function returns the maximum X coordinate for current graphics mode and driver. Declaration :- int getmaxx(); C program for getmaxx #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, max_x; char array[100]; initgraph(&gd,&gm,"C:\\TC\\BGI"); max_x = getmaxx(); sprintf(array, "Maximum X coordinate for current graphics mode and driver = %d.",max_x); outtext(array); getch(); closegraph(); return 0;

} 19. getmaxy function in C getmaxy function returns the maximum Y coordinate for current graphics mode and driver. Declaration :- int getmaxy(); C program for getmaxy #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, max_y; char array[100]; initgraph(&gd,&gm,"C:\\TC\\BGI"); max_y = getmaxy(); sprintf(array, "Maximum Y coordinate for current graphics mode and driver is = %d.",max_y); outtext(array); getch(); closegraph(); return 0; } 20. getpixel function in C getpixel function returns the color of pixel present at location(x, y). Declaration :- int getpixel(int x, int y); C program for getpixel #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, color; char array[50]; initgraph(&gd,&gm,"C:\\TC\\BGI"); color = getpixel(0, 0);

sprintf(array,"color of pixel at (0,0) = %d",color); outtext(array); getch(); closegraph(); return 0; } As we haven't drawn anything on screen and by default screen is BLACK, therefore color of pixel at (0,0) is BLACK. So output of program will be color of pixel at (0,0) is 0, as 0 indicates BLACK color. 21. getx function in C getx function returns the X coordinate of current position. Declaration :- int getx(); C program of getx #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; char array[100]; initgraph(&gd, &gm, "C:\\TC\\BIN"); sprintf(array, "Current position of x = %d",getx()); outtext(array); getch(); closegraph(); return 0; }

22. gety function in C gety function returns the y coordinate of current position. Declaration :- int gety(); C programming source code for gety #include<graphics.h>

#include<conio.h> main() { int gd = DETECT, gm, y; char array[100]; initgraph(&gd, &gm, "C:\\TC\\BIN"); y = gety(); sprintf(array, "Current position of y = %d", y); outtext(array); getch(); closegraph(); return 0; } 23. graphdefaults function in C graphdefaults function resets all graphics settings to their defaults. Declaration :- void graphdefaults(); It resets the following graphics settings :

Sets the viewport to the entire screen. Moves the current position to (0,0). Sets the default palette colors, background color, and drawing color. Sets the default fill style and pattern. Sets the default text font and justification.

C programming source code for graphdefaults #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BIN"); setcolor(RED); setbkcolor(YELLOW); circle(250, 250, 50); getch();

graphdefaults(); getch(); closegraph(); return 0; } In the above program we have first changed the drawing color to RED and background color to YELLOW and then drawn a circle with (250, 250) as center and 50 as radius. When the user will press a key graphdefaults is called and both drawing and background color will be reset to their default values i.e. WHITE and BLACK respectively. 24. grapherrormsg function in C grapherrormsg function returns an error message string. Declaration :- char *grapherrormsg( int errorcode ); C programming code for grapherrormsg #include<graphics.h> #include<stdlib.h> #include<conio.h> main() { int gd, gm, errorcode; initgraph(&gd, &gm, "C:\\TC\\BIN"); errorcode = graphresult(); if(errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to exit."); getch(); exit(1); } getch(); closegraph(); return 0; } In the above program we have not written gd = DETECT. After running this program we get the output :Graphics error: Graphics hardware not detected Press any key to exit. 25. imagesize function in C

imagesize function returns the number of bytes required to store a bitimage. This function is used when we are using getimage. Declaration:- unsigned int imagesize(int left, int top, int right, int bottom); C programming code for imagesize #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, bytes; char array[100]; initgraph(&gd, &gm, "C:\\TC\\BIN"); circle(200, 200, 50); line(150, 200, 250, 200); line(200, 150, 200, 250); bytes = imagesize(150, 150, 250, 250); sprintf(array, "Number of bytes required to store required area = %d", bytes); outtextxy(10, 280, array); getch(); closegraph(); return 0; }

Output of program:

26. line function in C line function is used to draw a line from a point(x1,y1) to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points of the line.The code given below draws a line. Declaration :- void line(int x1, int y1, int x2, int y2); C programming code for line #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); line(100, 100, 200, 200);

getch(); closegraph(); return 0; } Above program draws a line from (100, 100) to (200, 200). Output of program:

27. lineto function in C lineto function draws a line from current position(CP) to the point(x,y), you can get current position using getx and gety function. C programming code for lineto #include<graphics.h> #include<conio.h>

main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); moveto(100, 100); lineto(200, 200); getch(); closegraph(); return 0; }

28. linerel function in C linerel function draws a line from the current position(CP) to a point that is a relative distance (x, y) from the CP, then advances the CP by (x, y). You can use getx and gety to find the current position. C programming code for linerel #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BIN"); moveto(250, 250); linerel(100, -100); getch(); closegraph(); return 0; } 29. moveto function in C moveto function changes the current position (CP) to (x, y) Declaration :- void moveto(int x, int y); C programming code for moveto #include<graphics.h>

#include<conio.h> main() { int gd = DETECT, gm; char msg[100]; initgraph(&gd, &gm, "C:\\TC\\BIN"); sprintf(msg, "X = %d, Y = %d",getx(),gety()); outtext(msg); moveto(50, 50); sprintf(msg, "X = %d, Y = %d", getx(), gety()); outtext(msg); getch(); closegraph(); return 0; } 30. moverel function in C moverel function moves the current position to a relative distance. Declaration :- void moverel(int x, int y); C programming code for moverel #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, x, y; char message[100]; initgraph(&gd, &gm, "C:\\TC\\BIN"); moveto(100, 100); moverel(100, -100); x = getx(); y = gety(); sprintf(message, "Current x position = %d and y position = %d", x, y); outtextxy(10, 10, message);

getch(); closegraph(); return 0; } 31. outtext function outtext function displays text at current position. Declaration :- void outtext(char *string); C programming code for outtext #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); outtext("To display text at a particular position on the screen use outtextxy"); getch(); closegraph(); return 0; } Do not use text mode functions like printf, gotoxy etc while working in graphics mode. Also note '\n' or other escape sequences do not work in graphics mode. You have to ensure that the text doesn't go beyond the screen while using outtext.

32. outtextxy function in C outtextxy function display text or string at a specified point(x,y) on the screen. Declaration :- void outtextxy(int x, int y, char *string); x, y are coordinates of the point and third argument contains the address of string to be displayed. C programming code for outtextxy #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm;

initgraph(&gd,&gm,"C:\\TC\\BGI"); outtextxy(100, 100, "Outtextxy function"); getch(); closegraph(); return 0; } 33. pieslice function in C #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); pieslice(200,200,0,135,100); getch(); closegraph(); return 0; }

Output of program:

34. putimage function in C putimage function outputs a bit image onto the screen. Declaration:- void putimage(int left, int top, void *ptr, int op); putimage puts the bit image previously saved with getimage back onto the screen, with the upper left corner of the image placed at (left, top). ptr points to the area in memory where the source image is stored. The op argument specifies a operator that controls how the color for each destination pixel on screen is computed, based on pixel already on screen and the corresponding source pixel in memory.

35. putpixel function in C putpixel function plots a pixel at location (x, y) of specified color. Declaration :- void putpixel(int x, int y, int color);

For example if we want to draw a GREEN color pixel at (35, 45) then we will write putpixel(35, 35, GREEN); in our c program, putpixel function can be used to draw circles, lines and ellipses using various algorithms. C programming code for putpixel #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); putpixel(25, 25, RED); getch(); closegraph(); return 0; } Output of this program will be a RED pixel on screen at (25, 25) . Try to spot that pixel with your eyes at left top portion of your computer screen. 36. rectangle function in C Declaration :- void rectangle(int left, int top, int right, int bottom); rectangle function is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner. The code given below draws a rectangle. c programming code for rectangle #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); rectangle(100,100,200,200); getch(); closegraph(); return 0;

} Output of program:

37. sector function in C sector function draws and fills an elliptical pie slice. Declaration :- void sector( int x, int y, int stangle, int endangle, int xradius, int yradius); C programming code for sector #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BIN"); sector(100, 100, 0, 135, 25, 35);

getch(); closegraph(); return 0; } 38. setbkcolor function in C Declaration :- void setbkcolor(int color); setbkcolor function changes current background color e.g. setbkcolor(YELLLOW) changes the current background color to YELLOW. Remember that default drawing color is WHITE and background color is BLACK. C programming code for setbkcolor #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); outtext("Press any key to change the background color to GREEN."); getch(); setbkcolor(GREEN); getch(); closegraph(); return 0; }

39. setcolor function in C Declaration :- void setcolor(int color); In Turbo Graphics each color is assigned a number. Total 16 colors are available. Strictly speaking number of available colors depends on current graphics mode and driver.For Example :- BLACK is assigned 0, RED is assigned 4 etc. setcolor function is used to change the current drawing color.e.g. setcolor(RED) or setcolor(4) changes the current drawing color to RED. Remember that default drawing color is WHITE. C programming code for setcolor #include<graphics.h>

#include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); /* drawn in white color */ circle(100,100,50); setcolor(RED); circle(200,200,50); /* drawn in red color */ getch(); closegraph(); return 0; } Output of program:

40. setfillstyle function in C setfillstyle function sets the current fill pattern and fill color. Declaration :- void setfillstyle( int pattern, int color); Different fill styles:

enum fill_styles { EMPTY_FILL, SOLID_FILL, LINE_FILL, LTSLASH_FILL, SLASH_FILL, BKSLASH_FILL, LTBKSLASH_FILL, HATCH_FILL, XHATCH_FILL, INTERLEAVE_FILL, WIDE_DOT_FILL, CLOSE_DOT_FILL, USER_FILL }; C programming source code for setfillstyle #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); setfillstyle(XHATCH_FILL, RED); circle(100, 100, 50); floodfill(100, 100, WHITE); getch(); closegraph(); return 0; } Output of program:

41. settextstyle function in C settextstyle function is used to change the way in which text appears, using it we can modify the size of text, change direction of text and change the font of text. Declaration :- void settextstyle( int font, int direction, int charsize); font argument specifies the font of text, Direction can be HORIZ_DIR (Left to right) or VERT_DIR (Bottom to top). Different fonts enum font_names { DEFAULT_FONT, TRIPLEX_FONT, SMALL_FONT, SANS_SERIF_FONT, GOTHIC_FONT, SCRIPT_FONT, SIMPLEX_FONT, TRIPLEX_SCR_FONT, COMPLEX_FONT,

EUROPEAN_FONT, BOLD_FONT }; C programming source code for settextstyle #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, x = 25, y = 25, font = 0; initgraph(&gd,&gm,"C:\\TC\\BIN"); for ( font = 0 ; font <= 10 ; font++) { settextstyle(font, HORIZ_DIR, 1); outtextxy(x, y, "Text with different fonts"); y = y + 25; } getch(); closegraph(); return 0; } Output:

42. setviewport function in C setviewport function sets the current viewport for graphics output. Declaration :- void setviewport(int left, int top, int right, int bottom, int clip);

setviewport function is used to restrict drawing to a particular portion on the screen. For example setviewport(100 , 100, 200, 200, 1); will restrict our drawing activity inside the rectangle(100,100, 200, 200). left, top, right, bottom are the coordinates of main diagonal of rectangle in which we wish to restrict our drawing. Also note that the point (left, top) becomes the new origin. C programming source code for setviewport #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, midx, midy; initgraph(&gd, &gm, "C:\\TC\\BGI"); midx = getmaxx()/2; midy = getmaxy()/2; setviewport(midx - 50, midy - 50, midx + 50, midy + 50, 1); circle(50, 50, 55); getch(); closegraph(); return 0; }

Output of program:

43. textheight function in C textheight function returns the height of a string in pixels. Declaration :- int textheight(char *string); C programming source code for textheight #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, height; char array[100]; initgraph(&gd, &gm, "C:\\TC\\BGI"); height = textheight("C programming");

sprintf(array,"Textheight = %d",height); outtext(array); getch(); closegraph(); return 0; } 44. textwidth function in C textwidth function returns the width of a string in pixels. Declaration :- int textwidth(char *string); C programming source code for textwidth #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, width; char array[100]; initgraph(&gd, &gm, "C:\\TC\\BG I"); width = textwidth("C programming"); sprintf(array,"Textwidth = %d",width); outtext(array); getch(); closegraph(); return 0; }

C Graphics Programs
1. C Program for Bresenham Circle Drawing algorithm # include<stdio.h> # include<conio.h> # include<graphics.h> # include<math.h> void main()

{ int gd=DETECT,gm; int r,x,y,p,xc=320,yc=240; initgraph(&gd,&gm,"C:\\TC\\BGI"); cleardevice(); printf("Enter the radius "); scanf("%d",&r); x=0; y=r; putpixel(xc+x,yc-y,1); p=3-(2*r); for(x=0;x<=y;x++) { if (p<0) { y=y; p=(p+(4*x)+6); } else { y=y-1; p=p+((4*(x-y)+10)); } putpixel(xc+x,yc-y,1); putpixel(xc-x,yc-y,2);

putpixel(xc+x,yc+y,3); putpixel(xc-x,yc+y,4); putpixel(xc+y,yc-x,5); putpixel(xc-y,yc-x,6); putpixel(xc+y,yc+x,7); putpixel(xc-y,yc+x,8); } getch(); closegraph(); }

2. C program to implement Bezier Curve Drawing Algorithm #include<stdio.h> #include<conio.h> #include<graphics.h> int x,y,z; void main() { float u; int gd,gm,ymax,i,n,c[4][3]; for(i=0;i<4;i++) { c[i][0]=0; c[i][1]=0; } printf("\n\n Enter four points : \n\n");

for(i=0; i<4; i++) { printf("\t X%d Y%d : ",i,i); scanf("%d %d",&c[i][0],&c[i][1]); } c[4][0]=c[0][0]; c[4][1]=c[0][1]; detectgraph(&gd,&gm); initgraph(&gd,&gm,"e:\\tc\\bgi"); ymax = 480; setcolor(13); for(i=0;i<3;i++) { line(c[i][0],ymax-c[i][1],c[i+1][0],ymax-c[i+1][1]); } setcolor(3); n=3; for(i=0;i<=40;i++) { u=(float)i/40.0; bezier(u,n,c); if(i==0) { moveto(x,ymax-y);} else { lineto(x,ymax-y); }

getch(); } getch(); } bezier(u,n,p) float u;int n; int p[4][3]; { int j; float v,b; float blend(int,int,float); x=0;y=0;z=0; for(j=0;j<=n;j++) { b=blend(j,n,u); x=x+(p[j][0]*b); y=y+(p[j][1]*b); z=z+(p[j][2]*b); } } float blend(int j,int n,float u) { int k; float v,blend; v=C(n,j); for(k=0;k<j;k++)

{ v*=u; } for(k=1;k<=(n-j);k++) { v *= (1-u); } blend=v; return(blend); } C(int n,int j) { int k,a,c; a=1; for(k=j+1;k<=n;k++) { a*=k; } for(k=1;k<=(n-j);k++) { a=a/k; } c=a; return(c); }

3. C Program to Implement Flood Fill Algorithm #include<conio.h> #include<stdio.h> #include<graphics.h> #include<dos.h> void fill_right(x,y) int x , y ; { if(getpixel(x,y) == 0)

{ putpixel(x,y,RED); fill_right(++x,y); x=x-1; fill_right(x,y-1); fill_right(x,y+1); } } void fill_left(x,y) int x , y ; { if(getpixel(x,y) == 0) { putpixel(x,y,RED); fill_left(--x,y); x=x+1; fill_left(x,y-1); fill_left(x,y+1); } } void main() { int x , y ,a[10][10]; int gd, gm ,n,i; detectgraph(&gd,&gm);

initgraph(&gd,&gm,"c:\\tc\\bgi"); printf("\n\n\tEnter the no. of edges of polygon : "); scanf("%d",&n); printf("\n\n\tEnter the cordinates of polygon :\n\n\n "); for(i=0;i<n;i++) { printf("\tX%d Y%d : ",i,i); scanf("%d %d",&a[i][0],&a[i][1]); } a[n][0]=a[0][0]; a[n][1]=a[0][1]; printf("\n\n\tEnter the seed pt. : "); scanf("%d%d",&x,&y); cleardevice(); setcolor(WHITE); for(i=0;i<n;i++) /*- draw poly -*/ { line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]); } fill_right(x,y); fill_left(x-1,y); getch(); }

4. Graphics program to Display Animation (Fireworks) #include<conio.h> #include<graphics.h> #include<stdio.h> #include<math.h> void main() { int gd,gm; int x,y; int i,j,kk; detectgraph(&gd,&gm); initgraph(&gd,&gm,"c:\\tc\\bgi"); setcolor(WHITE); line(0,400,640,400); rectangle(300,330,340,400); rectangle(310,320,330,330); setcolor(4); line(319,280,319,398); line(320,280,320,398); rectangle(320,280,330,300); outtextxy(340,280,"PRESS ANY KEY TO IGNITE THE ROCKET"); getch(); for(j=400;j<640;j++)

{ cleardevice(); setcolor(WHITE); line(0,j,640,j); rectangle(300,j-70,340,j); rectangle(310,j-80,330,j-70); setcolor(RED); line(319,280,319,400); line(320,280,320,400); rectangle(320,280,330,300); setcolor(YELLOW); circle(325,300,2); delay(5); } for(i=400;i>340;i--) { cleardevice(); setcolor(RED); line(319,i,319,i-120); line(320,i,320,i-120); rectangle(320,i-120,330,i-100); setcolor(YELLOW); circle(325,i-100,2); delay(25); }

cleardevice(); kk=0; for(j=100;j<350;j++) { if(j%20==0) { setcolor(kk); kk=kk+3; delay(50); } ellipse(320,30,0,360,j+100,j+0); } for(j=100;j<350;j++) { if(j%20==0) { setcolor(BLACK); delay(2); } ellipse(320,30,0,360,j+100,j+0); } cleardevice(); for(i=0;i<70;i++) { setcolor(i);

settextstyle(GOTHIC_FONT,HORIZ_DIR,6); outtextxy(110,150,"HAPPY NEWYEAR"); delay(90); } getch(); }

5. C Program to implement Boundary Fill Algorithm #include<stdio.h> #include<conio.h> #include<graphics.h> #include<dos.h> void fill_right(x,y) int x , y ; { if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED)) { putpixel(x,y,RED); fill_right(++x,y); x=x-1; fill_right(x,y-1); fill_right(x,y+1); } delay(1); }

void fill_left(x,y) int x , y ; { if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED)) { putpixel(x,y,RED); fill_left(--x,y); x=x+1; fill_left(x,y-1); fill_left(x,y+1); } delay(1); } void main() { int x,y,n,i; int gd=DETECT,gm; clrscr(); initgraph(&gd,&gm,"c:\\tc\\bgi"); /*- draw object -*/ line (50,50,200,50); line (200,50,200,300); line (200,300,50,300); line (50,300,50,50); /*- set seed point -*/

x = 100; y = 100; fill_right(x,y); fill_left(x-1,y); getch(); }

6. C Program for Bresenham line drawing algorithm # include <stdio.h> # include <conio.h> # include <graphics.h> void main() { int dx,dy,x,y,p,x1,y1,x2,y2; int gd,gm;

clrscr(); printf("\n\n\tEnter the co-ordinates of first point : "); scanf("%d %d",&x1,&y1); printf("\n\n\tEnter the co-ordinates of second point : "); scanf("%d %d",&x2,&y2); dx = (x2 - x1); dy = (y2 - y1); p = 2 * (dy) - (dx); x = x1; y = y1;

detectgraph(&gd,&gm); initgraph(&gd,&gm,"e:\\tc\\bgi"); putpixel(x,y,WHITE); while(x <= x2) { if(p < 0) { x=x+1; y=y; p = p + 2 * (dy); } else { x=x+1; y=y+1; p = p + 2 * (dy - dx); } putpixel(x,y,WHITE); } getch(); closegraph(); }

7. C Program for Character Generation #include<stdio.h>

#include<conio.h> #include<graphics.h> void main() { int gd=DETECT,gm,i,j; int a[20][20]= {{0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0}, {0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0}, {0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,0}, {1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0}, {0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0}, {0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0}, {0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0}}; initgraph(&gd,&gm,"c:\\tc\\bgi"); for(i=0;i<19;i++) { for(j=0;j<19;j++) { if(a[i][j]==1) putpixel(100+j,200+i,WHITE); } }

getch(); }

8. C Program for Cohen Sutherland Line Clipping Algorithm #include<stdio.h> #include<graphics.h> #include<conio.h> typedef unsigned int outcode; enum { TOP=0x1, BOTTOM=0x2, RIGHT=0x4, LEFT=0x8 }; void lineclip(x0,y0,x1,y1,xwmin,ywmin,xwmax,ywmax ) float x0,y0,x1,y1,xwmin,ywmin,xwmax,ywmax; { int gd,gm; outcode code0,code1,codeout; int accept = 0, done=0; code0 = calcode(x0,y0,xwmin,ywmin,xwmax,ywmax); code1 = calcode(x1,y1,xwmin,ywmin,xwmax,ywmax); do{ if(!(code0 | code1)) { accept =1 ; done =1; } else if(code0 & code1) done = 1; else { float x,y;

codeout = code0 ? code0 : code1; if(codeout & TOP) { x = x0 + (x1-x0)*(ywmax-y0)/(y1-y0); y = ywmax; } else if( codeout & BOTTOM) { x = x0 + (x1-x0)*(ywmin-y0)/(y1-y0); y = ywmin; } else if ( codeout & RIGHT) { y = y0+(y1-y0)*(xwmax-x0)/(x1-x0); x = xwmax; } else { y = y0 + (y1-y0)*(xwmin-x0)/(x1-x0); x = xwmin; } if( codeout == code0) {

x0 = x; y0 = y; code0=calcode(x0,y0,xwmin,ywmin,xwmax,ywmax); } else { x1 = x; y1 = y; code1 = calcode(x1,y1,xwmin,ywmin,xwmax,ywmax); } } } while( done == 0); if(accept) line(x0,y0,x1,y1); rectangle(xwmin,ywmin,xwmax,ywmax); getch(); } int calcode (x,y,xwmin,ywmin,xwmax,ywmax) float x,y,xwmin,ywmin,xwmax,ywmax; { int code =0; if(y> ywmax) code |=TOP; else if( y<ywmin) code |= BOTTOM; else if(x > xwmax) code |= RIGHT; else if ( x< xwmin)

code |= LEFT; return(code); } main() { float x2,y2,x1,y1,xwmin,ywmin,xwmax,ywmax; int gd=DETECT,gm; clrscr(); initgraph(&gd,&gm,"e:\\tc\\bgi"); printf("\n\n\tEnter the co-ordinates of Line :"); printf("\n\n\tX1 Y1 : "); scanf("%f %f",&x1,&y1); printf("\n\n\tX2 Y2 : "); scanf("%f %f",&x2,&y2); printf("\n\tEnter the co_ordinates of window :\n "); printf("\n\txwmin , ywmin : "); scanf("%f %f",&xwmin,&ywmin); printf("\n\txwmax , ywmax : "); scanf("%f %f",&xwmax,&ywmax); clrscr(); line(x1,y1,x2,y2); rectangle(xwmin,ywmin,xwmax,ywmax); getch(); clrscr(); lineclip(x1,y1,x2,y2,xwmin,ywmin,xwmax,ywmax );

getch(); closegraph(); }

9. C program to implement Digital Differential Analyzer Line drawing algorithm #include<stdio.h> #include<conio.h> #include<math.h> #include<graphics.h> void main() { int gd=DETECT,gm; int x1,x2,y1,y2,dx,dy,steps,k; float xi,yi,x,y; clrscr(); initgraph (&gd,&gm,"C:\\TC\\BGI"); printf("Enter the co-ordinates of the first point \n"); printf("x1= "); scanf("%d/n",&x1); printf("y1= "); scanf("%d/n",&y1); printf("Enter the co-ordinates of the second point \n"); printf("x2= "); scanf("%d/n",&x2); printf("y2= ");

scanf("%d/n",&y2); clrscr(); dx= x2-x1; dy= y2-y1; if (abs(dx) > abs(dy)) steps = abs(dx); else steps = abs(dy); xi=(float)dx/steps; yi=(float)dy/steps; x=x1; y=y1; for(k=0;k<steps;k++) { putpixel (x,y,BLUE); x=x+xi; y=y+yi; } getch(); closegraph(); }

10. C Program for Liang Barsky Line Clipping Algorithm #include<graphics.h> #include<dos.h>

#include<conio.h> #include<stdlib.h> void main() { int gd, gm ; int x1 , y1 , x2 , y2 ; int wxmin,wymin,wxmax, wymax ; float u1 = 0.0,u2 = 1.0 ; int p1 , q1 , p2 , q2 , p3 , q3 , p4 ,q4 ; float r1 , r2 , r3 , r4 ; int x11 , y11 , x22 , y22 ; clrscr(); printf("Enter the windows left xmin , top boundry ymin\n"); scanf("%d%d",&wxmin,&wymin); printf("Enter the windows right xmax ,bottom boundry ymax\n"); scanf("%d%d",&wxmax,&wymax); printf("Enter line x1 , y1 co-ordinate\n"); scanf("%d%d",&x1,&y1); printf("Enter line x2 , y2 co-ordinate\n"); scanf("%d%d",&x2,&y2); printf("liang barsky express these 4 inequalities using lpk<=qpk\n"); p1 = -(x2 - x1 ); q1 = x1 - wxmin ; p2 = ( x2 - x1 ) ; q2 = wxmax - x1 ; p3 = - ( y2 - y1 ) ; q3 = y1 - wymin ; p4 = ( y2 - y1 ) ; q4 = wymax - y1 ;

printf("p1=0 line is parallel to left clipping\n"); printf("p2=0 line is parallel to right clipping\n"); printf("p3=0 line is parallel to bottom clipping\n"); printf("p4=0 line is parallel to top clipping\n"); if( ( ( p1 == 0.0 ) && ( q1 < 0.0 ) ) || ( ( p2 == 0.0 ) && ( q2 < 0.0 ) ) || ( ( p3 == 0.0 ) && ( q3 < 0.0 ) ) || ( ( p4 == 0.0 ) && ( q4 < 0.0 ) ) ) { printf("Line is rejected\n"); getch(); detectgraph(&gd,&gm); initgraph(&gd,&gm,"c:\\tc\\bgi"); setcolor(RED); rectangle(wxmin,wymax,wxmax,wymin); setcolor(BLUE); line(x1,y1,x2,y2); getch(); setcolor(WHITE); line(x1,y1,x2,y2); getch(); } else { if( p1 != 0.0 )

{ r1 =(float) q1 /p1 ; if( p1 < 0 ) u1 = max(r1 , u1 ); else u2 = min(r1 , u2 ); } if( p2 != 0.0 ) { r2 = (float ) q2 /p2 ; if( p2 < 0 ) u1 = max(r2 , u1 ); else u2 = min(r2 , u2 ); } if( p3 != 0.0 ) { r3 = (float )q3 /p3 ; if( p3 < 0 ) u1 = max(r3 , u1 ); else u2 = min(r3 , u2 ); } if( p4 != 0.0 ) {

r4 = (float )q4 /p4 ; if( p4 < 0 ) u1 = max(r4 , u1 ); else u2 = min(r4 , u2 ); } if( u1 > u2 ) printf("line rejected\n"); else { x11 = x1 + u1 * ( x2 - x1 ) ; y11 = y1 + u1 * ( y2 - y1 ) ; x22 = x1 + u2 * ( x2 - x1 ); y22 = y1 + u2 * ( y2 - y1 ); printf("Original line cordinates\n"); printf("x1 = %d , y1 = %d, x2 = %d, y2 = %d\n",x1,y1,x2,y2); printf("Windows coordinate are \n"); printf("wxmin = %d, wymin = %d,wxmax = %d , wymax = %d ",wxmin,wymin,wxmax,wymax); printf("New coordinates are \n"); printf("x1 = %d, y1 = %d,x2 = %d , y2 = %d\n",x11,y11,x22,y22); detectgraph(&gd,&gm); initgraph(&gd,&gm,"C:\\TC\\BGI"); setcolor(2); rectangle(wxmin,wymax,wxmax,wymin); setcolor(1);

line(x1,y1,x2,y2); getch(); setcolor(0); line(x1,y1,x2,y2); setcolor(3); line(x11,y11,x22,y22); getch(); } } }

11. C Implementation of Mid-Point Ellipse Drawing Algorithm #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <time.h> #include <dos.h> int main(void) { int gd=DETECT,gm; int cenx,ceny; float Pk,a,b,x,y; clrscr(); printf("\n\n Enter 'a' and 'b': ");

scanf("%f%f",&a,&b); initgraph(&gd,&gm,"c:\\tc\\bgi"); cenx=getmaxx()/2; ceny=getmaxy()/2; Pk=b*b-b*a*a+0.25*a*a; x=0; y=b; putpixel(cenx+x,ceny+y,WHITE); putpixel(cenx+x,ceny-y,WHITE); putpixel(cenx-x,ceny+y,WHITE); putpixel(cenx-x,ceny-y,WHITE); while (2*x*b*b <= 2*y*a*a) { if (Pk<0) { x=x+1; y=y; Pk=Pk+2*x*b*b+3*b*b; } else { x=x+1; y=y-1; Pk=Pk+2*x*b*b+3*b*b-2*y*a*a+2*a*a; } putpixel(cenx+x,ceny+y,WHITE); putpixel(cenx+x,ceny-y,WHITE);

putpixel(cenx-x,ceny+y,WHITE); putpixel(cenx-x,ceny-y,WHITE); delay(40); } Pk=(x+0.5)*(x+0.5)*b*b+(y-1)*(y-1)*a*a-a*a*b*b; putpixel(cenx+x,ceny+y,WHITE); putpixel(cenx+x,ceny-y,WHITE); putpixel(cenx-x,ceny+y,WHITE); putpixel(cenx-x,ceny-y,WHITE); while (y>0) { if (Pk>0) { x=x; y=y-1; Pk=Pk-2*y*a*a+3*a*a; } else { x=x+1; y=y-1; Pk=Pk-2*y*a*a+3*a*a+2*x*b*b+2*b*b; } putpixel(cenx+x,ceny+y,WHITE); putpixel(cenx+x,ceny-y,WHITE); putpixel(cenx-x,ceny+y,WHITE); putpixel(cenx-x,ceny-y,WHITE);

delay(40); } gotoxy(1,25); printf ("\npress any key to exit."); getch(); closegraph(); return 0; }

12.. C Program For Oblique projection of a 3D object #include<stdio.h> #include<math.h> #include<graphics.h> main() { int x1,y1,x2,y2,gd,gm; int ymax,a[4][8]; float par[4][4],b[4][8]; int i,j,k,m,n,p; double L1,phi; a[0][0] = 100; a[1][0] = 100; a[2][0] = 100; a[0][1] = 200; a[1][1] = 100; a[2][1] = 100;

a[0][2] = 200; a[1][2] = 200; a[2][2] = 100; a[0][3] = 100; a[1][3] = 200; a[2][3] = 100; a[0][4] = 100; a[1][4] = 100; a[2][4] = 200;

a[0][5] = 200; a[1][5] = 100; a[2][5] = 200; a[0][6] = 200; a[1][6] = 200; a[2][6] = 200; a[0][7] = 100; a[1][7] = 200; a[2][7] = 200; phi = (double) (3.14*45.0)/180 ; L1 = 0.5; par[0][0] = 1; par[0][1] = 0; par[0][2] = L1*cos(phi); par[0][3] = 0; par[1][0] = 0; par[1][1] = 1; par[1][2] = L1*sin(phi); par[1][3] = 0; par[2][0] = 0; par[2][1] = 0; par[2][2] = 0; par[2][3] = 0; par[3][0] = 0; par[3][1] = 0; par[3][2] = 0; par[3][3] = 1;

m=4; n=4; p=8; for(i=0; i<m; i++) for(k=0; k<p; k++) b[i][k] = 0; for(i=0; i<m; i++) for(k=0; k<p; k++) for(j=0; j<n; j++) b[i][k] += (float)par[i][j] * a[j][k]; detectgraph(&gd,&gm); initgraph(&gd,&gm, "c:\\tc\\bgi"); ymax = getmaxy();

/*- front plane display -*/ for(j=0;j<3;j++) { x1=(int) b[0][j]; y1=(int) b[1][j]; x2=(int) b[0][j+1]; y2=(int) b[1][j+1]; line( x1,ymax-y1,x2,ymax-y2); } x1=(int) b[0][3]; y1=(int) b[1][3]; x2=(int) b[0][0]; y2=(int) b[1][0]; line( x1,ymax-y1,x2,ymax-y2);

/*- back plane display -*/ setcolor(11); for(j=4;j<7;j++) { x1=(int) b[0][j]; y1=(int) b[1][j]; x2=(int) b[0][j+1]; y2=(int) b[1][j+1]; line( x1,ymax-y1,x2,ymax-y2); } x1=(int) b[0][7]; y1=(int) b[1][7]; x2=(int) b[0][4]; y2=(int) b[1][4]; line( x1,ymax-y1,x2,ymax-y2); setcolor(13); for(i=0;i<4;i++) {

x1=(int) b[0][i]; y1=(int) b[1][i]; x2=(int) b[0][4+i]; y2=(int) b[1][4+i]; line( x1,ymax-y1,x2,ymax-y2); } getch(); getch(); }

13. C Program For Perspective projection of 3D Object

#include<stdio.h> #include<math.h> #include<graphics.h> main() { int x1,y1,x2,y2,gd,gm; int ymax,a[4][8]; float par[4][4],b[4][8]; int i,j,k,m,n,p; int xp, yp, zp, x, y, z; a[0][0] = 100; a[1][0] = 100; a[2][0] = -100; a[0][1] = 200; a[1][1] = 100; a[2][1] = -100; a[0][2] = 200; a[1][2] = 200; a[2][2] = -100; a[0][3] = 100; a[1][3] = 200; a[2][3] = -100; a[0][4] = 100; a[1][4] = 100; a[2][4] = -200; a[0][5] = 200; a[1][5] = 100; a[2][5] = -200;

a[0][6] = 200; a[1][6] = 200; a[2][6] = -200; a[0][7] = 100; a[1][7] = 200; a[2][7] = -200; detectgraph(&gd,&gm); initgraph(&gd,&gm, "c:\\tc\\bgi"); ymax = getmaxy(); xp = 300; yp = 320; zp = 100;

for(j=0; j<8; j++) { x = a[0][j]; y = a[1][j]; z = a[2][j]; b[0][j] = xp - ( (float)( x - xp )/(z - zp)) * (zp); b[1][j] = yp - ( (float)( y - yp )/(z - zp)) * (zp); } /*- front plane display -*/ for(j=0;j<3;j++) { x1=(int) b[0][j]; y1=(int) b[1][j]; x2=(int) b[0][j+1]; y2=(int) b[1][j+1]; line( x1,ymax-y1,x2,ymax-y2); } x1=(int) b[0][3]; y1=(int) b[1][3]; x2=(int) b[0][0]; y2=(int) b[1][0]; line( x1, ymax-y1, x2, ymax-y2); /*- back plane display -*/ setcolor(11);

for(j=4;j<7;j++) { x1=(int) b[0][j]; y1=(int) b[1][j]; x2=(int) b[0][j+1]; y2=(int) b[1][j+1]; line( x1, ymax-y1, x2, ymax-y2); } x1=(int) b[0][7]; y1=(int) b[1][7]; x2=(int) b[0][4]; y2=(int) b[1][4]; line( x1, ymax-y1, x2, ymax-y2); setcolor(7); for(i=0;i<4;i++) { x1=(int) b[0][i]; y1=(int) b[1][i]; x2=(int) b[0][4+i]; y2=(int) b[1][4+i]; line( x1, ymax-y1, x2, ymax-y2); } getch(); getch(); }

14. Simple C program for Scan Line Polygon Filling Algorithm #include <stdio.h> #include <conio.h> #include <graphics.h> main() {

int n,i,j,k,gd,gm,dy,dx; int x,y,temp; int a[20][2],xi[20]; float slope[20]; clrscr(); printf("\n\n\tEnter the no. of edges of polygon : "); scanf("%d",&n); printf("\n\n\tEnter the cordinates of polygon :\n\n\n "); for(i=0;i<n;i++) { printf("\tX%d Y%d : ",i,i); scanf("%d %d",&a[i][0],&a[i][1]); } a[n][0]=a[0][0]; a[n][1]=a[0][1]; detectgraph(&gd,&gm); initgraph(&gd,&gm,"c:\\tc\\bgi"); /*- draw polygon -*/ for(i=0;i<n;i++) { line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]); } getch(); for(i=0;i<n;i++) {

dy=a[i+1][1]-a[i][1]; dx=a[i+1][0]-a[i][0]; if(dy==0) slope[i]=1.0; if(dx==0) slope[i]=0.0; if((dy!=0)&&(dx!=0)) /*- calculate inverse slope -*/ { slope[i]=(float) dx/dy; } } for(y=0;y< 480;y++) { k=0; for(i=0;i<n;i++) { if( ((a[i][1]<=y)&&(a[i+1][1]>y))|| ((a[i][1]>y)&&(a[i+1][1]<=y))) { xi[k]=(int)(a[i][0]+slope[i]*(y-a[i][1])); k++; } } for(j=0;j<k-1;j++) /*- Arrange x-intersections in order -*/ for(i=0;i<k-1;i++) { if(xi[i]>xi[i+1])

{ temp=xi[i]; xi[i]=xi[i+1]; xi[i+1]=temp; } } setcolor(35); for(i=0;i<k;i+=2) { line(xi[i],y,xi[i+1]+1,y); getch(); }

} }

15. C Program for 3-D transformations #include<stdio.h> #include<conio.h> #include<graphics.h> #include<math.h> #include<stdlib.h> int xp[2],yp[2],z; void display(); void translate();

void scaling(); void rotation(); void matrixmul(int [4][4]); void main() { int gd=DETECT,gm; int ch,i; initgraph(&gd,&gm,"c:\\tc\\bgi"); for(i=0;i<2;i++) { printf("\nEnter X-coordinate of vertex %d : ",i+1); scanf("%d",&xp[i]); printf("\nEnter Y-coordinate of vertex %d : ",i+1); scanf("%d",&yp[i]); } printf("\nEnter The Z-axis For 3d Figure : "); scanf("%d",&z); clrscr(); cleardevice(); display(xp,yp); getche(); do { printf("----- MENU -----"); printf("\n1.TRANSLATION.");

printf("\t2.SCALING."); printf("\n3.ROTATION."); printf("\t4.EXIT."); printf("\nEnter Your Choice : "); scanf("%d",&ch); clrscr(); cleardevice(); display(xp,yp); switch(ch) { case 1 : translate(); break; case 2 : scaling(); break; case 3 : rotation(); break; case 4 : exit(0); default: outtextxy(1,66,"-PLEASE SELECT THE RIGHT OPTION-"); } } while(ch!=4); getch(); closegraph(); }

void translate() { int p[4][4]; int tx,ty,tz,i,j; for(i=0;i<4;i++) for(j=0;j<4;j++) p[i][j]=(i==j); printf("\nEnter The Translating Factor tx : "); scanf("%d",&tx); printf("\nEnter The Translating Factor ty : "); scanf("%d",&ty); printf("\nEnter The Translating Factor tz : "); scanf("%d",&tz); clrscr(); cleardevice(); display(); p[0][3]=tx; p[1][3]=ty; p[2][3]=tz; matrixmul(p); } void scaling() { int p[4][4]; int sx,sy,sz,i,j;

for(i=0;i<4;i++) for(j=0;j<4;j++) p[i][j]=(i==j); printf("\nEnter The Scaling Factor sx : "); scanf("%d",&sx); printf("\nEnter The Scaling Factor sy : "); scanf("%d",&sy); printf("\nEnter The Scaling Factor sz : "); scanf("%d",&sz); if(sx==0) sx=1; if(sy==0) sy=1; if(sz==0) sz=1; clrscr(); cleardevice(); p[0][0]=sx; p[1][1]=sy; p[2][2]=sz; p[3][3]=1; matrixmul(p); } void rotation() {

float res[4][1],p[4][4],t[4][1]; int ang,i,j,k,l,rch; float rad; for(i=0;i<4;i++) for(j=0;j<4;j++) p[i][j]=(i==j); printf("\nEnter The Rotating Angle : "); scanf("%d",&ang); rad=ang*0.0174; printf("\nChoose the axis of roration "); printf("\n1.X-axis"); printf("\n2.Y-axis"); printf("\n3.Z-axis"); printf("\nEnter Your Choice : "); scanf("%d",&rch); switch(rch) { case 1 : p[1][1]=cos(rad); p[1][2]=(-1)*sin(rad); p[2][1]=sin(rad); p[2][2]=cos(rad); break; case 2 : p[0][0]=cos(rad); p[2][0]=(-1)*sin(rad);

p[0][2]=sin(rad); p[2][2]=cos(rad); break; case 3 : p[0][0]=cos(rad); p[0][1]=(-1)*sin(rad); p[1][0]=sin(rad); p[1][1]=cos(rad); break; default : printf("\nInvalid Choice !"); } clrscr(); cleardevice(); for(i=0;i<2;i++) { t[0][0]=xp[i]; t[1][0]=yp[i]; t[2][0]=z; t[3][0]=1; for(j=0;j<4;j++) { for(k=0;k<1;k++) { res[j][k]=0;

for(l=0;l<4;l++) { res[j][k]=res[j][k]+(p[j][l]*t[l][k]); } } } xp[i]=res[0][0]; yp[i]=res[1][0]; z=res[2][0]; } display(xp,yp); } void display(int xp[2],int yp[2]) { int x3,y3,x4,y4; line(getmaxx()/2,0,getmaxx()/2,getmaxy()); line(0,getmaxy()/2,getmaxx(),getmaxy()/2); outtextxy(getmaxx()/2+5,getmaxy()/2+5,"(0,0)"); outtextxy(getmaxx()-50,getmaxy()/2+10,"X-Axis"); outtextxy(getmaxx()/2+10,20,"Y-Axis"); outtextxy(10,getmaxy()/2+10,"X'-Axis"); outtextxy(getmaxx()/2+10,getmaxy()-20,"Y'-Axis"); rectangle(getmaxx()/2+xp[0],getmaxy()/2-yp[0],getmaxx()/2+xp[1],getmaxy()/2-yp[1]); if(z>=xp[0]) {

x3=z+xp[0]; y3=z+yp[0]; x4=z+xp[1]; y4=z+yp[1]; rectangle(getmaxx()/2+x3,getmaxy()/2-y3,getmaxx()/2+x4,getmaxy()/2-y4); line(getmaxx()/2+xp[0],getmaxy()/2-yp[0],getmaxx()/2+x3,getmaxy()/2-y3); line(getmaxx()/2+xp[1],getmaxy()/2-yp[1],getmaxx()/2+x4,getmaxy()/2-y4); line(getmaxx()/2+xp[0],getmaxy()/2-yp[1],getmaxx()/2+x3,getmaxy()/2-y4); line(getmaxx()/2+xp[1],getmaxy()/2-yp[0],getmaxx()/2+x4,getmaxy()/2-y3); } else { x3=xp[0]-z; y3=yp[0]-z; x4=xp[1]-z; y4=yp[1]-z; rectangle(getmaxx()/2+x3,getmaxy()/2-y3,getmaxx()/2+x4,getmaxy()/2-y4); line(getmaxx()/2+xp[0],getmaxy()/2-yp[0],getmaxx()/2+x3,getmaxy()/2-y3); line(getmaxx()/2+xp[1],getmaxy()/2-yp[1],getmaxx()/2+x4,getmaxy()/2-y4); line(getmaxx()/2+xp[0],getmaxy()/2-yp[1],getmaxx()/2+x3,getmaxy()/2-y4); line(getmaxx()/2+xp[1],getmaxy()/2-yp[0],getmaxx()/2+x4,getmaxy()/2-y3); } } void matrixmul(int a[4][4]) {

float res[4][1],b[4][1]; int i,j,k,l; for(i=0;i<2;i++) { b[0][0]=xp[i]; b[1][0]=yp[i]; b[2][0]=z; b[3][0]=1; for(j=0;j<4;j++) { for(k=0;k<1;k++) { res[j][k]=0; for(l=0;l<4;l++) { res[j][k]=res[j][k]+(a[j][l]*b[l][k]); } } } xp[i]=res[0][0]; yp[i]=res[1][0]; } z=res[2][0]; display(xp,yp); }

16. C Program To Output The Olympic Symbol #include<stdio.h> #include<graphics.h> #include<conio.h> #include<math.h> #include<dos.h> void main() { int i=0,j=0,k=0,l=0,m=0,ch; float pi=3.1424,a,b,c,d,e; int gd=DETECT,gm; initgraph(&gd,&gm,"c:\\tc\\bgi"); printf("\n\nEnter 1 or 2 "); scanf("%d",&ch); printf("\n\nYou have entered %d",ch); getch(); clrscr(); switch(ch) { case 1 : while(i<360) { a=(pi/180)*i; setcolor(3); circle(120+100*sin(a),150-100*cos(a),10);

i++; delay(5); } while(j<360) { b=(pi/180)*j; setcolor(0); circle(280+100*sin(b),150-100*cos(b),10); j++; delay(5); } while(k<360) { c=(pi/180)*k; setcolor(4); circle(440+100*sin(c),150-100*cos(c),10); k++; delay(5); } while(l<360) { d=(pi/180)*l; setcolor(14); circle(200+100*sin(d),300-100*cos(d),10); l++;

delay(5); } while(m<360) { e=(pi/180)*m; setcolor(2); circle(370+100*sin(e),300-100*cos(e),10); m++; delay(5); } break; case 2 : while(i<360) { a=(pi/180)*i; setcolor(3); circle(120+100*sin(a),150-100*cos(a),10); i++; delay(5); } while(l<360) { d=(pi/180)*l; setcolor(14); circle(200+100*sin(d),300-100*cos(d),10); l++;

delay(5); } while(j<360) { b=(pi/180)*j; setcolor(0); circle(280+100*sin(b),150-100*cos(b),10); j++; delay(5); } while(k<360) { c=(pi/180)*k; setcolor(4); circle(440+100*sin(c),150-100*cos(c),10); k++; delay(5); } while(m<360) { e=(pi/180)*m; setcolor(2); circle(370+100*sin(e),300-100*cos(e),10); m++; delay(5);

} break; default: setcolor(13); outtextxy(190,220,"YOU HAVE ENTERED THE WRONG CHOICE!!"); } getch(); }

17. Paint program in C Paint program in c:- This program can draw different shapes using mouse such as line, circle, pixel and many other shapes. You can also change the color, clear the screen. Code of paint program in c is given below:/* To understand the code see output below the code, it will help you in understanding the code. */ C programming code #include<graphics.h> #include<dos.h> #include<math.h> #include<stdlib.h> #include<stdio.h> #include<conio.h> union REGS i, o; int leftcolor[15]; int get_key() { union REGS i,o; i.h.ah = 0; int86(22,&i,&o); return ( o.h.ah ); } void draw_color_panel()

{ int left, top, c, color; left = 100; top = 436; color = getcolor(); setcolor(GREEN); rectangle(4,431,635,457); setcolor(RED); settextstyle(TRIPLEX_FONT,0,2); outtextxy(10,431,"Colors : "); for( c = 1 ; c <= 15 ; c++ ) { setfillstyle(SOLID_FILL, c); bar(left, top, left+16, top+16); leftcolor[c-1] = left; left += 26; } setcolor(color); } void draw_shape_panel() { int left, top, c, color; left = 529; top = 45; color = getcolor(); setcolor(GREEN); rectangle(525,40,633,255); for( c = 1 ; c <= 7 ; c++ ) { rectangle(left, top, left+100, top+25); top += 30; } setcolor(RED); outtextxy(530,45,"Bar"); outtextxy(530,75,"Line"); outtextxy(530,105,"Pixel"); outtextxy(530,135,"Ellipse"); outtextxy(530,165,"Freehand"); outtextxy(530,195,"Rectangle"); outtextxy(530,225,"Clear"); setcolor(color); }

void change_color(int x, int y) { int c; for( c = 0 ; c <= 13 ; c++ ) { if( x > leftcolor[c] && x < leftcolor[c+1] && y > 437 && y < 453 ) setcolor(c+1); if( x > leftcolor[14] && x < 505 && y > 437 && y < 453 ) setcolor(WHITE); } } char change_shape(int x, int y) { if ( x > 529 && x < 625 && y > 45 && y < 70 ) return 'b'; else if ( x > 529 && x < 625 && y > 75 && y < 100 ) return 'l'; else if ( x > 529 && x < 625 && y > 105 && y < 130 ) return 'p'; else if ( x > 529 && x < 625 && y > 135 && y < 160 ) return 'e'; else if ( x > 529 && x < 625 && y > 165 && y < 190 ) return 'f'; else if ( x > 529 && x < 625 && y > 195 && y < 220 ) return 'r'; else if ( x > 529 && x < 625 && y > 225 && y < 250 ) return 'c'; } void showmouseptr() { i.x.ax = 1; int86(0x33,&i,&o); } void hidemouseptr() { i.x.ax = 2; int86(0x33,&i,&o); } void restrictmouseptr( int x1, int y1, int x2, int y2) { i.x.ax = 7; i.x.cx = x1; i.x.dx = x2; int86(0x33,&i,&o); i.x.ax = 8;

i.x.cx = y1; i.x.dx = y2; int86(0x33,&i,&o); } void getmousepos(int *button,int *x,int *y) { i.x.ax = 3; int86(0x33,&i,&o); *button = o.x.bx; *x = o.x.cx; *y = o.x.dx; } main() { int gd = DETECT,gm; int maxx,maxy,x,y,button,prevx,prevy,temp1,temp2,key,color; char ch = 'f' ; // default free-hand drawing initgraph(&gd,&gm,"C:\\TC\\BGI"); maxx = getmaxx(); maxy = getmaxy(); setcolor(BLUE); rectangle(0,0,maxx,maxy); setcolor(WHITE); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); outtextxy(maxx/2-180,maxy-28,"www.programmingsimplified.com"); draw_color_panel(); draw_shape_panel(); setviewport(1,1,maxx-1,maxy-1,1); restrictmouseptr(1,1,maxx-1,maxy-1); showmouseptr(); rectangle(2,2,518,427); setviewport(1,1,519,428,1); while(1) { if(kbhit()) { key = get_key(); if( key == 1 )

{ closegraph(); exit(0); } } getmousepos(&button,&x,&y); if( button == 1 ) { if( x > 4 && x < 635 && y > 431 && y < 457 ) change_color( x, y ); else if ( x > 529 && x < 625 && y > 40 && y < 250 ) ch = change_shape( x, y ); temp1 = x ; temp2 = y ; if ( ch == 'f' ) { hidemouseptr(); while( button == 1 ) { line(temp1,temp2,x,y); temp1 = x; temp2 = y; getmousepos(&button,&x,&y); } showmouseptr(); } while( button == 1) getmousepos(&button,&x,&y); /* to avoid interference of mouse while drawing */ hidemouseptr(); if( ch == 'p') putpixel(x,y,getcolor()); else if ( ch == 'b' ) { setfillstyle(SOLID_FILL,getcolor()); bar(temp1,temp2,x,y); } else if ( ch == 'l') line(temp1,temp2,x,y); else if ( ch == 'e') ellipse(temp1,temp2,0,360,abs(x-temp1),abs(y-temp2)); else if ( ch == 'r' ) rectangle(temp1,temp2,x,y);

else if ( ch == 'c' ) { ch = 'f'; // setting to freehand drawing clearviewport(); color = getcolor(); setcolor(WHITE); rectangle(2,2,518,427); setcolor(color); } showmouseptr(); } } } Output of program:

18. Press me button game in c, download press-me-button game Press me game in C:- In this game when you try to bring mouse near a button it moves away from the mouse, so you keep on trying pressing the button. In this game we have

the coordinates of current position of mouse pointer at every moment of time, whenever we find mouse pointer very close to button we move the button suitably. C programming code #include<stdio.h> #include<conio.h> #include<dos.h> #include<graphics.h> #include<stdlib.h> union REGS i, o; int left = 265, top = 250; void initialize_graphics_mode() { int gd = DETECT, gm, error; initgraph(&gd,&gm,"C:\\TC\\BGI"); error = graphresult(); if( error != grOk ) { perror("Error "); printf("Press any key to exit...\n"); getch(); exit(EXIT_FAILURE); } } void showmouseptr() { i.x.ax = 1; int86(0x33,&i,&o); } void hidemouseptr() { i.x.ax = 2; int86(0x33,&i,&o); } void getmousepos(int *x,int *y) { i.x.ax = 3; int86(0x33,&i,&o); *x = o.x.cx; *y = o.x.dx; }

void draw_bar() { hidemouseptr(); setfillstyle(SOLID_FILL,CYAN); bar(190,180,450,350); showmouseptr(); } void draw_button(int x, int y) { hidemouseptr(); setfillstyle(SOLID_FILL,MAGENTA); bar(x,y,x+100,y+30); moveto(x+5,y); setcolor(YELLOW); outtext("Press me"); showmouseptr(); } void draw() { settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); outtextxy(155,451,"www.programmingsimplified.com"); setcolor(BLUE); rectangle(0,0,639,450); setcolor(RED); outtextxy(160,25,"Try to press the \"Press me\" button"); outtextxy(210,50,"Press escape key to exit"); setfillstyle(XHATCH_FILL,GREEN); setcolor(BLUE); bar(1,1,75,449); bar(565,1,638,449); showmouseptr(); draw_bar(); draw_button(left,top); } void initialize() { initialize_graphics_mode(); if( !initmouse() ) { closegraph(); printf("Unable to initialize the mouse"); printf("Press any key to exit...\n"); getch(); exit(EXIT_SUCCESS); }

draw(); } int initmouse() { i.x.ax = 0; int86(0x33,&i,&o); return ( o.x.ax ); } void get_input() { int x, y; while(1) { getmousepos(&x,&y); /* mouse pointer in left of button */ if( x >= (left-3) && y >= (top-3) && y <= (top+30+3) && x < left ) { draw_bar(); left = left + 4; if( left > 350 ) left = 190; draw_button(left,top); } /* mouse pointer in right of button */ else if( x <= (left+100+3) && y >= (top-3) && y <= (top+30+3) && x>(left+100)) { draw_bar(); left = left - 4; if( left < 190 ) left = 350; draw_button(left,top); } /* mouse pointer above button */ else if( x >= (left-3) && y >= (top-3) && y < (top) && x<=(left+100+3)) { draw_bar(); top = top + 4;

if( top > 320 ) top = 180; draw_button(left,top); } /* mouse pointer below button */ else if( x >= (left-3) && y > (top+30) && y <= (top+30+3) && x<=(left+100+3)) { draw_bar(); top = top - 4; if( top < 180 ) top = 320; draw_button(left,top); } if(kbhit()) { if( getkey() == 1 ) exit(EXIT_SUCCESS); } } } int getkey() { i.h.ah = 0; int86(22,&i,&o); return( o.h.ah ); } main() { initialize(); get_input(); return 0; } 19. Web browser project in c, c program to open a website/url This program opens a website entered by the user. User can open any website .It will launch mozilla firefox web browser to open a website so it should be installed on your computer, if you are using an another web-browser then you can change the path in the program. C programming code

#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<graphics.h> #include<dos.h> #include<string.h> void initialize_graphics_mode(); int get_key(); void draw(); union REGS i, o; main() { int key, i = 0, xpos, ypos, button; char arr[200], temp[5], *ptr; char a[] = "C:\\Progra~1\\Mozill~1\\firefox "; strcpy(arr,a); i = strlen(a); initialize_graphics_mode(); draw(); while(1) { if(kbhit()) key = get_key(); if((key>=97&&key<=122)||(key>=65&&key<=90)||key==46||key==47||key==63) { arr[i] = key; sprintf(temp,"%c",arr[i]); outtext(temp); if(getx()>470) { clearviewport(); moveto(5,2); } i++; } else if ( key == 13 ) { arr[i] = '\0'; system(arr); break; } else if ( key == 27 )

{ closegraph(); exit(EXIT_SUCCESS); } if(button==1&&xpos>=150&&xpos<=480&&ypos>=300&&ypos<=330) { system("C:\\Progra~1\\Mozill~1\\firefox www.programmingsimplified.com"); break; } key = -1; } closegraph(); return 0; } void initialize_graphics_mode() { int gd = DETECT, gm, errorcode; initgraph(&gd,&gm,"C:\\TC\\BGI"); errorcode = graphresult(); if( errorcode != grOk ) { printf("Graphics error : %s\n",grapherrormsg(errorcode)); printf("Press any key to exit...\n"); getch(); exit(EXIT_FAILURE); } } int get_key() { i.h.ah = 0; int86(22,&i,&o); return( o.h.al ); } void draw() { settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); outtextxy(275,11,"Web Browser"); outtextxy(155,451,"www.programmingsimplified.com"); outtextxy(5,105,"Enter URL : "); rectangle(120,100,600,130); setviewport(121,101,599,129,1); moveto(5,1); }

20. Traffic light program in c, traffic light simulation Traffic light Simulation: Traffic light program in c presents what happens in our daily life at traffic light signals. Firstly user will press a key to start the traffic light simulation. C programming code #include<graphics.h> #include<conio.h> #include<dos.h> #include<stdlib.h> main() { int gd = DETECT, gm, midx, midy; initgraph(&gd, &gm, "C:\\TC\\BGI"); midx = getmaxx()/2; midy = getmaxy()/2; setcolor(RED); settextstyle(SCRIPT_FONT, HORIZ_DIR, 3); settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy-10, "Traffic Light Simulation"); outtextxy(midx, midy+10, "Press any key to start"); getch(); cleardevice(); setcolor(WHITE); settextstyle(DEFAULT_FONT, HORIZ_DIR, 1); rectangle(midx-30,midy-80,midx+30,midy+80); circle(midx, midy-50, 22); setfillstyle(SOLID_FILL,RED); floodfill(midx, midy-50,WHITE); setcolor(BLUE); outtextxy(midx,midy-50,"STOP"); delay(2000); graphdefaults(); cleardevice(); setcolor(WHITE); rectangle(midx-30,midy-80,midx+30,midy+80); circle(midx, midy, 20); setfillstyle(SOLID_FILL,YELLOW); floodfill(midx, midy,WHITE); setcolor(BLUE); outtextxy(midx-18,midy-3,"READY"); delay(2000);

cleardevice(); setcolor(WHITE); rectangle(midx-30,midy-80,midx+30,midy+80); circle(midx, midy+50, 22); setfillstyle(SOLID_FILL,GREEN); floodfill(midx, midy+50,WHITE); setcolor(BLUE); outtextxy(midx-7,midy+48,"GO"); setcolor(RED); settextstyle(SCRIPT_FONT, HORIZ_DIR, 4); outtextxy(midx-150, midy+100, "Press any key to exit..."); getch(); closegraph(); return 0; }

21.C program to add, subtract, multiply and divide Complex Numbers, complex arithmetic C Program to add, subtract, multiply and divide complex numbers :- This program performs basic operations on complex numbers i.e addition, subtraction, multiplication and division. This is a menu driven program in which user will have to enter his/her choice to perform an operation. User can perform operations until desired. To easily handle a complex number a structure named complex has been used, which consists of two integers first integer is for real part of a complex number and second for imaginary part. C programming code #include<stdio.h> #include<conio.h> #include<stdlib.h> struct complex { int real; int img; }; main() { int choice, temp1, temp2, temp3; struct complex a, b, c;

while(1) { clrscr(); printf("Press 1 to add two complex numbers.\n"); printf("Press 2 to subtract two complex numbers.\n"); printf("Press 3 to multiply two complex numbers.\n"); printf("Press 4 to divide two complex numbers.\n"); printf("Press 5 to exit.\n"); printf("Enter your choice "); scanf("%d",&choice); if( choice == 5) exit(0); if(choice >= 1 && choice <= 4) { printf("Enter a and b where a + ib is the first complex number."); printf("\na = "); scanf("%d", &a.real); printf("b = "); scanf("%d", &a.img); printf("Enter c and d where c + id is the second complex number."); printf("\nc = "); scanf("%d", &b.real); printf("d = "); scanf("%d", &b.img); } if ( choice == 1 ) { c.real = a.real + b.real; c.img = a.img + b.img; if ( c.img >= 0 ) printf("Sum of two complex numbers = %d + %di",c.real,c.img); else printf("Sum of two complex numbers = %d %di",c.real,c.img); } else if ( choice == 2 ) { c.real = a.real - b.real; c.img = a.img - b.img; if ( c.img >= 0 ) printf("Difference of two complex numbers = %d + %di",c.real,c.img); else printf("Difference of two complex numbers = %d %di",c.real,c.img); } else if ( choice == 3 ) { c.real = a.real*b.real - a.img*b.img; c.img = a.img*b.real + a.real*b.img;

if ( c.img >= 0 ) printf("Multiplication of two complex numbers = %d + %di",c.real,c.img); else printf("Multiplication of two complex numbers = %d %di",c.real,c.img); } else if ( choice == 4 ) { if ( b.real == 0 && b.img == 0 ) printf("Division by 0 + 0i is not allowed."); else { temp1 = a.real*b.real + a.img*b.img; temp2 = a.img*b.real - a.real*b.img; temp3 = b.real*b.real + b.img*b.img; if ( temp1%temp3 == 0 && temp2%temp3 == 0 ) { if ( temp2/temp3 >= 0) printf("Division of two complex numbers = %d + %di",temp1/temp3,temp2/temp3); else printf("Division of two complex numbers = %d %di",temp1/temp3,temp2/temp3); } else if ( temp1%temp3 == 0 && temp2%temp3 != 0 ) { if ( temp2/temp3 >= 0) printf("Division of two complex numbers = %d + %d/%di",temp1/temp3,temp2,temp3); else printf("Division of two complex numbers = %d %d/%di",temp1/temp3,temp2,temp3); } else if ( temp1%temp3 != 0 && temp2%temp3 == 0 ) { if ( temp2/temp3 >= 0) printf("Division of two complex numbers = %d/%d + %di",temp1,temp3,temp2/temp3); else printf("Division of two complex numbers = %d %d/%di",temp1,temp3,temp2/temp3); } else { if ( temp2/temp3 >= 0) printf("Division of two complex numbers = %d/%d + %d/%di",temp1,temp3,temp2,temp3); else printf("Division of two complex numbers = %d/%d %d/%di",temp1,temp3,temp2,temp3);

} } } else printf("Invalid choice."); printf("\nPress any key to enter choice again..."); getch(); } }

22. Captcha program in C This program generates captcha, a captcha is a random code generated using some algorithm. We will use random function in our code. These are used in typing tutors and in website to check whether a human is operating on a website. C programming code #include<stdlib.h> #include<dos.h> #include<graphics.h> main() { int i = 0, key, num, midx, gd = DETECT, gm; char a[10]; initgraph(&gd,&gm,"C:\\TC\\BGI"); midx = getmaxx()/2; settextstyle(SCRIPT_FONT,HORIZ_DIR,5); settextjustify(CENTER_TEXT,CENTER_TEXT); setcolor(GREEN); outtextxy(midx,20,"CAPTCHA"); settextstyle(SCRIPT_FONT,HORIZ_DIR,2); outtextxy(midx,125,"Press any key to change the generated random code \"captcha\""); outtextxy(midx,150,"Press escape key to exit..."); setcolor(WHITE); setviewport(100,200,600,400,1); setcolor(RED); randomize(); while(1)

{ while(i<6) { num = random(3); if ( num == 0 ) a[i] = 65 + random(26); else if ( num == 1) a[i] = 97 + random(26); else a[i] = 48 + random(10); i++; } a[i] = '\0'; outtextxy(210,100,a); key = getch(); if( key == 27 ) exit(0); clearviewport(); i = 0; } } Output of program: /* escape key*/

/* 65 is the ascii value of A */ /* 97 is the ascii value of a */ /* 48 is the ascii value of 0 */

23. C program to move a car Program in c using graphics move a car. A car is made using two rectangles and two circles which act as tyres of car. A for loop is used to move the car forward by changing the rectangle and circle coordinates and erasing the previous contents on screen using clearviewport, you can also use cleardevice. Speed of car can be adjusted using delay function, more the delay lesser will be the speed or lesser the delay your car will move fast. In this program color of the car also keeps on changing, this is accomplished by incrementing the color value by one each time in for loop, you can also use random function for this purpose. Before you see a car moving you will be asked to press a key. C code #include<graphics.h> #include<dos.h> main() { int i, j = 0, gd = DETECT, gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); settextstyle(DEFAULT_FONT,HORIZ_DIR,2); outtextxy(25,240,"Press any key to view the moving car"); getch(); setviewport(0,0,639,440,1); for( i = 0 ; i <= 420 ; i = i + 10, j++ ) { rectangle(50+i,275,150+i,400); rectangle(150+i,350,200+i,400); circle(75+i,410,10); circle(175+i,410,10); setcolor(j); delay(100); if( i == 420 ) break; clearviewport(); } getch(); closegraph(); return 0; }

C Mouse Programs
1. C Program to check if mouse support is available or not /* Program to check if mouse driver is loaded or not */ C programming code #include<dos.h> #include<conio.h> int initmouse(); union REGS i, o; main() { int status; status = initmouse(); if ( status == 0 ) printf("Mouse support not available.\n"); else printf("Mouse support available.\n"); getch(); return 0; } int initmouse() { i.x.ax = 0; int86(0X33,&amp;i,&amp;o); return ( o.x.ax ); }

Output of program:

2. C Program to display mouse pointer in textmode /* Program to display mouse-pointer in text-mode */ #include<dos.h> #include<conio.h> int initmouse(); void showmouseptr(); union REGS i, o; main() { int status; status = initmouse(); if ( status == 0 ) printf("Mouse support not available.\n"); else showmouseptr(); getch(); return 0; }

int initmouse() { i.x.ax = 0; int86(0X33,&i,&o); return ( o.x.ax ); } void showmouseptr() { i.x.ax = 1; int86(0X33,&i,&o); }

3. C Program to display mouse pointer in graphics mode This program displays mouse pointer in graphics mode. First graphics mode is initialized and then mouse using initmouse. C programming code #include<graphics.h> #include<conio.h> #include<dos.h> int initmouse(); void showmouseptr(); union REGS i, o; main() { int status, gd = DETECT, gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); status = initmouse(); if ( status == 0 ) printf("Mouse support not available.\n"); else showmouseptr(); getch(); return 0; } int initmouse() { i.x.ax = 0; int86(0X33,&i,&o);

return ( o.x.ax ); } void showmouseptr() { i.x.ax = 1; int86(0X33,&i,&o); }

Output of program:

4. C Program to hide mouse pointer This program hides mouse pointer. We require to hide mouse pointer when we want to draw something on screen as it may interfere with drawing, after that we again make it visible. /* Program to show and hide mouse-pointer alternatively */ C programming code #include<graphics.h> #include<conio.h>

#include<dos.h> int initmouse(); void showmouseptr(); void hidemouseptr(); union REGS i, o; main() { int status, count = 1, gd = DETECT, gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); status = initmouse(); if ( status == 0 ) printf("Mouse support not available.\n"); else { showmouseptr(); while(count<=10) { getch(); count++; if(count%2==0) hidemouseptr(); else showmouseptr(); } } getch(); return 0; } int initmouse() { i.x.ax = 0; int86(0X33,&i,&o); return ( o.x.ax ); } void showmouseptr() { i.x.ax = 1; int86(0X33,&i,&o); } void hidemouseptr()

{ i.x.ax = 2; // to hide mouse int86(0X33,&i,&o); }

5. C Program to get current position of mouse pointer This program prints the x and y coordinates of current position of mouse pointer i.e. wherever you move the mouse coordinates of that point will be printed on the screen. /* Program to get mouse-pointer coordinates - where is the mouse */ C programming code #include<graphics.h> #include<conio.h> #include<stdio.h> #include<dos.h> int initmouse(); void showmouseptr(); void hidemouseptr(); void getmousepos(int*,int*,int*); union REGS i, o; main() { int gd = DETECT, gm, status, button, x, y, tempx, tempy; char array[50]; initgraph(&gd,&gm,"C:\\TC\\BGI"); settextstyle(DEFAULT_FONT,0,2); status = initmouse(); if ( status == 0 ) printf("Mouse support not available.\n"); else { showmouseptr(); getmousepos(&button,&x,&y); tempx = x; tempy = y; while(!kbhit()) {

getmousepos(&button,&x,&y); if( x == tempx && y == tempy ) {} else { cleardevice(); sprintf(array,"X = %d, Y = %d",x,y); outtext(array); tempx = x; tempy = y; } } } getch(); return 0; } int initmouse() { i.x.ax = 0; int86(0X33,&i,&o); return ( o.x.ax ); } void showmouseptr() { i.x.ax = 1; int86(0X33,&i,&o); } void getmousepos(int *button, int *x, int *y) { i.x.ax = 3; int86(0X33,&i,&o); *button = o.x.bx; *x = o.x.cx; *y = o.x.dx; }

Output of program:

6. C program to determine which mouse button is clicked This program print which mouse button is clicked whether left or right, coordinates of the point where button is clicked are also printed on the screen. /* Program to determine which mouse button is clicked */ C programming code #include<graphics.h> #include<conio.h> #include<dos.h> union REGS i, o; int initmouse() { i.x.ax = 0; int86(0X33,&i,&o); return ( o.x.ax ); } void showmouseptr()

{ i.x.ax = 1; int86(0X33,&i,&o); } void getmousepos(int *button, int *x, int *y) { i.x.ax = 3; int86(0X33,&i,&o); *button = o.x.bx; *x = o.x.cx; *y = o.x.dx; } main() { int gd = DETECT, gm, status, button, x, y; char array[50]; initgraph(&gd,&gm,"C:\\TC\\BGI"); settextstyle(DEFAULT_FONT,0,2); status = initmouse(); if ( status == 0 ) printf("Mouse support not available.\n"); else { showmouseptr(); getmousepos(&button,&x,&y); while(!kbhit()) { getmousepos(&button,&x,&y); if( button == 1 ) { button = -1; cleardevice(); sprintf(array,"Left Button clicked x = %d y = %d",x,y); outtext(array); } else if( button == 2 ) { button = -1; cleardevice(); sprintf(array,"Right Button clicked x = %d y = %d",x,y); outtext(array); } } } getch(); return 0;

7. C program to restrict mouse pointer This program restricts mouse pointer in a rectangle. When this program is executed the mouse pointer is restricted in a rectangle i.e. you can't move mouse pointer out of the rectangle. /* Program to restrict mouse-pointer */ C programming code #include<dos.h> #include<graphics.h> #include<conio.h> int initmouse(); void showmouseptr(); void hidemouseptr(); void restrictmouseptr(int, int, int, int); union REGS i, o; main() { int status, gd = DETECT, gm;

initgraph(&gd,&gm,"C:\\TC\\BGI"); settextstyle(DEFAULT_FONT,0,2); status = initmouse(); if ( status == 0 ) outtext("Mouse support not available.\n"); else { showmouseptr(); rectangle(120,70,520,410); restrictmouseptr(120,70,520,410); } getch(); return 0; } int initmouse() { i.x.ax = 0; int86(0X33,&i,&o); return ( o.x.ax ); } void showmouseptr() { i.x.ax = 1; int86(0X33,&i,&o); } void restrictmouseptr(int x1, int y1, int x2, int y2) { i.x.ax = 7; i.x.cx = x1; i.x.dx = x2; int86(0X33,&i,&o); i.x.ax = 8; i.x.cx = y1; i.x.dx = y2; int86(0X33,&i,&o); }

Output of program:

8. C program to restrict mouse pointer in a circle This program restricts mouse pointer in a circle i.e you can't move mouse out of a circle. When you try to bring mouse pointer outside the circle, mouse pointer is moved to it's previous location which is inside the circle. Code to restrict mouse in circle is given below :C programming code #include<graphics.h> #include<conio.h> #include<dos.h> #include<stdlib.h> #include<math.h> union REGS i, o;

int initmouse() { i.x.ax = 0; int86(0X33, &i, &o); return ( o.x.ax ); } void showmouseptr() { i.x.ax = 1; int86(0X33, &i, &o); } void hidemopuseptr() { i.x.ax = 2; int86(0X33,&i,&o); } void getmousepos(int *x, int *y) { i.x.ax = 3; int86(0X33, &i, &o); *x = o.x.cx; *y = o.x.dx; } void movemouseptr(int x, int y) { i.x.ax = 4; i.x.cx = x; i.x.dx = y; int86(0X33, &i, &o); } main() { int gd = DETECT, gm, midx, midy, radius, x, y, tempx, tempy; radius = 100; initgraph(&gd, &gm, "C:\\TC\\BGI"); if(!initmouse()) { closegraph(); exit(1); } midx = getmaxx()/2; midy = getmaxy()/2; showmouseptr(); movemouseptr(midx, midy); circle(midx, midy, radius); x = tempx = midx; y = tempy = midy;

while(!kbhit()) { getmousepos(&x, &y); if((pow(x-midx,2)+pow(y-midy,2)-pow(radius,2))>0) { movemouseptr(tempx, tempy); x = tempx; y = tempy; } tempx = x; tempy = y; } closegraph(); return 0; }

C Graphics Codes
1. Draw shapes using C This c graphics program draws basic shapes such as circle, line, rectangle, ellipse and display text on screen using c graphics. This can be a first graphics program for a beginner. C programming code #include<graphics.h> #include<conio.h> main() { int gd = DETECT,gm,left=100,top=100,right=200,bottom=200,x= 300,y=150,radius=50; initgraph(&gd, &gm, "C:\\TC\\BGI"); rectangle(left, top, right, bottom); circle(x, y, radius); bar(left + 300, top, right + 300, bottom); line(left - 10, top + 150, left + 410, top + 150); ellipse(x, y + 200, 0, 360, 100, 50); outtextxy(left + 100, top + 325, "My First C Graphics Program");

getch(); closegraph(); return 0; } Output of program:

2. C program draw bar chart This program draws bar chart using c graphics. Chart is drawn using bars filled with different styles and in different colors. C programming code #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm;

initgraph(&gd, &gm, "C:\\TC\\BGI"); setcolor(YELLOW); rectangle(0,30,639,450); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); setcolor(WHITE); outtextxy(275,0,"Bar Chart"); setlinestyle(SOLID_LINE,0,2); line(100,420,100,60); line(100,420,600,420); line(90,70,100,60); line(110,70,100,60); line(590,410,600,420); line(590,430,600,420); outtextxy(95,35,"Y"); outtextxy(610,405,"X"); outtextxy(85,415,"O"); setfillstyle(LINE_FILL,BLUE); bar(150,100,200,419); setfillstyle(XHATCH_FILL,RED); bar(225,150,275,419); setfillstyle(WIDE_DOT_FILL,GREEN); bar(300,200,350,419); setfillstyle(INTERLEAVE_FILL,MAGENTA); bar(375,125,425,419); setfillstyle(HATCH_FILL,BROWN); bar(450,175,500,419); getch(); return 0; }

Output of program:

3. C program to draw pie chart This c program draws a pie chart showing percentage of various components drawn with different filling styles and colors. C programming code #include<graphics.h> #include<conio.h> main() { int gd = DETECT, gm, midx, midy; initgraph(&gd, &gm, "C:\\TC\\BGI"); setcolor(MAGENTA); rectangle(0,40,639,450); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); setcolor(WHITE); outtextxy(275,10,"Pie Chart"); midx = getmaxx()/2;

midy = getmaxy()/2; setfillstyle(LINE_FILL,BLUE); pieslice(midx, midy, 0, 75, 100); outtextxy(midx+100, midy - 75, "20.83%"); setfillstyle(XHATCH_FILL,RED); pieslice(midx, midy, 75, 225, 100); outtextxy(midx-175, midy - 75, "41.67%"); setfillstyle(WIDE_DOT_FILL,GREEN); pieslice(midx, midy, 225, 360, 100); outtextxy(midx+75, midy + 75, "37.50%"); getch(); return 0; } Output of program:

4. C program to draw a 3d bar chart This c program draws a 3d bar chart. C code #include<graphics.h> #include<conio.h>

main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); setcolor(YELLOW); rectangle(0,30,639,450); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); setcolor(WHITE); outtextxy(275,0,"Bar Chart"); setlinestyle(SOLID_LINE,0,2); line(100,420,100,60); line(100,420,600,420); line(90,70,100,60); line(110,70,100,60); line(590,410,600,420); line(590,430,600,420); outtextxy(95,35,"Y"); outtextxy(610,405,"X"); outtextxy(85,415,"O"); setfillstyle(LINE_FILL,BLUE); bar(150,100,200,419); setfillstyle(XHATCH_FILL,RED); bar(225,150,275,419); setfillstyle(WIDE_DOT_FILL,GREEN); bar(300,200,350,419); setfillstyle(INTERLEAVE_FILL,MAGENTA); bar(375,125,425,419); setfillstyle(HATCH_FILL,BROWN); bar(450,175,500,419); getch(); return 0; }

Output of program:

5. C smiling face animation This animation using c draws a smiling face which appears at random position on screen. See output below the code, it will help you in understanding the code easily. C programming code #include<graphics.h> #include<conio.h> #include<stdlib.h> main() { int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75; void *p; initgraph(&gd,&gm,"C:\\TC\\BGI"); setcolor(YELLOW); circle(50,100,25); setfillstyle(SOLID_FILL,YELLOW); floodfill(50,100,YELLOW);

setcolor(BLACK); setfillstyle(SOLID_FILL,BLACK); fillellipse(44,85,2,6); fillellipse(56,85,2,6); ellipse(50,100,205,335,20,9); ellipse(50,100,205,335,20,10); ellipse(50,100,205,335,20,11); area = imagesize(left, top, left + 50, top + 50); p = malloc(area); setcolor(WHITE); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); outtextxy(155,451,"Smiling Face Animation"); setcolor(BLUE); rectangle(0,0,639,449); while(!kbhit()) { temp1 = 1 + random ( 588 ); temp2 = 1 + random ( 380 ); getimage(left, top, left + 50, top + 50, p); putimage(left, top, p, XOR_PUT); putimage(temp1 , temp2, p, XOR_PUT); delay(100); left = temp1; top = temp2; } getch(); closegraph(); return 0; }

Output of program:

6. C program to draw circles in circles This program draws circles in circles in two different colors. C programming code #include<graphics.h> #include<conio.h> #include<dos.h> main() { int gd = DETECT, gm, x, y, color, angle = 0; struct arccoordstype a, b; initgraph(&gd, &gm, "C:\\TC\\BGI"); delay(2000); while(angle<=360) { setcolor(BLACK); arc(getmaxx()/2,getmaxy()/2,angle,angle+2,100); setcolor(RED);

getarccoords(&a); circle(a.xstart,a.ystart,25); setcolor(BLACK); arc(getmaxx()/2,getmaxy()/2,angle,angle+2,150); getarccoords(&a); setcolor(GREEN); circle(a.xstart,a.ystart,25); angle = angle+5; delay(50); } getch(); closegraph(); return 0; } Output of program:

7. C program countdown This c graphics program performs countdown for 30 seconds. C program countdown code #include<graphics.h> #include<dos.h>

#include<conio.h> main() { int gd = DETECT, gm, i; char a[5]; initgraph( &gd, &gm, "C:\\TC\\BGI"); settextjustify( CENTER_TEXT, CENTER_TEXT ); settextstyle(DEFAULT_FONT,HORIZ_DIR,3); setcolor(RED); for(i = 30 ; i >=0 ; i--) { sprintf(a,"%d",i); outtextxy(getmaxx()/2, getmaxy()/2, a); delay(1000); if ( i == 0 ) break; cleardevice(); } getch(); closegraph(); return 0; }

8.C Program for Bresenham Circle Drawing algorithm # include<stdio.h> # include<conio.h> # include<graphics.h> # include<math.h> void main() { int gd=DETECT,gm; int r,x,y,p,xc=320,yc=240; initgraph(&gd,&gm,"C:\\TC\\BGI"); cleardevice();

printf("Enter the radius "); scanf("%d",&r);

x=0; y=r; putpixel(xc+x,yc-y,1); p=3-(2*r); for(x=0;x<=y;x++) { if (p<0) { y=y; p=(p+(4*x)+6); } else { y=y-1; p=p+((4*(x-y)+10)); } putpixel(xc+x,yc-y,1); putpixel(xc-x,yc-y,2); putpixel(xc+x,yc+y,3); putpixel(xc-x,yc+y,4); putpixel(xc+y,yc-x,5); putpixel(xc-y,yc-x,6); putpixel(xc+y,yc+x,7); putpixel(xc-y,yc+x,8); } getch(); closegraph(); }

9.C program to implement Bezier Curve Drawing Algorithm #include<stdio.h> #include<conio.h> #include<graphics.h> int x,y,z; void main() { float u; int gd,gm,ymax,i,n,c[4][3];

for(i=0;i<4;i++) { c[i][0]=0; c[i][1]=0; }

printf("\n\n Enter four points : \n\n"); for(i=0; i<4; i++) { printf("\t X%d Y%d : ",i,i); scanf("%d %d",&c[i][0],&c[i][1]); } c[4][0]=c[0][0]; c[4][1]=c[0][1]; detectgraph(&gd,&gm); initgraph(&gd,&gm,"e:\\tc\\bgi"); ymax = 480; setcolor(13); for(i=0;i<3;i++) { line(c[i][0],ymax-c[i][1],c[i+1][0],ymax-c[i+1][1]); } setcolor(3); n=3; for(i=0;i<=40;i++) { u=(float)i/40.0; bezier(u,n,c);

if(i==0) { moveto(x,ymax-y);} else { lineto(x,ymax-y); } getch(); } getch(); } bezier(u,n,p) float u;int n; int p[4][3]; { int j; float v,b; float blend(int,int,float); x=0;y=0;z=0; for(j=0;j<=n;j++) { b=blend(j,n,u); x=x+(p[j][0]*b); y=y+(p[j][1]*b); z=z+(p[j][2]*b); } } float blend(int j,int n,float u) { int k; float v,blend; v=C(n,j); for(k=0;k<j;k++) { v*=u; } for(k=1;k<=(n-j);k++) { v *= (1-u); } blend=v; return(blend); } C(int n,int j) { int k,a,c; a=1; for(k=j+1;k<=n;k++) { a*=k; } for(k=1;k<=(n-j);k++) { a=a/k; } c=a; return(c); }

C++ Language
1. C++ program to add two numbers #include<iostream.h> main() { int a, b, c; cout << "Enter two numbers to add\n"; cin >> a >> b; c = a + b; cout <<"Sum of entered numbers = " << c << endl; return 0; } If you are using gcc compiler then use the following source code: #include<iostream> using namespace std; main() { int a, b, c;

cout << "Enter two numbers to add\n"; cin >> a >> b; c = a + b; cout <<"Sum of entered numbers = " << c << endl; return 0; }

2. C++ program to add two arrays #include<iostream.h> main() { int first[20], second[20], c, n; cout << "Enter the number of elements in the array "; cin >> n; cout << "Enter elements of first array " << endl; for ( c = 0 ; c < n ; c++ ) cin >> first[c]; cout << "Enter elements of second array " << endl; for ( c = 0 ; c < n ; c++ ) cin >> second[c]; cout << "Sum of elements of two arrays " << endl; for ( c = 0 ; c < n ; c++ ) cout << first[c] + second[c] << endl; return 0; }

3. C++ program to add two complex numbers #include<iostream.h> class complex { public : int real, img;

}; main() { complex a, b, c; cout << "Enter a and b where a + ib is the first complex number."; cout << "\na = "; cin >> a.real; cout << "b = "; cin >> a.img; cout << "Enter c and d where c + id is the second complex number."; cout << "\nc = "; cin >> b.real; cout << "d = "; cin >> b.img; c.real = a.real + b.real; c.img = a.img + b.img; if ( c.img >= 0 ) cout << "Sum of two complex numbers = " << c.real << " + " << c.img << "i"; else cout << "Sum of two complex numbers = " << c.real << " " << c.img << "i"; return 0; }

4. C++ program to generate fibonacci series #include<iostream.h> main() { int n, c, first = 0, second = 1, next; cout << "Enter the number of terms of fibonacci series you want "; cin >> n; cout << "First " << n << " terms of fibonacci series are :- " << endl; for ( c = 0 ; c < n ; c++ ) { if ( c <= 1 ) next = c; else { next = first + second;

first = second; second = next; } cout << next << endl; } return 0; } 5. C++ program to generate prime numbers #include<iostream.h> #include<math.h> main() { int n, status = 1, num = 3, count, c; cout << "Enter the number of prime numbers you want "; cin >> n; if ( n >= 1 ) { cout << "First " << n <<" prime numbers are :-" << endl; cout << 2 << endl; } for ( count = 2 ; count <=n ; ) { for ( c = 2 ; c <= sqrt(num) ; c++ ) { if ( num%c == 0 ) { status = 0; break; } } if ( status != 0 ) { cout << num << endl; count++; } status = 1; num++; } return 0; }

6. C++ program to generate random numbers #include<iostream.h> #include<stdlib.h> main() { int n, max, num, c; cout << "Enter the number of random numbers you want "; cin >> n; cout << "Enter the maximum value of random number "; cin >> max; cout << "random numbers from 0 to " << max << " are :-" << endl; for ( c = 1 ; c <= n ; c++ ) { num = random(max); cout << num << endl; } return 0; }

7. C++ program to add two matrices #include<iostream.h> main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; cout << "Enter the number of rows and columns of matrix "; cin >> m >> n; cout << "Enter the elements of first matrix\n"; for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) cin >> first[c][d]; cout << "Enter the elements of second matrix\n"; for ( c = 0 ; c < m ;c++ ) for ( d = 0 ; d < n ; d++ ) cin >> second[c][d]; for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ )

sum[c][d] = first[c][d] + second[c][d]; cout << "Sum of entered matrices:-\n"; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) cout << sum[c][d] << "\t"; cout << endl; } return 0; }

8. C++ program to make a pie chart #include<iostream.h> #include<stdio.h> #include<conio.h> #include<math.h> #include<graphics.h> #include<dos.h> #define round(a)(int(a+0.5)) void main() { double total=0.0,a=0.0; double x2,y2; int i,n; int gd=DETECT,gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); cout<<"PIE CHART"<<endl; cout<<"Enter the no. of regions"<<endl;

cin>>n; double values[10]; double per[10]; double angle[10]={0,0,0,0,0,0,0,0,0,0}; double b[10]; cout<<"Enter the values of the regions"<<endl; circle(300,300,100); line(300,300,400,300); for(i=0;i<n;i++) { cin>>values[i]; total=total+values[i]; } for(i=0;i<n;i++) { per[i]=((values[i]/total)*100); a=((per[i]/100)*360); if(i==0) b[i]=a; else b[i]=b[i-1]+a; angle[i]=(3.14*b[i])/180; x2=(300+100*cos(angle[i])); y2=(300-100*sin(angle[i])); line(300,300,round(x2),round(y2));

setfillstyle(1,i+1); if(x2>300&&y2< 300) floodfill(x2+2,y2+2,15); else floodfill(x2-2,y2-2,15); } getch(); closegraph(); }

9. C++ graphics program to display a Calender.It also gives an introduction to mouse programming in graphics. Save the file with a '.cpp' extension and compile it. #include<iostream.h> #include<conio.h> #include<graphics.h> #include<stdlib.h> #include<dos.h> #include<string.h> union REGS i,o; initmouse(); showmouse(); hidemouse(); void restrictmouse(int x1,int y1,int x2,int y2); void getmousestatus( int *button,int *x,int *y); void findday(); void menu();

void cal(); void main() { clrscr(); int gd=EGA,gm=EGAHI; initgraph(&gd,&gm,"c:\\tc\\bgi "); menu(); getch(); closegraph(); } void findday() { int k=1,m=11,mon,D,C,f,i,y,total=0,t,I,d,x1=115,y1=160,q,r,v; static int s=0; char st2[3],st3[9],st4[5]; int days[]={31,28,31,30,31,30,31,31,30,31,30,31}; char *month[]={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY" ,"AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMEBER"}; restorecrtmode(); cout<<"Enter year : "; cin>>y; cout<<"Enter month : "; cin>>mon; if(mon>12) {

cout<<" Invalid entry !....."; delay(1000); setgraphmode(getgraphmode()); menu(); } y-=1; C=y/100; D=y%100; f=(k+((13*m-1)/5)+D+(D/4)+(C/4)-(2*C)); i=f%7; if(i< 0) i+=7; y++; if(y%4==0) days[1]=29; for(t=0;t<mon-1;t++) { total+=days[t]; } I=total%7; d=I+i; if(d>=7) d=d%7; setgraphmode(getgraphmode()); cal();

v=mon-1; strcpy(st3,month[v]); itoa(y,st4,10); settextstyle(2,0,8); outtextxy(100,90,st3); outtextxy(250,90,st4); q=days[mon-1]; settextstyle(1,0,2); setcolor(15); for(r=1;r<=d;r++) { x1+=62; s++; } for(r=1;r<=q;r++) { itoa(r,st2,10); if(s>=6) { outtextxy(x1,y1,st2); y1+=30; x1=112; s=0; continue; }

outtextxy(x1,y1,st2); x1+=60; s++; } s=0; getch(); menu(); } void menu() { cleardevice(); int b,xx,yy; initmouse(); restrictmouse(0,0,getmaxx(),getmaxy()); setbkcolor(0); settextstyle(10,0,2); outtextxy(100,70,"***********MENU***********"); outtextxy(100,150,"=> MONTH'S CALENDAR"); outtextxy(100,200,"=> EXIT"); settextstyle(8,0,1); outtextxy(350,300,"Made By: ANGAD"); showmouse(); while(!kbhit()) { getmousestatus(&b,&xx,&yy);

if(xx>=100&&yy>=150&&xx<=500&&yy<=200) { getmousestatus(&b,&xx,&yy); if(b&1==1) { hidemouse(); cleardevice(); findday(); } } if(xx>=100&&yy>=200&&xx<=300&&yy<=260) { getmousestatus(&b,&xx,&yy); if(b&1==1) { hidemouse(); cleardevice(); setbkcolor(0); setcolor(15); settextstyle(10,0,5); outtextxy(100,200,"EXITING"); int o=0; for(int n=0;n< 10;n++) { outtextxy(380+o,200,".");

o+=20; delay(200); } exit(0); } } } } void cal() { cleardevice(); int l=100,t=125,r=155,b=185,g,x=110,y=127; char *day[]={"SUN","MON","TUE","WED","THU","FRI","SAT"}; char st1[4]; setbkcolor(0); settextstyle(10,0,7); setcolor(15); outtextxy(100,-40,"C"); settextstyle(10,0,6); outtextxy(160,-20,"ALENDAR"); setfillstyle(1,BLUE); bar(85,115,530,345); setfillstyle(1,0); bar3d(l,t,r,b,0,0); bar3d(l,t+30,r,b+30,0,0);

bar3d(l,t+60,r,b+60,0,0); bar3d(l,t+90,r,b+90,0,0); bar3d(l,t+120,r,b+120,0,0); bar3d(l,t+150,r,b+150,0,0); bar3d(l,t+180,r,b+150,0,0); bar3d(l+60,t,r+60,b,0,0); bar3d(l+60,t+30,r+60,b+30,0,0); bar3d(l+60,t+60,r+60,b+60,0,0); bar3d(l+60,t+90,r+60,b+90,0,0); bar3d(l+60,t+120,r+60,b+120,0,0); bar3d(l+60,t+150,r+60,b+150,0,0); bar3d(l+60,t+180,r+60,b+150,0,0); bar3d(l+120,t,r+120,b,0,0); bar3d(l+120,t+30,r+120,b+30,0,0); bar3d(l+120,t+60,r+120,b+60,0,0); bar3d(l+120,t+90,r+120,b+90,0,0); bar3d(l+120,t+120,r+120,b+120,0,0); bar3d(l+120,t+150,r+120,b+150,0,0); bar3d(l+120,t+180,r+120,b+150,0,0); bar3d(l+180,t,r+180,b,0,0); bar3d(l+180,t+30,r+180,b+30,0,0); bar3d(l+180,t+60,r+180,b+60,0,0); bar3d(l+180,t+90,r+180,b+90,0,0); bar3d(l+180,t+120,r+180,b+120,0,0); bar3d(l+180,t+150,r+180,b+150,0,0);

bar3d(l+180,t+180,r+180,b+150,0,0); bar3d(l+240,t,r+240,b,0,0); bar3d(l+240,t+30,r+240,b+30,0,0); bar3d(l+240,t+60,r+240,b+60,0,0); bar3d(l+240,t+90,r+240,b+90,0,0); bar3d(l+240,t+120,r+240,b+120,0,0); bar3d(l+240,t+150,r+240,b+150,0,0); bar3d(l+240,t+180,r+240,b+150,0,0); bar3d(l+300,t,r+300,b,0,0); bar3d(l+300,t+30,r+300,b+30,0,0); bar3d(l+300,t+60,r+300,b+60,0,0); bar3d(l+300,t+90,r+300,b+90,0,0); bar3d(l+300,t+120,r+300,b+120,0,0); bar3d(l+300,t+150,r+300,b+150,0,0); bar3d(l+300,t+180,r+300,b+150,0,0); bar3d(l+360,t,r+360,b,0,0); bar3d(l+360,t+30,r+360,b+30,0,0); bar3d(l+360,t+60,r+360,b+60,0,0); bar3d(l+360,t+90,r+360,b+90,0,0); bar3d(l+360,t+120,r+360,b+120,0,0); bar3d(l+360,t+150,r+360,b+150,0,0); bar3d(l+360,t+180,r+360,b+150,0,0); settextstyle(1,0,2); setcolor(15); for(g=0;g< 7;g++)

{ strcpy(st1,day[g]); outtextxy(x,y,st1); x+=60; } } initmouse() { i.x.ax=0; int86(0x33,&i,&o); return(o.x.ax); } showmouse() { i.x.ax=1; int86(0x33,&i,&o); return(o.x.ax); } hidemouse() { i.x.ax=2; int86(0x33,&i,&o); return(o.x.ax); } void restrictmouse(int x1,int y1,int x2,int y2)

{ i.x.ax=7; i.x.cx=x1; i.x.dx=x2; int86(0x33,&i,&o); i.x.ax=8; i.x.cx=y1; i.x.dx=y2; int86(0x33,&i,&o); } void getmousestatus(int *button,int *x,int *y) { i.x.ax=3; int86(0x33,&i,&o); *button=o.x.bx; *x=o.x.cx; *y=o.x.dx; }

11. C++ code to print pattern 1 1 12 21 12321 C++ code to print pattern #include<iostream> using namespace std;

main() { int n, k, c, space, x, num = 1; cin >> n; x = n; for ( k = 1 ; k <= n ; k++ ) { for ( c = 1 ; c <= k ; c++ ) { cout << num; num++; } num--; for ( c = 1 ; c <= 2*x - 3 ; c++ ) cout << " "; x--; if ( k != n ) { for ( c = 1 ; c <= k ; c++ ) { cout << num; num--; } } else { num--; for ( c = 1 ; c <= k - 1 ; c++ ) { cout << num; num--; } } printf("\n"); num = 1; } return 0; }

C Game Programming Tutorial


C Game Programming tutorial is for all those who wish to make their own games or are curious to know about what works behind when we play games. First of all we must know what qualities a game should have, your game should work fast and responds to user input very quickly and it's look should be very good. As far as speed is concerned we know that C is very fast so you need not worry about speed you just have to ensure that you have applied the best method to solve a particular problem and look of the game is entirely in your hand. Now a question that may come in your mind is that what i need to know to make my first own game. To make a game in C you need to know the following things:1) C Graphics programming 2) Mouse Programming ( How to handle mouse events ) 3) Keyboard Graphics programming is needed to build key game elements. For example if in your game you want a car then you can use rectangle and circle to draw it. If you don't know c graphics programming then visit c graphics programming tutorial. If your game is such that it takes user input through a mouse then you should know how to handle mouse events. Some of the things which we frequently need to know in our games are what is the mouse current position, which mouse button is clicked etc. here you will find sample source code and programs, you can also download executable files so you can understand a program better. Similarly if your game gets input from keyboard you need to know which key is pressed and then you can take appropriate action according to the key pressed. Sample source codes and executable files are also available. Know you know how to make a game. So what are you waiting for just implement your idea into a program. Help us improve this article by providing your feedback and suggestions, email us at contact[at]programmingsimplified DOT com.

Project Development Tutorial


C Project Development tutorial :-This tutorial is for all those who wish to make their own project using c programming. First of all let me tell you need not be an expert in programming to make your own project, if you are a beginner/student then you can make one of your own. Fundamental concepts of c will be required to make a project , also don't worry if you don't know pointers if you know then it's good, pointers are used rarely as it depends only on you whether you want to use them or not. But you should know how to make your own functions and use them. To make a project you may have to use graphics in your program, so if you want to learn c graphics programming then visit c graphics programming tutorial. Following points will be useful to manage your project 1) Be very clear about the idea of your project, modifying your project at a later time can be a trouble for you. 2) Always create a back up of your source code, you start your project by writing some portion and it works fine but at a later point of time you need to modify it so you

modified the original one and you find it's not working and now you want your original one back but it is not possible if you have saved your file or you can undo if it works. So you should keep a backup of every source file. 3) To easily manage your project keep your source code in different files . 4) Do not use too many global variables as global variables are shared by many functions so they get modified causing a lot of trouble when your not getting the result what you desire although your logic is correct. 5) Use const keyword as much as you can, it will help you to protect your variables from being modified when undesired. 6) Make sure that every function is performing the task for what it is made you can test your function separately by using it in a program which is not a part of your project. 7) Every function should have a description about what is to be done by a function and description of arguments being passed to it. You can use comments for this purpose. 8) Write detailed comments in your source code where possible particularly when you have use a trick etc. It will help quickly understand your source code at a later time. 9) Initialize every variable at declaration time. 10) Use tab and blank spaces to make your code easily readable which will help in easy understanding of code. For example consider the following sample program
#include<stdio.h> int main() { int b = 1, c = 1; for( b = 1 ; b <= 10 ; b++ ) { for( c = 1 ; c <= 10 ; c++ ) { printf("%d\n", b*c); } } return 0; }

the above program is easily readable then shown below :#include<stdio.h> int main() { int b=1,c=1; for(b=1;b<=10;b++) { for(c=1;c<=10;c++) { printf("%d\n",b*c); }

} return 0; }

I hope the above tips will help you to easy manage your project, but if you are using c/c++ to make your project then what is written below is also worth reading. If you want to make your own game as a project then visit c game programming tutorial.

Java Language
1. Hello world program hello world java program :- Java code to print hello world. Java source code

class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); }


}

Output:

2. Java program to print alphabets This program print alphabets on screen i.e a, b, c, ..., z. Java source code class Alphabets { public static void main(String args[]) { char ch; for( ch = 'a' ; ch <= 'z' ; ch++ ) System.out.println(ch); } }

Output:

3. Java program to print multiplication table This java program prints multiplication table of a number entered by the user using a for loop. Java source code import java.util.Scanner; class MultiplicationTable { public static void main(String args[]) { int n, c; System.out.println("Enter an integer to print it's multiplication table"); Scanner in = new Scanner(System.in); n = in.nextInt(); System.out.println("Multiplication table of "+n+" is :-"); for ( c = 1 ; c <= 10 ; c++ ) System.out.println(n+"*"+c+" = "+(n*c)); }

Output:

Its Good But Actual format is


class Multiplication{ public static void main(String a[]){ int n=6; int i; for(i=1;i<=20;i++) { System.out.println(i+"*"+n+"="+(i*n)); } } }

4. How to get input from user in java This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the user to enter a string and then the string is printed, then an integer and entered integer is also printed and finally a float and it is also printed ion the screen. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement Scanner a = new Scanner(System.in); here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below :-

1) nextInt to input an integer 2) nextFloat to input a float 3) nextLine to input a string Java source code import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { int a; float b; String s; Scanner in = new Scanner(System.in); System.out.println("Enter a string"); s = in.nextLine(); System.out.println("You entered string "+s); System.out.println("Enter an integer"); a = in.nextInt(); System.out.println("You entered integer "+a); System.out.println("Enter a float"); b = in.nextFloat(); System.out.println("You entered float "+b); } } Output:

5. Java program to add two numbers

Java program to add two numbers :- Given below is the code of java program that adds two numbers which are entered by the user. Java source code import java.util.Scanner; class AddNumbers { public static void main(String args[]) { int x, y, z; System.out.println("Enter two integers to calculate their sum "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); z = x + y; System.out.println("Sum of entered integers = "+z); }
}

Output:

6. Java program to find odd or even

This java program finds if a number is odd or even. If the number is divisible by 2 then it will be even, otherwise it is odd. We use modulus operator to find remainder in our program. Java source code import java.util.Scanner; class OddOrEven { public static void main(String args[]) { int x; System.out.println("Enter an integer to check if it is odd or even "); Scanner in = new Scanner(System.in); x = in.nextInt(); if ( x % 2 == 0 ) System.out.println("You entered an even number."); else System.out.println("You entered an odd number."); } } Output:

7. Java program swap two numbers

This java program swaps two numbers using a temp variable. Swapping using temp or third variable import java.util.Scanner; class SwapNumbers { public static void main(String args[]) { int x, y, temp; System.out.println("Enter x and y "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); System.out.println("Before Swapping\nx = "+x+"\ny = "+y); temp = x; x = y; y = temp; System.out.println("After Swapping\nx = "+x+"\ny = "+y); } } Swapping without temp variable import java.util.Scanner; class SwapNumbers { public static void main(String args[]) { int x, y; System.out.println("Enter x and y "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); System.out.println("Before Swapping\nx = "+x+"\ny = "+y); x = x + y; y = x - y; x = x - y; System.out.println("After Swapping\nx = "+x+"\ny = "+y); } }

Output:

8. Java program to find largest of three numbers This java program finds largest of three numbers and then prints it. If the entered numbers are unequal then "numbers are not distinct" is printed. import java.util.Scanner; class LargestOfThreeNumbers { public static void main(String args[]) { int x, y, z; System.out.println("Enter three integers "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); z = in.nextInt(); if ( x > y && x > z ) System.out.println("First number is largest."); else if ( y > x && y > z ) System.out.println("Second number is largest."); else if ( z > x && z > y ) System.out.println("Third number is largest."); else System.out.println("Entered numbers are not distinct.");

} } Output:

9. Java program to find factorial This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed. Java programming code import java.util.Scanner; class Factorial { public static void main(String args[]) { int n, c, fact = 1; System.out.println("Enter an integer to calculate it's factorial"); Scanner in = new Scanner(System.in); n = in.nextInt(); if ( n < 0 ) System.out.println("Number should be non-negative."); else { for ( c = 1 ; c <= n ; c++ )

fact = fact*c; System.out.println("Factorial of "+n+" is = "+fact); } } } Output of program:

10. Java program print prime numbers This java program prints prime numbers, number of prime numbers required is asked from the user. Remember that smallest prime number is 2. Java programming code import java.util.*; class PrimeNumbers { public static void main(String args[]) { int n, status = 1, num = 3; Scanner in = new Scanner(System.in); System.out.println("Enter the number of prime numbers you want "); n = in.nextInt(); if ( n >= 1 ) { System.out.println("First "+n+" prime numbers are :-"); System.out.println(2); } for ( int count = 2 ; count <=n ; ) { for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break;

} } if ( status != 0 ) { System.out.println(num); count++; } status = 1; num++; } }


}

Output:

11. Java program to check armstrong number This java program checks if a number is armstrong or not. Java programming code import java.util.*; class ArmstrongNumber { public static void main(String args[]) { int n, sum = 0, temp, r; Scanner in = new Scanner(System.in);

System.out.println("Enter a number to check if it is an armstrong number"); n = in.nextInt(); temp = n; while( temp != 0 ) { r = temp%10; sum = sum + r*r*r; temp = temp/10; } if ( n == sum ) System.out.println("Entered number is an armstrong number."); else System.out.println("Entered number is not an armstrong number."); } } Output:

12. Java program to print Floyd's triangle This java program prints Floyd's triangle. Java source code

import java.util.Scanner; class FloydTriangle { public static void main(String args[]) { int n, num = 1, c, d; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows of floyd's triangle you want"); n = in.nextInt(); System.out.println("Floyd's triangle :-"); for ( c = 1 ; c <= n ; c++ ) { for ( d = 1 ; d <= c ; d++ ) { System.out.print(num+" "); num++; } System.out.println(); } } }

13. Consider this pattern A AB ABC ABCD Character pattern source code import java.util.Scanner; class Character_Pattern { public static void main(String args[]) { int n, number = 0, c, d; char ch = 'A'; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows"); n = in.nextInt();

for ( c = 1 ; c <= n ; c++ ) { for ( d = 1 ; d <= c ; d++ ) { System.out.print(ch); ch++; } ch = 'A'; System.out.println(); } } } 14. Consider this pattern 0 10 101 0101 01010 Number pattern java source code import java.util.Scanner; class Number_Pattern { public static void main(String args[]) { int n, number = 0, c, d; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows"); n = in.nextInt(); for ( c = 1 ; c <= n ; c++ ) { for ( d = 1 ; d <= c ; d++ ) { System.out.print(number); if ( number == 0 ) number = 1; else number = 0; } System.out.println(); } } }

15. Java program to reverse a string This java program reverses a string entered by the user. We use charAt method to extract characters from the string and append them in reverse order to reverse the entered string. Java programming code import java.util.*; class ReverseString { public static void main(String args[]) { String original, reverse =""; Scanner in = new Scanner(System.in); System.out.println("Enter a string to reverse"); original = in.nextLine(); int length = original.length(); for ( int i = length - 1 ; i >= 0 ; i-- ) reverse = reverse + original.charAt(i); System.out.println("Reverse of entered string is "+reverse); } } Output:

16. Java program to check palindrome Java palindrome program :- Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome. import java.util.*; class Palindrome { public static void main(String args[]) { String original, reverse=""; Scanner in = new Scanner(System.in); System.out.println("Enter a string to check if it is a palindrome"); original = in.nextLine(); int length = original.length(); for ( int i = length - 1 ; i >= 0 ; i-- ) reverse = reverse + original.charAt(i); if (original.equals(reverse)) System.out.println("Entered string is a palindrome."); else System.out.println("Entered string is not a palindrome."); }
}

Output:

17. Java program to compare two strings This program compare strings i.e test whether two strings are equal or not, compareTo method of String class is used to test equality of two String class objects. compareTo method is case sensitive i.e "java" and "Java" are two different strings if you use compareTo method. If you wish to compare strings bu ignoring the case then use compareToIgnoreCase method. Java programming code import java.util.Scanner; class Compare_Strings { public static void main(String args[]) { String s1, s2; Scanner in = new Scanner(System.in); System.out.println("Enter the first string"); s1 = in.nextLine(); System.out.println("Enter the second string"); s2 = in.nextLine(); if ( s1.compareTo(s2) > 0 ) System.out.println("First string is greater than second."); else if ( s1.compareTo(s2) < 0 )

System.out.println("First string is smaller than second."); else System.out.println("Both strings are equal."); } } Output of program:

18. Java program to find all substrings of a string Java program to find substrings of a string :- This program find all substrings of a string and the prints them. For example substrings of "fun" are :- "f", "fu", "fun", "u", "un" and "n". substring method of string class is used to find substring. Java code to print substrings of a string is given below :import java.util.Scanner; class SubstringsOfAString { public static void main(String args[]) { String string, sub; int i, c, length; Scanner in = new Scanner(System.in); System.out.println("Enter a string to print it's all substrings"); string = in.nextLine(); length = string.length(); System.out.println("Substrings of \""+string+"\" are :-"); for( c = 0 ; c < length ; c++ ) { for( i = 1 ; i <= length - c ; i++ ) { sub = string.substring(c, c+i); System.out.println(sub); } }

} } Output:

19. Java program to display date and time, print date and time using java program Java date and time program :- Java code to print or display current system date and time. This program prints current date and time. We are using GregorianCalendar class in our program. Java code to print date and time is given below :import java.util.*; class GetCurrentDateAndTime { public static void main(String args[]) { int day, month, year; int second, minute, hour; GregorianCalendar date = new GregorianCalendar(); day = date.get(Calendar.DAY_OF_MONTH); month = date.get(Calendar.MONTH); year = date.get(Calendar.YEAR); second = date.get(Calendar.SECOND); minute = date.get(Calendar.MINUTE); hour = date.get(Calendar.HOUR); System.out.println("Current date is "+day+"/"+(month+1)+"/"+year);

System.out.println("Current time is "+hour+" : "+minute+" : "+second); } } Output:

20. Java program to perform garbage collection This program performs garbage collection. Free meory in java virtual machine is printed and then garbage collection is done using gc method of RunTime class, freeMemory method returns amount of free memory in jvm, getRunTime method is used to get reference of current RunTime object. Java source code import java.util.*; class GarbageCollection { public static void main(String s[]) throws Exception { Runtime rs = Runtime.getRuntime(); System.out.println("Free memory in jvm (Java Virtual Machine) before Garbage Collection = "+rs.freeMemory()); rs.gc(); System.out.println("Free memory in jvm (Java Virtual Machine) after Garbage Collection = "+rs.freeMemory()); } }

Output:

21. Java program to get ip address This program prints ip address of your computer system. InetAddress class of java.net package is used, getLocalHost method returns InetAddress object which represents local host. Java source code import java.net.InetAddress; class IPAddress { public static void main(String args[]) throws Exception { System.out.println(InetAddress.getLocalHost()); } } Output:

22. Java program to reverse number

This program prints reverse of a number i.e. if the input is 951 then output will be 159. Java source code import java.util.Scanner; class ReverseNumber { public static void main(String args[]) { int n, reverse = 0; System.out.println("Enter the number to reverse"); Scanner in = new Scanner(System.in); n = in.nextInt(); while( n != 0 ) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; } System.out.println("Reverse of entered number is "+reverse); } } Output:

23. Java program to add two matrices This java program add two matrices. You can add matrices of any order. Java source code import java.util.Scanner; class AddTwoMatrix { public static void main(String args[])

{ int m, n, c, d; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of matrix"); m = in.nextInt(); n = in.nextInt(); int first[][] = new int[m][n]; int second[][] = new int[m][n]; int sum[][] = new int[m][n]; System.out.println("Enter the elements of first matrix"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) first[c][d] = in.nextInt(); System.out.println("Enter the elements of second matrix"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) second[c][d] = in.nextInt(); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) sum[c][d] = first[c][d]+ second[c][d]; System.out.println("Sum of entered matrices:-"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) System.out.print(sum[c][d]+"\t"); System.out.println(); } } }

Output:

24. Java program to transpose matrix This java program find transpose of a matrix of any order. Java source code import java.util.Scanner; class TransposeAMatrix { public static void main(String args[]) { int m, n, c, d; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of matrix"); m = in.nextInt(); n = in.nextInt(); int matrix[][] = new int[m][n]; System.out.println("Enter the elements of matrix"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) matrix[c][d] = in.nextInt();

int transpose[][] = new int[n][m]; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) transpose[d][c] = matrix[c][d]; } System.out.println("Transpose of entered matrix:-"); for ( c = 0 ; c < n ; c++ ) { for ( d = 0 ; d < m ; d++ ) System.out.print(transpose[c][d]+"\t"); System.out.print("\n"); } }
}

Output:

25. Java program to multiply two matrices This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not. Java programming code import java.util.Scanner;

class MatrixMultiplication { public static void main(String args[]) { int m, n, p, q, sum = 0, c, d, k; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of first matrix"); m = in.nextInt(); n = in.nextInt(); int first[][] = new int[m][n]; System.out.println("Enter the elements of first matrix"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) first[c][d] = in.nextInt(); System.out.println("Enter the number of rows and columns of second matrix"); p = in.nextInt(); q = in.nextInt(); if ( n != p ) System.out.println("Matrices with entered orders can't be multiplied with each other."); else { int second[][] = new int[p][q]; int multiply[][] = new int[m][q]; System.out.println("Enter the elements of second matrix"); for ( c = 0 ; c < p ; c++ ) for ( d = 0 ; d < q ; d++ ) second[c][d] = in.nextInt(); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { for ( k = 0 ; k < p ; k++ ) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } }

System.out.println("Product of entered matrices:-"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < q ; d++ ) System.out.print(multiply[c][d]+"\t"); System.out.print("\n"); } } }
}

Output:

You might also like