You are on page 1of 111

Introduction to

C Programming

C CONCEPTS 1.1 Introduction C is a remarkable language. Designed originally by Dennis Ritchie, working at AT&T Bell Laboratories in New Jersey, it has increased in use until now it may well be one of the most widely-written computer languages in the world. C is a structured language. It allows variety of programs in small modules. It is easy for debugging, testing, and maintenance if a language is a structured one. 1.2 Structure of a C program:

Include header file section Global declaration section Main() { Declaration part Executable part } User-defined functions { Statements } Include header file section: C program depends upon some header files for function definition that are used in program. Each header file by default is extended with .h. The header file should be included using # include directive as given here. Global declaration: This section declares some variables that are used in more than one function. These variables are known as global variables. This section must be declared outside of all the functions. Function main: Every program written in C language must contain main () function. The function main() is a starting point of every C program. The execution of the program always begins with the function main ().

Declaration part: The declaration part declares the entire variables that are used in executable part. The initializations of variables are also done in this section. Initialization means providing initial value to the variables Executable part: This part contains the statements following the declaration of the variables. This part contains a set of statements or a single statement. These statements are enclosed between the braces. User defined function: The functions defined by the user are called user-defined functions. These functions are generally defined after the main () function. 1.3 Steps for executing the program

1. Creation of program: Programs should be written in C editor. The file name does not necessarily include extension C. The default extension is C. 2. Compilation of a program: The source program statements should be translated into object programs which is suitable for execution by the computer. The translation is done after correcting each statement. If there is no error, compilation proceeds and translated program are stored in another file with the same file name with extension .obj. 3. Execution of the program: After the compilation the executable object code will be loaded in the computers main memory and the program is executed. 1.4 C Character set: Digits White Spaces All decimal digits 0 to Blank space 9 Horizontal tab Vertical tab New line Form feed

Letters Capital A to Z Small a to z

Special Characters: , . ; : ! | / \ ~ _ $ ? Comma Dot Semicolon Colon Apostrophe Quotation mark Exclamation mark Vertical bar Slash Back slash Tilde Underscore Dollar Question mark & ^ * + < > () [] {} % # = @ Ampersand Caret Asterisk Minus Plus Less than Greater than Parenthesis left/right Bracket left/right Braces left/right Percent Number sign or Hash Equal to At the rate

1.5

Delimiters: Use Useful for label Terminates the statement Used in expression and function Used for array declaration Scope of the statement Preprocessor directive Variable separator

Delimiters : Colon ; Semicolon ( ) Parenthesis [ ] Square Bracket { } Curly Brace # hash , Comma 1.6 C Keywords:

Auto Break Case Char Const Continue Default

Double Else Enum Extern Float For Goto

Int Long Register Return Short Signed Sizeof

Struct Switch Typedef Union Unsigned Void Volatile

Do 1.7 Identifiers:

If

Static

while

Identifiers are names of variables, functions, and arrays. They are user-defined names, consisting sequence of letters and digits, with the letter as the first character, 1.8 Constants:

Values do not change during the execution of the program Types: 1. Numerical constants: - Integer constants These are the sequence of numbers from 0 to 9 without decimal points or fractional part or any other symbols. It requires minimum two bytes and maximum four bytes. Eg: 10,20, +30, -14 - Real constants It is also known as floating point constants. Eg: 2.5, 5.342 2. Character constants: - Single charcter constants A charcter constant is a single character. Charcters are also represented with a single digit or a single special symbol or white space enclosed within a pair of single quote marks Eg: a,8, - String constants String constants are sequence of charcters enclosed within double quote marks.

Eg: Hello, india,444 1.9 Variables: It is a data name used for storing a data value. Its value may be changed during the program execution. The value of variables keeps on changing during the execution of a program. 1.10 Data types: Data type Char Unsigned char Short or int Unsigned int Float Long Unsigned long Double Long double Size (Bytes) 1 1 2 2 4 4 4 8 10 Range -128 to 127 0 to 255 -32,768 to 32, 767 0 to 655355 3.4e-38 to +3.4e +38 -2147483648 to 2147483647 0 to 4294967295 Format Specifiers %c %c %i or %d %u %f or %g %ld %lu

1.7e-308 to 1.7e+308 %lf 3.4e-4932 to 1.1e+4932 %lf

1.11 Operators: It indicates an operation to be performed on data that yields value. Types: Type of Operator Arithmetic operators Relational operators Logical operators Increment and decrement operator Assignment operator Bitwise operator Comma operator Conditional operator 1.12 Input and Output: Symbolic representation +,-,*,/,% >,<,==,>=,<=,!= &&, ||, != ++ and -= &,|,^,>>,<<, ~ , ?:

Reading data from input devices and displaying the results on the screen are the two main tasks of any program. Formatted functions: - The formatted input/output functions read and write all types of values Input Scanf() Unformatted functions: - The unformatted input/output functions only work with the charcter data type Input getch() getche() getchar() gets() 1.13 Decision statements: It checks the given condition and then executes its sub-block. The decision statement decides the statement to be executed after the success or failure of a given condition. Types: 1. 2. 3. 4. 5. 6. 7. 8. 9. If statement If-else statement Nested if-else statement Break statement Continue statement goto statement switch() statement nested switch ()case switch() case and nested if Syntax if(condition) Output putch() putchar() put() Output printf()

Statement If statement

If-else statement

Statement; If (condition) { Statement 1; Statement 2; } else { Statement 3; Statement 4; } If (condition) { Statement 1; Statement 2; } else if (condition) { Statement 3; Statement 4; } else { Statement 5; Statement 6; } Break; Continue; goto label; Switch (variable or expression) { Case constant A: Statement; break; Case constant B: Statement; break; default:

Nested if-else statement

Break statement Continue statement Goto statement Switch() statement

Statement; } 1.14 Loop Control statements: Loop is a block of statements which are repeatedly executed for certain number of times. Types: 1. 2. 3. 4. 5. for loop nested for loops while loop do while loop do-while statement with while loop Syntax for(initialize counter; test condition; reevaluation parameter { Statement; Statement; } for(initialize counter; test condition; reevaluation parameter) { Statement; Statement; for(initialize counter; test condition; reevaluation parameter) Statement; Statement; } } While (test condition) { Body of the loop }

Statement For loop

Nested for loop

While loop

Do while loop do { Statement; } While(condition); Do-while with while do while(condition) loop { Statement; } While (condition); 1.15 Arrays: It is a collection of similar data types in which each element is located in separate memory locations. Types: 1. One dimensional array 2. Two dimensional arrays 3. Three or multi dimensional arrays Operations: 1. 2. 3. 4. 5. Insertion Deletion Searching Sorting Merging

sscanf(): This function allows reading characters from a character array and writes them to another array. This function is similar to scanf(), but instead of reading from standard input it reads data from an array. sprintf():

This function is similar to the printf() function except for a small difference between them. The printf() function sends the output to the screen whereas the sprint() function writes the values of any data type to an array of characters. 1.16 Strings: Character arrays are called strings. Group of characters, digits, symbols enclosed within quotation marks are called as strings. String standard functions: Functions Description Strlen() Determines the length of a string Strcpy() Copies a string from source to destination Strncpy() Copies characters of a string to another string up to the specified length Stricmp() Compares characters of two strings Strcmp() Compares characters of two strings up to the specified length Strncmp() Compares characters of two strings up to the specified length Strnicmp() Compares characters of two strings up to the specified length Strlwr() Converts uppercase characters of a string to lower case Strupr() Converts lowercase characters of a string to upper case Strdup() Duplicates a string Strchr() Determines the first occurrence of a given character in a string Strrchr() Determines the last occurrence of a given character in a string Strstr() Determines the first occurrence of a given string in another string Strcat() Appends source string to destination string Strrev() Reverses all characters of a string Strset() Sets all characters of a string with a given argument or symbol Strspn() Finds up to what length two strings are identical Strpbrk() Searches the first occurrence of the character in a given string and then displays the string starting from that character

1.17 Functions: It is a self-contained block or a sub program of one or more statements that performs a special task Declaration of functions: Function_name (argument/parameter) Argument declaration; { Local variable declaration; Statement1; Statement 2; Return (value); } Call by value: In this type, value of actual arguments is passed to the formal arguments and the operation is done on the formal arguments. Any change made in the formal argument does not affect the actual arguments because formal arguments are photo copies of actual arguments. Call by reference: In this type, instead of passing values, addresses are passed. Function operates on address rather than values. Here the formal arguments are pointers to the actual argument. 1.18 Recursion: A function is called repetitively by itself. 1.19 Pointers A pointer is a memory variable that stores a memory address. It can have any name that is legal for another variable and it is declared in the same fashion like other variables but it is always denoted by * operator. Void pointers: Pointers can also be declared as a void type. Void pointers cannot be dereferencing without explicit type conversion.

1.20. Structure: A structure is a collection of one or more variables of different data types grouped together under a single name. typedef: By using typedef we can create new data type. The statement typedef is to be used while defining the new data type. The syntax is typedef type dataname; type is the data type; dataname is the user-defined name for that type. Bit-fields: A bit field provides the exact amount of bits required for storage of values. Enumerated data type: Enum is a keyword. It is used for declaring enumeration types. The programmer can create his/her own data type and define what values the variables of these data types can hold. Eg. enum month{Jan, Feb, Mar, Apr, may, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; 1.21 Union: Union is a variable, which is similar to the structure. It contains a number of members like structure but it holds only one object at a time.

1.22 Files File: File is a set of records that can be accessed through a set of library functions.

File types: 1. Sequential file Steps for file operations: Opening a file Reading or writing a file Closing a file File functions: 2. Random access file

Function fopen() fclose() closeall() fgetc() getc() fprintf() fscanf() putc() fputc() gets() puts() putw() getw() fread() fwrite() fseek() feof() ferror() perror() ftell() rewind() unlink() rename()

Operation Creates a new file for read/write operation Closes a file associated with file pointer Closes all opened files with fopen() Reads the character from current pointer position and advances the pointer to next character Same as fgetc() Writes all types of data values to the file Reads all types of data values from a file Writes character one by one to a file Same as putc() Reads string from the file Writes string to the file Writes an integer to the file Reads an integer from the file Reads structured data written by fwrite() function Writes block of structured data to the file Sets the pointer position anywhere in the file Detects the end of the file Reports error occurred while read/write operations Prints compilers error messages along with user-defined messages Returns the current pointer position Sets the record pointer at the beginning of the file Removes the specified file from the disk Changes the name of the file

Text Modes:

1. W(write): This mode opens a new file on the disk for writing. If the file already exists, it will be overwritten without confirmation. Syntax: fp=fopen(data.txt, w);
2.

r(read): This mode opens a pre-existing file for reading. If the file does not exist, then the compiler returns NULL to the pointer. Syntax: fp=fopen(data.txt, r);

3. a(append): This mode opens a pre-existing file for appending data. If the file does not exist, then the new file is opened, that is, if the file does not exist then the model of a is same as w. Syntax: fp=fopen(data.txt, a); 4. w+(write+read) It searches for file, if found its contents are destroyed. If the file is not found a new file is created. Returns NULL if fails to open the file. In this mode file can be written and read. Syntax: fp=fopen(data.txt, w+); 5. a+(append+read) In this mode file can be read and records can be added at the end of file. Syntax: fp=fopen(data.txt, a+); 6. r+(read+write): This mode is used for both reading and writing. We can both read and write the record in the file. If the file does not exist, then the compiler returns NULL to the pointer. Syntax: fp=fopen(data.txt, r+); Binary modes: 1. wb(write) This mode opens a binary file in write mode

rb(read) 3. ab(append) data can be added


2. 4.

This mode opens a binary file in read mode This mode opens a binary file in append mode, i.e., at the end of file. This mode opens a pre-existing file in read and This mode creates a new file in read and This mode opens a file in append mode, i.e. end of the file

r+b(read+write) write mode 5. w+b(read+write) write mode 6. a+b(append+write) data can be written at the

1.23 Command line arguments Command: An executable program that performs a specific task for operating system is called as command. Command line arguments: Arguments are associated with the commands; hence these arguments are called as command line arguments. Application of Command line arguments: 1. Type 2.Del3. Rename

Environment variables: Environment variable provide different settings/ path related to operating system.

C PROGRAMS 1. Write a c program to find out the Greatest of Three Numbers

#include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf(enter the three numbers\n); scanf(%d%d%d,&a,&b,&c); printf(the greatest number is\n); if((a>b)&&(a>c)) printf(a is greatest %d,a); else if(b>c) printf(b is greatest %d,b); else printf(c is greatest %d,c); getch(); } Output: enter the three numbers 90 89 67 a is greatest 90

Explanation: a=90,b=89,c=67 (90>89)&&(90>67) and operator in relational expression of if branch is true when both condition is true so the true part of the if alone works, the branch is not directed to the false part. 2. Write a C program to find out the Area and Circumference of Circle #include<stdio.h> #include<conio.h> void main() {

float a,b,c; clrscr(); printf(enter the r value\n); scanf(%f,&r); a=3.14*r*r; b=2*3.14*r; printf(area=%f\n,a); printf(circumference=%f\n,b); getch(); } Output: enter the r value 3 area=28.26 circumference=18.84 Explanation: r=3 a=3.14*3*3 b=2*3.14*3 area =28.26 circumference=18.84

3. Write a C program to find out the Average of three Real Numbers #include<stdio.h> #include<conio.h> void main() { float a,b,c,x; clrcsr(); printf(enter the three real numbers:\n); scanf(%f%f%f,&a,&b,&c); x=(a+b+c)/3; printf(average=%f\n,x); getch(); }

Output: enter the three real numbers: 3 4 5 average=4.000000 Explanation: Here 3,4,5 are made in float format as float a=3.000000 b=4.000000 c=5.000000 x=(3.000000+4.000000+5.00000)/3 x=12.000000/3 x=4.000000 4. Write a C program to find out the Sum of two Numbers #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf(enter the two numbers:\n); scanf(%d%d,&a,&b); c=a+b; printf(sum=%d,c); getch(); } Output: enter the two numbers: 5 4 sum=9 Explanation: a=5,b=4 c=a+b + operator performs addition on both the operands. c=5+4 c=9

5. Write a C program to convert Hour into Minutes #include<stdio.h> #include<conio.h> void main() { float h,m; clrscr(); printf(enter the hour:\n); scanf(%f,&h); m=n*60; printf(minutes=%f,m); getch(); } Output: enter the hour: 8 minutes=480.000000 Explanation: Hour=8.000000 M=8.0000000*60 Minutes=480.000000

6. Write a C program to find out the Simple Interest #include<stdio.h> #include<conio.h> void main() { float p,n,r,s; clrscr(); printf(enter the p,n,r value:\n); scanf(%f%f%f,&p,&n,&r); s=(p*n*r)/100; printf(simple interest=%f,s); getch(); }

Output: enter the p,n,r value: 30000 2 3 simple interest=1800.000000 Explanation: P=30000,n=2,r=3 s=(p*n*r)/100 s=(30000.000000*2.000000*3.0000)/100 s=180000.000000/100 s=1800.000000 7. Write a C program to convert Celsius to Fahrenheit #include<stdio.h> #include<conio.h> void main() { float f,c; clrscr(); printf(enter the celsius value:\n); scanf(%f,&c); f=((c*9)/5)+32; printf(fahrenheit value=%f,f); getch(); } Output: enter the celsius value: 37 fahrenheit value=98.599998 Explanation: Celsius=37.000000 f=((c*9)/5)+32 f=((37.000000*9)/5)+32 f=((333.000000)/5)+32; f=66.599998+32 f=98.599998 8. Write a C program to find out the Area and Perimeter of Rectangle

#include<stdio.h> #include<conio.h> void main() { float a,b,l,p; clrscr(); printf(enter the l and b value:\n); scanf(%f%f,&l,&b); a=l*b; p=2*(l+b); printf(area=%f\n perimeter=%f\n,a,p); getch(); } Output: enter the l and b value: 6 8 area=48.000000 perimeter=28.000000 Explanation: L=6.0000000,b=8.000000 a=l*b 6.0000000*8.000000=48.000000 p=2*(l+b) 2*(6.000000+8.0000000) 2*(14.000000) area=48.000000 perimeter=28.000000 9. Write a C program to find out the Area and Perimeter of Square #include<stdio.h> #include<conio.h> void main() { float s,a,p; clrscr(); printf(enter the s value:\n); scanf(%f,&s); a=s*s; p=4*s; printf(area=%f\n perimeter=%f\n,a,p); getch();

} Output: enter the s value: 5 area=25.000000 perimeter=20.000000 Explanation: S=5.000000 a=s*s 5.000000*5.000000=25.000000 p=4*s 4*.5.000000 =20.000000 area=25.000000 perimeter=20.000000 10. Write a C program to find out the Sum and Percentage of five Marks #include<stdio.h> #include<conio.h> void main() { int a,b,c,d,e,s; float x; clrscr(); printf(enter the 5 marks:\n); scanf(%d%d%d%d%d,&a,&b,&c,&d,&e) s=a+b+c+d+e; x=s/5.0; printf(sum=%d \npercentage=%f\n,s,x); getch(); } Output: enter the 5 marks: 87 98 78 76 89 sum=428 percentage=85.000000

Explanation: a=87,b=98,c=78,d=76,e=89 s=a+b+c+d+e 87+98+78+76+89 = 428 x=s/5 =428/5.0 (integer by float results in float) =85.000000 sum=428 percentage=85.000000 11. Write a C program for Swapping two Values without Using Temporary Variables #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf(enter the two values\n); scanf(%d%d,&a,&b); a=a+b; b=a-b; a=a-b; printf(a=%d\nb=%d\n,a,b); getch(); } Output: enter the two values: 9 8 a=8 b=9 Explanation: a=9,b=8 a=a+b a=8+9 =17 b=a-b b=17-8=9 a=a-b a=17-9=8 a=8 b=9

12. Write a C program for Swapping two values Using Temporary Variable #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf(enter the two values\n); scanf(%d%d,&a,&b); c=a; a=b; b=c; printf(a=%d\nb=%d,a,b); getch(); } Output: enter the two values: 9 8 a=8 b=9 Explanation: a=9,b=8 c=a c=9 c is assigned with a value a=b a=8 a is assigned with b value then a value is changed with b b=c b= 9 b is assigned with c value then b value is changed with c a=8 b=9 13. Write a C program to check the given year is Leap Year or not #include<stdio.h> #include<conio.h> void main()

{ int a; clrscr(); printf(enter the year\n); scanf(%d,&a); if(a%4==0) printf(leap year); else printf(not a leap year); getch(); } Output: enter the year: 1998 not a leap year. Explanation: a=1998 (a%4==0) (1998%4==2) so the if condition is not matched so the false part works and the result is not a leap year if condition is matched when modulus operator gives the remainder as zero

14. Write a C program to check whether the person is eligible to Vote or Not #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf(enter the age\n); scanf(%d,&a); if(a>=18) printf(eligible to vote); else printf(not eligible);

getch(); } Output: enter the age: 21 eligible to vote Explanation: A=21 (21>=18) here the result of the relational expression is true (18 and more than 18 is true) so eligible to vote 15. Write a C program to find out the given number is Greater than100 or Not #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf(enter the number\n); scanf(%d,&a); if(a>100) printf(greater than 100); else printf(less than 100); getch(); } Output: enter the number 366 greater than 100 Explanation: A=366 (366>=100) here the result of the relational expression is true

so the true part of the if branching or decision statement is carried out so the result is greater than 100 16. Write a C program to find out the biggest of two Numbers: #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf(enter the 2 numbers); scanf(%d%d,&a,&b); if(a>b) printf(a is biggest); else printf(b is biggest); getch(); } Output: enter the two numbers: 6 7 b is biggest. Explanation: a=6,b=7 (6>7) here the if condition is not true so the else (false part of the if is carried out) so the result is b is biggest. 17. Write a C program to find out the given number is Odd or Even Number #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf(enter the number\n); scanf(%d,&a); if(a%2==0)

printf(even number); else printf(odd number); getch(); } Output: enter the number 9 odd number Explanation: A=9 (9%2==0) (1==0) so the else part of the if statement is carried out so the result is odd number

18. Write a C program to convert Fahrenheit to Celsius #include<stdio.h> #include<conio.h> void main() { float f,c; clrscr(); printf(enter the fahrenheit value\n); scanf(%f,&f); c=((f-32)*5)/9; printf(celsius value=%f,f); getch(); } Output: enter the fahrenheit value: 98.6 celsius value=37.00000 Explanation: Fareheit value=98.600000 c=((f-32)*5)/9

c=((98.60000-32)*5)/9 c=((66.599998*5)/9 c=333.00000/9 c=37.000000 19. Write a C program to find out the Greatest of two Numbers Using Conditional Operator #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf(enter the 2 numbers); scanf(%d%d,&a,&b); (a>b?printf(a is greater):printf(b is greater)); getch(); } Output: enter the two numbers 6 3 a is greater Explanation: a=6, b=3 6>3? 1:0; Conditional operator is checked if it is true the statement after the ? will be executed or otherwise after the : will be executed here it is true so the 1 part is executed to get the result as a is greater 20. Write a C program to find out the Roots of Quadratic Equation #include<stdio.h> #include<conio.h> #include<math.h> void main() { int a,b,c,d; float x1,x2; clrscr(); printf(\nenter the values of a,b,c\n);

scanf(%d%d%d,&a,&b,&c); d=b*b-4*a*c; if(d==0) { printf(\nthe roots are real and equal); x1=-b/(2*a); printf(%f\n,x1); } else if(d<0) { printf(\nthe roots are imaginary\n); x1=-b/(2*a); x2=sqrt(-d)/(2*a); printf(%2f+i%2f\n,x1,x2); printf(%2f-i%2f\n,x1,x2); } else { printf(\n the roots are real and distinct); x1=-b+sqrt(d)/(2*a); x2=-b-sqrt(d)/(2*a); printf(\n%f\n%f,x1,x2); } getch(); } Output: enter the values of a,b,c 2 8 3 the roots are real and distinct -6.418861 -9.581139 Explanation: a=2,b=8,c=3 d=8*8-4*2*3 d=40 here the d value is not equal to zero and and also no less than zero so the real and distinct part of the if else ladder statement is branched x1=-8+sqrt(40)/(2*2) x2=-8-sqrt(40)/(2*2)

so the result is the roots are real and distinct -6.418861 -9.581139 21. Write a C program to perform Menu Driven Calculator #include<stdio.h> #include<conio.h> void main() { int a,b,c,ch; clrscr(); printf(\n1.add\n2.subtract\n3.multiply\n4.division\n5.remainder\n); printf(\nenter your choice\n); scanf(%d,&ch); switch(ch) { case1: printf(\nenter values of a and b\n); scanf(%d%d,&a,&b); c=a+b; printf(\nthe answer is %d,c); break; case2: printf(\nenter values of a and b\n); scanf(%d%d,&a,&b); c=a-b; printf(\nthe answer is %d,c); break; case3: printf(\nenter values of a and b\n); scanf(%d%d,&a,&b); c=a*b; printf(\nthe answer is %d,c); break; case4: printf(\nenter values of a and b\n); scanf(%d%d,&a,&b); c=a/b;

printf(\nthe answer is %d,c); break; case5: printf(\nenter values of a and b\n); scanf(%d%d,&a,&b); c=a%b; printf(\nthe answer is %d,c); break; default: printf(\nenter the correct choice); break; } getch(); } Output: 1.add 2.subtract 3.multiply 4.division 5.remainder enter your choice 2 enter the values of a and b 7 4 the answer is 3 Explanation: Ch=2 So the case constant value 2 of the switch is alone branched a=7,b=4 c=a-b c=7-4 c=7 the answer is 3 22. Write a C program to covert Decimal to Binary Conversion #include<stdio.h> #include<conio.h> #include<math.h>

void main() { int no,r,sum=0,i=0; clrscr(); printf(\nenter the number\n); scanf(%d,&no); while(no>0) { r=no%2; sum=sum+pow(10,i)*r; no=no/2; i++; } printf(\nthe binary value is %d,sum); getch(); } Output: enter the number 8 the binary value is 1000 Explanation: No=8, i=0 while(8>0) r=8%2 r=0 sum=0+pow(10, 0)* 0 n0=8/2 n0=4 again the while loop is checked either no is greater than zero the above body of the loop will be executed until the condition is true other wise control will come out of the loop then the result is the binary value is 1000 23. Write a C program to display the Number and its Square #include<stdio.h> #include<conio.h> void main() { int n,i; clrscr(); printf(enter the value of n\n); scanf(%d,&n);

for(i=1;i<=n;i++) printf(the number is %d and its square is %d\n,i,i*i); getch(); } Output: enter the value of n 3 the number is 1 and its square is 1 the number is 2 and its square is 4 the number is 3 and its square is 9 Explanation: I=1,n=3 for(i=1;1<=3;) condition is true so the body of the loop is executed in printf i and i * i value is printed then the I value is incremented and checked with the condition until the condition is true the body of the loop is executed. Otherwise control passes out of the loop. 24. Write a C program to find out the Sum and Average of First N Numbers #include<stdio.h> #include<conio.h> void main() { int i,sum=0,n; float avg; clrscr(); printf(enter the value of n\n); scanf(%d,&n); for(i=1;i<=n;i++) { sum=sum+i; } printf(sum=%d\n,sum); avg=sum/n; printf(average=%f,c); getch(); }

Output: enter the value of n 5 sum=15 average=3 Explanation: N=5,sum=0, i=1 for(i=1;1<=5;i++) sum=0+1 sum=1+2 sum=3+3 sum=6+4 sum=10+5 sum=15 this is calculated still the condition is true avg=15/5=3 25. Write a C program to Print the prime numbers From N to 1 #include<stdio.h> #include<conio.h> void main() { int p; clrscr(); printf(\nenter the value of n\n); scanf(%d,&p); for( ;p>0;p--) printf(%d\n,p); getch(); } Output: enter the value of n 4 4 3 2 1 Explanation: p=4, this is initialization of the for loop

for(;4>0;4--) the value is printed as 4 for each iteration the p value is decremented by one the next iteration value of p is 3 so the result is 4 3 2 1 26. Write a C program to find out the Sum of N Numbers #include<stdio.h> #include<conio.h> void main() { int n,sum=0; clrscr(); printf(\nenter the value of n\n); scanf(%d,&n); for(i=1;i<=n;i++) { sum=sum+i; } printf(sum=%d\n,sum); getch(); } Output: enter the value of n 10 sum=55 Explanation: N=10,sum=0 For(i=1;1<=10;i++) Sum=0+1, sum=1+2, sum=3+2, sum=5+3sum=45+10 sum=55 27. Write a C program to find out the Fibonacci Series #include<stdio.h> #include<conio.h> void main() { int a=0,b=1,c=0,i,n; clrscr(); printf(enter the number of terms\n); printf(%d\n%d,a,b);

for(i=3;i<=n;i++) { c=a+b; printf(%d\n,c); a=b; b=c; } getch(); } Output: enter the number of terms 4 0 1 1 2 Explanation: A=0,b=1,c=0n=4 a and b value is printed as 0 and 1 for(i=3;3<=4;i++) c=a+b =0+1 c=1 in body of the for loop a=b a=1 b=c b=1 so the output is 0 1 1 2 28. Write a C program to find out the Factorial of a Given Number #include<stdio.h> #include<conio.h> void main() { int n,i,fact=1; clrscr(); printf(enter the number\n); scanf(%d,&n); for(i=n;i>=1;i--) { fact=fact*i; } printf(the factorial of given number is %d,fact); getch();

} Output: enter the number 5 the factorial of given number is 120 Explanation: Fact=1 N=5 for(i=5;5>=1;5--) fact=fact*i fact=1*5,fact=5*4,fact=20*3 fact=60*2 fact=120*1 the factorial of given number is 120 29. Write a C program to find out the Sum of N Numbers Using While Loop #include<stdio.h> #include<conio.h> void main() { int i=1,sum=0; clrscr(); printf(enter the value of n\n); scanf(%d,&n); while(i<=n) { sum=sum+i; i++; } printf(sum=%d,sum); getch(); } Output: enter the value of n 5 sum=15 Explanation: i=1,sum=0 n=5

while(1<=5) sum=0+1 i=2 sum=1+2 i=3 sum=3+3 i=4 sum=6+4 i=5 sum=10+5 i=6 condition is false therefore the sum is 55 30. Write a C program to calculate the Electric Energy Bill #include<stdio.h> #include<conio.h> void main() { float r,a=2.5,b=3.5,c=1.5; clrscr(); printf(enter the readings\n); scanf(%f,&r); if(r>=200) printf(rupees=%f,r*b); else if((r>=100)&&(r<200)) printf(rupees=%f,r*a); else printf(rupees=%f,r*c); getch(); } Output: enter the readings 140 rupees=280.000000 Explanation: a=2.5,b=3.5,c=1.5 r=140.000000 the condition matches in else if (140.00000>=100 && 140.000000<200) 140.00000*2

280.000000 31. Write a C program to display the Prime Numbers between 100 and 500 #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); printf(the prime numbers are:\n); for(i=100;i<=500;i++) { for(j=2;j<i;j++) { if(i%j==0) break; } if(i==j) printf(%d\t,i); } getch(); } Output: the prime numbers are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 Explanation: Here we used the nested for loop I=100;100<=500,i++ J=2;2<100,j++ The innermost loop has an simple if first time 100 is modulus by 2 to get remainder as zero The i==j is not matched if it is matched then the value of j is printed as prime number

then the j value is incremented the innermost loop runs until the condition is satisfied when the inner most is not satisfied only the I value is incremented again the innermost loop runs until the condition is satisfied this happens as no of outermost iteration * innermost iteration to get the prime numbers from 100 to 500. 32. Write a C program to find out the given number is Armstrong Number or not #include<stdio.h> #include<conio.h> #include<math.h> void main() { int n,k,r,sum=0; clrscr(); printf(enter the number\n); scanf(%d,&n); k=n; while(n!=0) { r=n%10; sum=sum+pow(r,3); n=n/10; } if(sum==k) printf(the number is armstrong); else printf(the number is not armstrong); getch(); } Output: enter the number 153 the number is Armstrong Explanation: Sum=0

N=153 While(153!=0) r=153%10 r=3 Sum=0+pow(3,3) sum=0+27 n=153/10 n=15 15!=0 r=15%10 r=5 sum=27+pow(5,3) sum=27+125 n=15/10 n=1 1!=0 r=1%10 r=1 sum=152+pow(1,3)= 152+1 n=1/10 condition is not matched then in if condition the cube of the individual digits of the number is checked with the original number to find it is Armstrong or not so the result is the number is Armstrong 33. Write a C program to find out the given number is Palindrome Number or Not #include<stdio.h> #include<conio.h> void main() { int n,k,r,sum=0; clrscr(); printf(enter the number\n); scanf(%d,n); k=n; while(n!=0) { r=n%10; sum=sum*10+r; n=n/10; } if(sum==k) printf(the number is palindrome); else printf(the number is not palindrome); getch(); }

Output: enter the number 323 the number is palindrome Explanation: N=323 r=323%10 r=3,sum=0*10+r,sum=3, n=323/10,n=32 r=32%10 r=2 sum=30+2 sum=32 n=32/10 n=3 r=3%10 r=3 sum=320+3 n=3/10 n=0 if condition matches so the given number is palindrome 34. Write a C program to find out the Maximum Value in the Array #include<stdio.h> #include<conio.h> void main() { int a[5],max,i; clrscr(); printf(enter elements for the array\n); for(i=0;i<5;i++) scanf(%d,&a[i]); max=a[0]; for(i=1;i<5;i++) { if(max>a[i]) max=a[i]; } printf(the maximum value is%d,max); getch(); }

Output: enter the elements for array 4 6 3 8

5 the maximum value is 8 Explanation: Size is 4 6,3,8,5 max=a[0] max=6 the first number is assumed as maximum and it is compared with all other numbers to find which is the maximum by using for loop if(6>3) condition fails (6>8) condition matches then max=8, (8>5) condition fails. So the maximum value is 8 35. Write a C program to perform Matrix Multiplication #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],r1,r2,c1,c2,i,j,k; clrscr(); printf(enter the no.of rows and columns for 1st matrix:\n); scanf(%d%d,&r1,&c1); printf(enter the values of 1st matrix:\n); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf(%d,&a[i][j]); } printf(enter the no.of rows and columns for 2nd matrix:\n); scanf(%d%d,&r2,&c2); printf(enter the values of 2nd matrix:\n); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) scanf(%d,&b[i][j]); } if(c1==r2) { for(i=0;i<r1;i++) { for(j=0;j<c2;j++)

{ c[i][j]=0; for(k=0;k<c1;k++) { c[i][j]=c[i][j]+a[i][k]+b[k][j]; } } } printf(resultant matrix is:\n); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { printf(%d\t,c[i][j]); } printf(\n); } } else printf(the matrix are not multiplied); getch(); } Output: enter the no.of rows and columns for 1st matrix: 3 3 enter the values of 1st matrix: 1 1 1 1 1 1 1 1 1 enter the rows and columns for 2nd matrix: 3 3 enter the values of 2nd matrix:

1 1 1 1 1 1 1 1 1 resultant matrix is: 3 3 3 3 3 3 3 3 3 Explanation: r1=3,c1=3,r2=3,c2=3 By using nested for loop one is for the row and another is for the column of the matrix the inputs of the two matrix is obtained . Then multiplication is carried by the following steps by taking the row of the first matrix1 and column1 of the matrix2 is multiplied and added and the result is stored in the c matrix by using the three for loops by specifying exactly the variables in the for loop Then the resultant multiplied matrix is printed. If the column 1 of the matrix 1 and row 2 of the matrix is not equal the we cannot perform the matrix multiplication. 36. Write a C program to display the following output * * * * * * * * * #include<stdio.h> #include<conio.h> void main() { int i,j,k; clrscr(); for(i=1;i<=3;i++) { for(j=3;j>=i;j--) { printf( ); }

for(k=1;k<=i*2-1;k++) { printf(*); } printf(\n); } getch(); } Explanation: The j for loop prints two empty spaces The k loop for the first time prints the single * then the new line works and after the i for loop is incremented Then for the next iteration of the outermost I loop j loop prints single space k loop prints three * and new line and so on until the condition to match to get desired output 37. Write a C program to display the following Output * * * * * * * * * * * * * * * #include<stdio.h> #include<conio.h> void main() { int i,j,k; clrscr(); for(i=1;i<=5;i++) { for(j=5;j>i;j--) printf( ); for(k=1;k<=i;k++) printf(*); printf(\n); } getch(); } Explanation:

The innermost loop of j prints five empty spaces and the k loop prints single * based on the condition and the new line works In the next iteration printing of spaces is reduced by one and printing * has been increased one this process is repeated to get the desired output. 38. Write a C program to perform searching the element in an Array #include<stdio.h> #include<conio.h> void main() { int j=0,n,x[5]; clrscr(); printf(enter the elements of array\n); for(j=0;j<5;j++) scanf(%d,&x[j]); printf(enter the element to search\n); scanf(%d,&n); for(j=0;j<5;j++) { if(x[j]==n) break; } if(x[j]==n) printf(element found); else printf(element not found); getch(); } Output: enter the elements of array: 1 2 3 4 5 enter the elements to search 3 element found Explanation: Elements are x[5]={1, 2, 3, 4, 5}

This is obtained by the scanf statement which is inside the forloop N=3 X[0],x[1],x[2],x[3],x[4] 1==3,1==2,1==3 condition matches at this part of the if which is inside the for loop we have break in the if so the control comes out the for loop. By if condition the result is element found 39. Write a C program to perform inserting elements in an Array #include<stdio.h> #include<conio.h> void main() { int num[20],j,p,n,s; clrscr(); printf(enter the number of elements\n); scanf(%d,&n); printf(enter the elements of array\n); for(j=0;j<n;j++) scanf(%d,&num[j]); printf(enter the element and positon to be inserted\n); scanf(%d%d,&s,&p); p--; for(j=n;j!=p;j--) { num[j]=num[j-1]; } num[j]=s; for(j=0;j<=n;j++) printf(%d,num[j]); getch(); } Output: enter the number of elements 4 enter elements 1 2 3

5 enter the element and position to be inserted 4 4 1 2 3 45 Explanation: Array size 4 elements are 1 2 3 4 Elements are num[5]={1, 2, 3, 4, 5} This is obtained by the scanf statement which is inside the for loop Element and position is obtained and the position is decremented by one because the array element starts with num[0] location in the for loop we make the elements to shift from the original position to one above because while inserting one element in the middle array size grow by one. If the desired position is met after the for loop the element is inserted and the elements are printed by matching the condition <=n. to get the last element also. 40. Write a C program to perform deleting element in an Array #include<stdio.h> #include<conio.h> void main() { int num[20],j,p,n,s; clrscr(); printf(enter the number of elements\n); scanf(%d,&n); printf(enter the elements of array\n); for(j=0;j<n;j++) scanf(%d,&num[j]); printf(enter the position to delete\n); scanf(%d,&p); p--; for(j=p;j<n;j++) num[j]=num[j+1]; for(j=0;j<n-1;j++) printf(%d,num[j]); getch(); } Output: enter the number of elements

3 enter elements 1 2 3 enter the position to delete 2 1 3 Explanation: Array size 3 num[]={1,2,3} This is obtained by the scanf statement which is inside the for loop Position is obtained to delete the element in the position and position is decremented by one because the array element starts with num[0] location in the for loop we make the elements to shift from the original position to one below because while deleting one element in the middle array size shrinks by one If the desired position is met after the for loop the element is deleted and the elements are printed by matching the condition <n-1 to get the remaining elements after the deletion. 41. Write a C program to perform sorting the elements in an array #include<stdio.h> #include<conio.h> void main() { int num[20],j,k,n,t; clrscr(); printf(enter the number of elements\n); scanf(%d,&n); printf(enter the elements of array\n); for(j=0;j<n;j++) { scanf(%d,&num[j]); } for(k=0;k<s;k++) { for(j=k+1;j<n;j++) { if(a[j]>a[k]) { t=a[k]; a[k]=a[j];

a[j]=t; } } } printf(Sorted elements); for(j=0;j<n;j++) { Printf(%d\n, a[j]); } getch(); } Output: enter the number of elements 3 5 3 8 3 5 8 Explanation: In the above program the n value =3 Three values are obtained and stored in the num array. 5 3 8 By using two nested for loops the outer most loop to take the first element and the inner most loop to take the second element and is compared in branching statement if the condition is matched the swapping happens. 5>3 condition matches swapping the two locations 3 and 5 this process continues until the outer and inner most of the for loop to get the sorted elements in their locations. Finally the sorted elements are printed as 3 5 8. 42 Write a C program to perform merging the elements in an Array #include<stdio.h> #include<conio.h> void main() { int j,h=0,k=0; int x[4]={1,2,3,4}; int y[4]={5,6,7,8}; int z[8]; clrscr(); printf(array x:\n); for(j=0;j<4;j++)

printf(%d,x[j]); printf(array y:\n); for(j=0;j<4;j++) printf(%d,y[j]); j=0; while(j<8) { if(j%2==0) z[j]=x[k++]; else z[j]=y[h++]; j++; } printf(array z:\n); for(j=0;j<8;j++) printf(%d,z[j]); getch(); } Output: array x: 1 2 3 4 array y: 5678 array z: 15263748 Explanation: By using a for loop to print the first array elements By using another for loop to print the second array elements The for merging the two arrays while loop is used inside the while loop the odd value elements in the first array and the even no elements in the second array is stored in the third array as merged elements the merged array is printed by another for loop. 43 Write a C program to perform the sorting the given Strings in Ascending Order #include<stdio.h> #include<conio.h> #include<string.h> void main() {

int i,j,n,x; char str[20][20],str1[20][20]; clrscr(); printf(enter the number of strings:\n); scanf(%d,&n); for(i=0;i<n;i++) { printf(\nenter str[%d],i+1); scanf(%s,&str[i]); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { x=strcmp(str[i],str[j]) if(x>0) { strcpy(str[1],str[j]); strcpy(str[j],str[i]); strcpy(str[i],str[1]); } } } printf(\nthe sorted strings in ascending order is\n); for(i=0;i<n;i++) { printf(\n%s,str[i]); } getch(); } Output: enter the number of strings: 3 enter str[1] raja enter str[2] vignesh enter str[3] adhi the sorted strings in ascending order is adhi raja vignesh

Explanation: N=3 By using two dimensional character array the first subscript to denote the number of strings that u are going to get as input and the second subscript to store the each and every particular string. the input as 3 strings are obtained through For loop with inside as scanf statement. Two nested for loop is used , one is used to denote the first string and the second is used to denote the second string comparison is made by comparing the ASCII difference between the characters of the both string if the ith string character ASCII value is greater then the jth string is swapped with ith string by using strcpy function. In the inner most iteration the string has the least ASCII value will be in the first location of the character array. This process continues until the condition is satisfied to get the sorted strings. 44. Write a C program to find out the Fibonacci Series using Recursive Function #include<stdio.h> #include<conio.h> int fibo(int,int) int t1,t2,t3,count; void main() { printf(enter the number of terms\n); scanf(%d,&n); t1=0; t2=1; printf(%d\t%d,t1,t2); count=2; fibo(t1,t2); getch(); } int fibo(int t1,int t2) { if(count<=n) return 0; else { t3=t1+t2; printf(\t%d,t3);

count++; t1=t2; t2=t3; fibo(t1,t2); } } output: enter the number of terms 5 01123 Explanation: First the t1 and t2 values are printed. t1=0 t2=1 Then we have the calling function of fibo with actual arguments of values t1 and t2. Then the control directly passes to the called function in that function t3=0+1 And the next term is printed and the count value is incremented and the t1 and t2 values are assigned as t1=t2 and t2=t3 T1=1 and t2=1 Again we had a direct recursion a called function calling itself. Until the if condition of the count to get the Fibonacci series of the consecutively the next terms. 45. Write a C program to find out the Swapping of two Values using Functions #include<stdio.h> #include<conio.h> int swapval(int,int); int swapref(int*,int*); int a,b; void main() { clrscr(); printf(enter the two values\n); scanf(%d%d,&a,&b); printf(pass by value\n); printf(before function call a=%d b=%d ,a,b); swapval(a,b); printf(after function swapval a=%d b=%d ,a,b); printf(pass by reference\n); printf(before function call a=%d b=%d ,a,b);

swapref(&a,&b); printf(after function swapref a=%d b=%d ,a,b); getch(); } swapval(int x,int y) { int t; t=x; x=y; y=t; printf(\nwith swap val x=%d y=%d,x,y); } swapref(int*x,int*y) { int *t; *t=*x; *x=*y; *y=*t; printf(\nwith swapref x=%d y=%d ,*x,*y); } Output: give two numbers 5 6 pass by value before function call a=5 b=6 with swapval x=6 y=5 after function swapval a=5 b=6 pass by reference before function call a=5 b=6 with swapref x=6 y=5 after function swapref a=6 b=5 Explanation: A=5 and b=6 in main function By calling function of swapval as actual arguments of a and b value is passed to the called function In the called function the swapping happens by using a temporary variable that does not affect the actual arguments because the formal arguments are the photocopies of the actual arguments.

So the result is pass by value before function call a=5 b=6 with swapval x=6 y=5 after function swapval a=5 b=6 A=5 and b=6 in main function By calling function of swapref as actual arguments of a and b reference (address) is passed to the called function In the called function the swapping happens by using a temporary variable that affect the actual arguments because the The changes are directly happens in the actual arguments So the result is pass by reference before function call a=5 b=6 with swapref x=6 y=5 after function swapref a=6 b=5 46. Write a C program to perform the Substring Replacement #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[50],str1[15],str2[15],temp[50]; char *ptr; int cnt; clrscr(); printf(enter a line of text..... \n); gets(str); printf(enter the string to be replaced... \n); gets(str1); printf(enter the replacing string...); gets(str2); printf(\n the replaced line of the text....); while(1) { ptr=strstr(str,str1); if(ptr==\o) break; cnt=ptr-str; strncpy(temp,str,cnt);

temp[cnt]=\0; strcat(temp,str+cnt+strlen(srt1)); strcpy(str1,temp); puts(str); } getch(); } Output: enter the line of text... i love india enter the string to be replaced..india enter the replacing string...my parents the replaced line of text i love my parents Explanation: By using str character array the original line of text is obtained from the user. By using str1 character array the substring which is to be replaced is obtained. By using st2r character array the replacing string is obtained In while condition By str str function either str1 is present in the line of text or not if then its address is obtained and stored in the pointer variable. If the replacing string is available then the program terminates other wise count is calculated from the input from I to love and one space. This is copied to the temp array. Then the string which is to be replaced is concatenated and also of the remaining text after replaced in the original text is also appended. Then the result is displayed. 47. Write a C program to transpose of a Matrix using Function #include<stdio.h> #include<conio.h> #include<string.h> void main() { void trans(int,int,int[10][10]); int i,j,a,b,m[10][10]; clrcsr(); printf(enter the rows and columns of matrix); scanf(%d%d,&a,&b);

printf(enter the elements); for(i=1;i<=a;i++) { for(j=1;j<=b;j++) { printf(enter m[%d][%d]...i,i); scanf(%d,&m[i][j]); } } printf(\n before transpose\); for(i=1;i<=a;i++) { for(j=1;j<=b;j++) { printf(%d\t,m[i][j]); } printf(\n); } trans(a,b,m); getch(); } void trans(inta,intb,intm[10][10]) { int i,j; printf(after transpose); for(j=1;j<=b;j++) { for(i=1;i<=a;i++) { printf(\t%d,m[i][j]); } printf(\n); } } Output: enter the rows and columns of matrix..3 3 enter the elements enter m[1][1]=1 enter m[1][2]=2

enter m[1][3]=3 enter m[2][1]=4 enter m[2][2]=5 enter m[2][3]=6 enter m[3][1]=7 enter m[3][2]=8 enter m[3][3]=9 before transpose 1 2 3 456 789 after transpose 1 4 7 258 369 Explanation: Here the row value is obtained in the a variable and column value is obtained in the b variable. In nested form of two for loop the value of the matrix is obtained and the row value and column value and the matrix elements are passed as actual arguments in the calling function name trans. This program illustrates the passing array as an argument to the function In the called function trans first for loop is used for column and the second for loop is used for to get the transposed values of the matrix rows as columns and columns as rows. 48. Write a C program to find out the Standard Deviation using Function #include<stdio.h> #include<conio.h> #include<math.h> float mean(int a[],int n); float std(int a[],int n,float m); void main() { float m,sd; int n,a[10],i; clrscr(); printf(\nenter the number of values\n); scanf(%d,&n); printf(\n enter the elements\n); for(i=0;i<n;i++) scanf(%d,&n); m=mean(a,n);

printf(mean=%f\n,m); sd=std(a,n,m); printf(\n sd=%f,sd); getch(); } flaot mean (inta[],intn) { float f; int sum=0; for(i=0;i<n;i++) sum=sum+ a[i]; f=(float)sum/n; return f; } float std(int a[],int n,float m) { int i; float std,sum=0.0,d; for(i=0;i<n;i++) { d=a[i]-m; a=d*d; sum=sum+d; } sd=sqrt(sum\n); return sd; } Output: enter the number of values 5 enter the elements 1 2 3 4 5 mean=3.000000 sd=1.414200 Explanation:

N=5, the five values is obtained and stored in the array a In calling the function mean ,passing the array and n value as arguments in the called function sum of 1+2+3+4+5is calculated and typecast of sum and divided by n to get the mean value and is returned to the calling function of main function. In the same way the standard deviation is calculated by the formula subtracting the individual values by the mean value and the result is squared and summed in the sum variable with in a loop then the sqrt of sum by n is obtained to get the result of sd and is returned as output of the called function to the calling function of the main. 49. Write a C program to find out the Palindrome without using String Function #include<stdio.h> #include<conio.h> void main() { char str[20]; int i,j,flag=0; clrscr(); printf(enter a string:\n); scanf(%s,str); i=o; while(str[i]!=10) i++; j=j-1; for(i=0;i<=j;i++,j--) { if(str[i]!=str[j]) { flag=1 break; } } if flag==0 printf(it is palindrome); else printf(it is not a palindrome); getch(); }

Output: enter a string: malayalam it is palindrome Explanation: The string is obtained from the user, and its length is calculated. By using the for loop variables the first character of the string and the last character of the string is compared. If it is not equal flag value will be set as 1 or otherwise as 0. This happens until the condition matches. If the flag value is zero then the given string is palindrome otherwise it is not a palindrome. 50. Write a C program to perform Mark list Analysis using Structures #include<stdio.h> #include<conio.h> #include<string.h> void main() { struct stud { int rno; char name[15]; int marks[5]; int total; float avg; char class[15]; } st[10],temp; int i,n,j; clrscr(); printf(\n enter\n); scanf(%d,&n); for(i=1;i<=n;i++) { printf(\n enter the roll no..); scanf(%d,&st[i].rno); printf(name...\n); scanf(%s,&st[i].name); printf(enter three marks..); for(j=1;j<=3;j++)

scanf(%d,&st[i].marks[j]); } for(i=1;i<=n;i++) { st[i].total=0; for(j=1;j<=3;j++) { st[i].total=st[i].total+st[i].marks[j]; } st[i].avg=st[i].total/30; if(st[i].avg>=75) strcpy(st[i].grade,distinction); elseif(st[i].avg>=60) strcpy(st[i].grade,first); elseif(st[i].avg>=50) strcpy(st[i].grade,second); else strcpy(st[i].grade,fail); } for(i=1;i<=n;i++) { for(j=j+1;j<=n;j++) { if(st[i].total<st[j].total) { temp=st[i]; st[i]=st[j]; st[j]=temp; } } } printf(\n the student details in rankwise\n); for(i=1;i<=n;i++) { printf(\n\n roll no:%d,st[i].rno); printf(\n name :%s,st[i].name); printf(\n marks in three subjects); for(j=1;j<=3;j++) { printf(\n %d,st[i].marks[j]); }

printf (\n total: %d, st[i].total); printf(\n average:%f,st[i].avg); printf(\n grade:%s,st[i].grade); } getch(); } Output: enter 2 enter the roll no...105 name...sheik raja enter the three marks...89 87 78 enter roll no...110 name...sriram enter the three marks...98 96 95 the student details in rankwise roll no:105 name:sheik raja marks in three subjects 89 87 78 total:254 average:84.666664 grade:distinction roll no:110 name:sriram marks in three subjects 98 96 95 total:289 average:96.3333336

grade:distinction Explanation: Structure stud is created By using the structure variable st.structure member the values are obtained for 2 students of n value The roll no and name and three marks of each student is obtained in a for loop. The sum and average marks of the students is calculated and based on the average values class is copied to the structure member class by using string copy function. Then the sorting takes place on the value total to get the ranks. Then the sorted details are prtinted. 51. Write a C program to shift the input data by two bits right #include<stdio.h> #include<conio.h> void main() { int x,y; clrscr(); printf(Read the integer from keyboard(x):); scanf(%d, &x); x>>=2; y=x; printf(The right shifted data is =%d, y); getch(); } Output: Read the integer from keyboard(x): 8 The right shifted data is = 2 Explanation: X=8 X>>=2, x=x>>2 00001000 the last two bits is shifted in right side to get 00000010 The right shifted data is = 2 52. Write a C program to shift the input data by three bits left #include<stdio.h> #include<conio.h> void main() {

int x,y; clrscr(); printf(Read the integer from keyboard(x):); scanf(%d, &x); x<<=3; y=x; printf(The Left shifted data is =%d, y); getch(); } Output: Read the integer from keyboard(x): 2 The left shifted data is = 16 Explanation: X=2 the binary value is 00000010 the three bits shifted in left side to get 00010000 The left shifted data is = 16 53. Write a C program to use bitwise AND operator between the two integers and display the results. #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf(Read the integer from keyboard(a&b):); scanf(%d%d, &a, &b); c=a&b; printf(The answer after AND operation is (c)=%d, c); getch(); } Output: Read the integer from keyboard(a&b): 8 4 The answer after AND operation is (c)=0 Explanation: 00001000 binary value of 8 00000100 binary value of 4 by using AND truth table to and both 8 & 4 to get result as zero

00000000 54. Write a C program to operate OR operation on two integers and display the result. #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf(Read the integer from keyboard(a&b):); scanf(%d%d, &a, &b); c=a| b; printf(The answer after OR operation is (c)=%d, c); getch(); } Output: Read the integer from keyboard (a&b): 8 4 The answer after OR operation is (c)= 12 Explanation: 00001000 binary value of 8 00000100 binary value of 4 by using OR truth table to and both 8 | 4 to get result as 12 00001100 =12 55. Write a C program to operate XOR operation on two integers and display the result. #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf(Read the integer from keyboard(a&b):); scanf(%d%d, &a, &b); c=a^b; printf(The answer afterX OR operation is (c)=%d, c); getch(); }

Output: Read the integer from keyboard (a&b): 8 2 The answer after XOR operation is (c)= 10 Explanation: 00001000 binary value of 8 00000010 binary value of 4 by using XOR truth table to and both 8 ^ 4 to get result as 10 00001010 56. Write a C program to read and print the integer value using character variable. #include<stdio.h> #include<conio.h> void main() { Char a; clrscr(); printf(Enter value of A:); scanf(%d, &a); printf(A=%d, a); getch(); } Output: Enter value of A: 255 A=-1 Enter value of A: 256 A=0 Explanation: Character and integer has compatibility the character which is declared I signed as range is from -128 to 127 this values is repeated after the integer numbers 127 57. Write a C program to check whether the entered number is less than 10. If yes, display the same. #include<stdio.h> #include<conio.h> void main() {

int v; clrscr(); printf(Enter the number:); scanf(%d, &v); if(v<10) printf(\n Number entered is less than 10); sleep(2); getch(); } Output: Enter the number:9 Number entered is less than 10 Explanation: V=9 If(9<10) condition matches and the result is true part of the branching statement as Number entered is less than 10 58. Write a C program to check equivalence of two numbers. #include<stdio.h> #include<conio.h> void main() { int m,n; clrscr(); printf(Enter two numbers:); scanf(%d%d, &m, &n); if(m-n= =0) printf(\n Two numbers are equal); getche(); } Output: Enter two numbers: 5 5 Two numbers are equal Explanation: m=5 and n=5 if(5-5==0)

the subtracted value of m and n is checked with equal to relational operator value zero if it is true then the two numbers m and n are the same else they are the different. 59. Write a C program to calculate the square of those numbers only whose least significant digit is 5 #include<stdio.h> #include<conio.h> void main() { int s,d; clrscr(); printf(Enter a number:); scanf(%d, &s); d=s%10; if(d= =5) { s=s/10; printf(\n square=%d%d, s*s++, d*d); } else Printf(\n Invalid number); } Output: Enter a number: 25 Square =625 Explanation: S=25 S%10 60. Write a C program to convert decimal number to hexadecimal number. #include<stdio.h> #include<conio.h> #include<process.h> void main() { Int x, y=30, z; clrscr(); printf(Enter the number:);

scanf(%d, &x); printf(\n conversion of decimal to hexadecimal number\n); for(;;) { if(x= =0) exit(1); z=x%16; x=x/16; gotoxy(y--,5); switch(z) { Case 10: Printf(A); Break; Case 11: Printf(%c, B); Break; Case 12: Printf(%c, C); Break; Case 13: Printf(D); Break; Case 14: Printf(E); Break; Case 15: Printf(F); Default: Printf(%d, z); } } getch(); } Output: Enter the number: 31 Conversion of decimal to Hexa decimal number 1F Explanation: X=31

z=x%16 31%16 =15 x=x/16 31/16 =1 gotoxy function makes the cursor position to go in the place of F In switch the case constant value 15 is matched and it is printed as F And in the net iteration of the for loop the value is 1 z=x%16 1%16 =1 x=x/16 1/16 =0 gotoxy function makes the cursor position to go one decrement to the place of F In switch the case constant value nothing is matched so the default is printed with the Z value So the output is 1F 61. Write a C program to count number of 1s, blank spaces and others using nested switch() statements. #include<stdio.h> #include<conio.h> void main() { Static int x,s,a,z,o; chartxt[20]; clrscr(); printf(Enter numbers); gets(txt); while(txt[x]!=\0) { Switch(txt[x]) { case: s++; break; default: switch(txt[x]) { case1: a++; break; case0: z++; break;

default: o++ } } X++; } Printf(\n total spaces:%d, s); Printf(\n total 1s:%d, a); Printf(\n total 0s:%d, z); Printf(\n others:%d, o); Printf(\n string length:%d, s+a+z+o); } getch(); } Output: Enter numbers:1110022 222 Total spaces :1 Total 1s :3 Total 0s :2 Others :5 String length :11 Explanation: By using the unformatted input statement gets we are getting the line of text In the while loop each and every character is passed as an constant value of the switch until NULL character. If the character value is 1 then a variable is incremented and if the character value is space s variable is incremented and if the constant value is 0 then z is incremented in default o is incremented. This process is repeated until the NULL character to get the result. 62. Write a C program to print five numbers starting from one together with their squares. #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); for(i=1;i<=5;i++) printf(\n number: %5d its square : %8d, i, i*i);

getch(); } Output: Number: 1 its square: 1 Number: 2 its square: 4 Number: 3 its square: 9 Number: 4 its square: 16 Number: 5 its square: 25 Explanation: The for loop run for five times with the values 1,2,3,4,5, for each iteration its value and its squares are printed until the condition of the loop satisfies. 63. Write a C program to evaluate the series given in comments /*x=1/1+1/4+1/9...1/n2*/ /*y=1/1+1/8+1/27...1/n3*/ #include<stdio.h> #include<conio.h> #include<math.h> void main() { int i,n; float x=0, y=0; clrscr(); printf(enter value of n:); scanf(%d, &n); for(i=1;i<=n; i++) { x=x+(1/pow)i,2)); y=y+(1/pow(i,3)); } Printf(value of x=%f,x); printf(\n value fo y=%f,y); getche(); } Output: Enter value of n:2 Value of x= 1.2500 Value of y=1.12500 Explanation: Here the value of n=2

Until the n value the for loop runs twice as for this input is concerns In order to get the x=x+(1/pow)i,2)) =x=0+(1/pow)1,2=1/1 y=y+(1/pow(i,3)) =y=0+(1/pow)1,3=1/1 x=x+(1/pow)i,2)) =x=1+(1/pow)2,2=1/4 y=y+(1/pow(i,3)) =y=1+(1/pow)2,3=1/8 So the result is Value of x= 1.2500 Value of y=1.12500 64. Write a C program to perform multiplication of two integers by using negative sign. #include<stdio.h> #include<conio.h> void main() { int a,b,c,d=0; clrscr(); printf(\n enter two numbers:); scanf(%d%d, &a, &b); for(c=1;c<=b;c++) d=(d)-(-a); printf(Multiplication of %d * %d:%d,a,b,d); getch(); } Output: Enter two numbers: 5 5 Multiplication of 5 *5 : 25 Explanation A=5 b=5: The for loop runs for five times because c value is incremented five times to come out of the for loop and it is checked with the value of b variable D=0-5 D=5+5 d=10 (-*-=+) D=10+5 d=15 D=15+5 d=20 D=20+5 d=25 65. Write a C program to perform multiplication of two integers by using repetitive addition.

#include<stdio.h> #include<conio.h> #include<math.h> void main() { int a,b,c=1,d=0; clrscr(); printf(\n enter two numbers:); scanf(%d%d, &a, &b); for(;;) d=d+a; if(c= =b) goto stop; c++; } Stop: printf(Multiplication of %d * %d:%d,a,b,d); getch(); } Output: Enter two numbers: 8 4 Multiplication of 8 *4 : 32 Explanation A=8 b=4 D=d+a =0+8 D=8 in the first iteration of the for loop 1==4 condition not matches c variable is incremented d=8+8 d=16 2==4 condition not matches c variable is incremented d=16 +8=24 3==4 condition not matches c variable is incremented d=24 +8=32 4==4 conation matches control goes to stop label by the unconditional branching goto statement and the result is printed Multiplication of 8 *4 : 32 66. Write a C program to simulate a digital clock. #include<stdio.h>

#include<conio.h> #include<dos.h> void main() { int h,m,s; clrscr(); for(h=1;h<=12;h++) { clrscr(); for(m=1;m<=59;m++) { clrscr(); for(s=1;s<=59;s++) { Gotoxy(8,8); printf(hh mm ss); gotoxy(8,9); printf(%d%d%d, h,m,s); sleep(1); } } } getch(); } Output: Hh mm ss 1 1 1 Explanation The above program uses three for loops for hour, minute and second. The inner most loop is for seconds operation followed by middle loop for minutes and the outer most is for hours When the seconds loop executes 60 times the minutes loop increased by 1. Similarly the hours loop increases after completing minutes loop. The hours loop increments only up to 12. There after it resets from 1. The gotoxy () function is used for selecting the position where hh mm ss is tobe marked 67. Write a C program to accept a number and find the sum of its individual digits repeatedly till the result is a single digit. #include<stdio.h> #include<conio.h>

#include<process.h> void main() { int n,s=0; clrscr(); printf(\n enter a number:); scanf(%d, &n); printf(\n Sum of digits till a single digit\n %d, n); for(;n!=0;) { s=s+n%10; n=n/10; if(n= =0) &&s>9) { Printf(\n %2d, s); N=s; S=0; } } printf(\n%2d,s); getch(); } Output: Enter a number:4687 Sum of digits till a single digit 4687 25 7 Explanation: N=4687 S=s+n%10 =0+4687%10 s =0+7 n=n/10 4687/10 n=468 here the if condition is not matches so the next iteration of the for loop is N=468 S=s+n%10 =7+468%10 s =7+8 =15 n=n/10 468/10 n=46 here the if condition is not matches so the next iteration of the for loop is N=46 S=s+n%10 =15+46%10 s =15+6 =21 n=n/10 46/10 n=4

here the if condition is not matches so the next iteration of the for loop is N=4 S=s+n%10 =21+4%10 s =21+4 =25 n=n/10 4/10 n=0 Here the is condition matches so the N=25 and s=0 so again the loop repeats N=25 S=s+n%10 =0+25%10 s =0+5 =5 n=n/10 25/10 n=2 here the if condition is not matches so the next iteration of the for loop is N=2 S=s+n%10 =5+2%10 s =5+2 =7 n=n/10 2/10 n=0 so the result is 7 68. Write a C program to display the series of numbers as given below. 1 21 321 4321 4321 321 21 1 #include<stdio.h> #include<conio.h> void main() { int i,j,x; printf(\n enter value of x:); scanf(%d, &x); clrscr(); for(j=1;j<=x;j++) { for(i=j;i>=1; i--) { Printf(%3d, i); }

Printf(\n); } Printf(\n); for(j=x;j<=1;j--) { for(i=j;i>=1; i--) { Printf(%3d, i); } Printf(\n); } getch(); } Output: Enter value of x: 4 1 21 321 4321 4321 321 21 1 Explanation: Using nested loops, and the test condition setting nature and also the increment decrement values the result is obtained . 69. Write a C program to generate the pyramid structure using numerical #include<stdio.h> #include<conio.h> void main() { int k,i,j,x,p=34; clrscr(); printf(Enter a number:); scanf(%d, &x); for(j=0;j<=x;j++)

{ gotoxy(p,j+1); for(i=0-j;i<=j;i++) printf(%3d, abs(i)); p=p-3; } getch(); } Output: Enter a number: 3 0 101 21012 3 210123 Explanation: Here in the above program p is equated to 34. This number decides the X coordinate on the screen from the numbers are to be displayed. The Y coordinates is decided by J+1 where J is varying from 0 to entered number. The value of is negative towards the left of zero. Hence its absolute value is taken. The inner for loop is executed for displaying digits towards the left and right of zero 70. Write a C program to display array elements in reverse order #include<stdio.h> #include<conio.h> void main() { int show(int*); int num[]={12,13,14,15,16,17,18} clrscr(); show(&num[6]); } Show(int*u) { Int m=6; while(m!=-1) { printf(\nnum[%d]=%d,m,*u); u--, m--;

} return (NULL); getch(); } Output: Num[6]=18 Num[5]=17 Num[4]=16 Num[3]=15 Num[3]=14 Num[1]=13 Num[0]=12 Explanation: In the above program the reference of the array and the number of values in the array are passed as actual arguments in the function show() and in called function should have an pointer variable u to receive the reference. In the called function show() while loop runs until m value is not as -1. and inside of the while loop we are printing the elements of the integer array from the last position and pointer decrement by 2bytes and m value by one. This process is repeated to get the elements of the array in the reversed order. 71. Write a C program to calculate triangular number of an entered number with recursion function method. #include<stdio.h> #include<conio.h> void main() { int n,t,tri_num(int); clrscr(); printf(Enter a number:); scanf(%d, &n); t-tri_num(n); printf(\n Triangular number of %d is %d , n,t); } tri_num(m) { int f=0; f=0+m;

if(m= =0) return(f); else f=f+tri_num(m-1); return(f); getch(); } Output: Enter a number: 5 Triangular number 5 is 15 Explanation: Here the recursive function method is used. The n actual arguments in the tri_num() is n=5 And in the called function f=0 f=f+tri_num(m-1) = f=5+tri_num(m-1) = f= 5+4 again by recursive function f=f+tri_num(m-1) = f=9+tri_num(m-1) = f= 9+3 again by recursive function f=f+tri_num(m-1) = f=12+tri_num(m-1) = f= 12+2 again by recursive function f=f+tri_num(m-1) = f=14+tri_num(m-1) = f= 14+1 again by recursive function f=f+tri_num(m-1) = f=15+tri_num(m-1) = f= 15+0 If condition matches and the value is returned so the result is Triangular number 5 is 15

72. Write a C program to accept any string up to 15 characters. Display the elements of string with their element numbers in a separate column. #include<stdio.h> #include<conio.h> #include<process.h> void main() {

static char name[15]; int i; clrscr(); printf(Enter your name:); gets(name); printf(Element no. & character\n); for(i=0;i<=15;i++) { if(name[i]= =\0) exit(1); printf(\n %d \t\t%c, i, name[i]); } getch(); } Output: Enter your name:shri 0 1 2 3 s h r i

Explanation: By using the gets unformatted input statement we are getting an input as shri At the end of the string the compiler automatically puts the NULL character if the character is not NULL then the location of the character and the character value is printed. If the character is NULL then the program is terminated by the exit () which is a predefined function present in the process.h 73. Write a C program to print WELCOME by using different formats of initialization of array. #include<stdio.h> #include<conio.h> #include<string.h> void main() { char arr1[9]={W,E,L,,C,O,M,E,\0}; char arr2[9]=WELCOME; char arr3[9]={{ W},{E},{L},{ },{C},{O},{M},{E}};

clrscr(); printf(\narray1=%s:, arr1); printf(\narray2=%s:, arr2); printf(\narray3=%s:, arr3); getch(); } Output: Array1=WELCOME Array2=WELCOME Array3=WELCOME Explanation: The string elements can be initialized by individually by enclosing in single quotes and braces. The curly braces are optional. While initializing individual elements they must be separated by a comma. This is done in the first and the third declaration statements. Also it can be initialized with double quotation marks and this is done in the second statement. 74. Write a C program to count the number of characters in a given string #include<stdio.h> #include<conio.h> #include<string.h> void main() { char text [20]; int len; clrscr(); printf(type text below\n); gets(text); len=strlen(text); printf(Length of string=%d, len); getch(); } Output: Type text below Sam Length of the string=3 Explanation:

We are getting an input string in the text array name by using the predefined function of string .h string length function. This function returns the output as no of characters in the given sting and it is assigned in an integer variable. The value of the integer variable is printed. 75. Write a C program to read a name through the keyboard. Determine the length of the string and find its equivalent ASCII codes. #include<stdio.h> #include<conio.h> #include<string.h> void main() { static char name[20]; int i,l; clrscr(); printf(enter your name:); scanf(%s, name); l=strlen(name); printf(your name is %s & , name); printf(it contains %d characters, l); printf(\n Name & its ASCII Equivalent\n); printf(= = = = = = = = = = = = = = = \n); for(i=0;i<1;i++) printf(\n%c\t\t%d, name[i]name[j]); getche(); } Output: Enter your name: SACHIN Your name is SACHIN & it contains 6 characters Name& its ASCII equivalent =============== S 83 A 65 C 67 H 72 I 73 N 78 Explanation:

In the above program the string is entered and stored in the name character array and string length is found out by strlen(). The for loop is used for displaying the characters and to get the ACII values of the character we should specify the field specifier format as %d and character location. We will get the ASCII value because Character and integer has compatibility. 76. Write a C program to delete all the occurrences of vowels in a given text. Assume that the text length will be of one line. #include<stdio.h> #include<conio.h> void main() { char line[20], line2[80]; int i,j=0; clrscr(); printf(enter text below.\n); gets(line); for(i=0;i<80;i++) { If(line[i]= =a || line[i]= =e ||line[i]= =i ||line[i]= =0||line[i]= =u) continue; else { line2[j]=line[i]; j++; } } Printf(\n Text with Vowels: %s, line); Printf(\n Text without vowels:%s, line2); getch(); } Output: Enter text below. anandamurugan Text with vowels: anandamurugan Text without vowels: nndmrgn Explanation:

We are getting the input a line o f text in the character array line and by using for loop to check the character until the NULL and inside the for loop we use an if statement with different or statement to check the character is an vowel a e i o u or if the character is not in the vowels list then the character is assigned to the line2 array and the I value is incremented for the next iteration this process continue up to the NULL character Then the output is Text with vowels: anandamurugan Text without vowels: nndmrgn 77. Write a C program to to copy contents of one string to another string #include<stdio.h> #include<conio.h> #include<string.h> void main() { Char ori[20], dup[20]; clrscr(); printf(enter your name:); gets(ori); strcpy(dup,ori); printf(original string: %s, ori); printf(\nduplicate string:%s, dup); getch(); } Output: Enter your name: SAM Original string: SAM Duplicate String: SAM Explanation: In the above example we have declared the two arrays namely ori[20] and dup[20]. The function strcpy() copies characters of ori[] to dup[]. The characters are copied one by one from the source string (ori[20] to the destination string dup[20]) 78. Write a C program to convert upper case string to lower case string. #include<stdio.h>

#include<conio.h> #include<string.h> void main() { char upper[15]; clrscr(); printf(\n Enter a string in upper case:); gets(upper); printf(After strlwr();%s, strlwr(upper)); getch(); } Output: Enter a string in upper case: ABCDEFG After strlwr(): abcdefg Explanation: In this program string is entered in capital letters. The string is passed to the function strlwr() . this function converts the string to a lower case. 79. Write a C program to convert lower case string to upper case string. #include<stdio.h> #include<conio.h> #include<string.h> void main() { char upper[15]; clrscr(); printf(\n Enter a string in lower case:); gets(upper); printf(After strupr();%s, strupr(upper)); getch(); } Output: Enter a string in lower case: abcdefg After strupr(): ABCDEFG Explanation:

In this program string is entered in the lowercase The string is passed to the function strupr (). This function converts the string to uppercase 80. Write a C program to enter the string and get its duplicate #include<stdio.h> #include<conio.h> #include<string.h> void main() { Chartext1[20], *text2; clrscr(); printf( Enter text:); gets(text1); text2=strdup(text1); printf(original string=%s\n duplicate string=%s, text1, text2); getch(); } Output: Enter a text: anandamurugan Original string: anandamurugan Duplicate String: anandamurugan Explanation: In the above program the character array text1[] and pointer variable *text2 are declared. String is entered in the character array text1[]. The str dup function copies contents of text1[] array to pointer variable *text . The printf() function displays the contents of the both the variable which are same. 81. Write a C program to find first occurrence of a given character in a string #include<stdio.h> #include<conio.h> #include<string.h> void main() { Char string[30],ch,*chp; clrscr(); printf( Enter text below); gets(string); printf(\n character to find:);

ch=getchar(); chp=strchr(string,ch); if(chp) printf(character %c found in string,ch); else printf(character %c not found in string,ch); getch(); } Output: Enter text below: anandamurugan Character to find: r Character r found in string Explanation: The string is obtained in the character array string. The character to find in the given string is obtained in the character variable ch by using getchar() function which gets a single character as an input. Chp is an pointer variable which collects the address returned by strchr(). The character present means the first occurrence its address with this we can find the given character is present in the string or not. 82. Write a C program to find occurrence of a sub string in the first string. #include<stdio.h> #include<conio.h> #include<string.h> void main() { Char line[30], line2[30],*chp; clrscr(); puts(Enter line1:); gets(line1); puts(Enter line2:); gets(line2); chp=strstr(line1,line2); if(chip) printf( %s string is present in given string, line2); else printf( %s string is not present in given string, line2);

getch(); } Output: Enter line1: anandamurugan is an author Enter line2: author author string is present in given string Explanation: The strstr() function finds the second string in the first string. It returns the pointer location from where the second string starts in the first string. In case the first occurrence of the string is not observed the function returns a NULL character. 83. Write a C program to concatenate two strings without the use of a standard function. #include<stdio.h> #include<conio.h> #include<string.h> void main() { char name[50],fname[15],sname[15],lname[15]; int i,j,k; clrscr(); printf(First name:); gets(fname); printf(second name:); gets(sname); printf(last name:); gets(lname); for(i=0;fname[i]!=\0;i++) name[i]=fname[i]; name[i]= ; for(j=0;sname[j]!=\0;j++) name[i+j+1]=sname[j]; name[i+j+1]= ; for(k=0;lname[k]!=\0;k++) name[i+j+k+2]=lname[k]; name[i+j+k+2]=\0; printf(\n\n);

printf(complete name after concatenation\n); printf(%s, name); getche(); } Output: First name: ANANDA Second name: MURUGAN Last name: SELVARAJ Complete name after concatenation ANANDA MURUGAN SELVARAJ Explanation: The first name and last name and the second name are obtained and stored in the respective character array . To concatenate all those in the name array first the first name is assigned by the for loop and after that a space is appended to the name array and then from that location the second name is appended and then a space and the last name is appended and after the NULL character is appended. The concatenated string is printed. 84. Write a C program to append second string with specified (n) number of characters at the end of the first string. #include<stdio.h> #include<conio.h> #include<string.h> void main() { Char text1[30], text2[10],n; Puts(Enter text1:); gets(text1) puts(Enter text2:); gets(text2); printf(Enter number of characters to add:); gets(n); strcat(text1,); strncat(text1, text2,n); clrscr(); printf(%s\n, text1); getch();

} Output: Enter text1:MAY I Enter text2: COME IN? Enter number of characters to add:4 MAY I COME Explanation: In this program two strings are entered. The number of the second string to append in the first string is also entered. The strncat() function uses three arguments text1[],text2[] and n where n characters of text2[] are appended in the text1[] string. In this program MAY I COME IN and n=4 are entered the strnact() function returns MAY I COME. 85. Write a C program to display reverse of the given string. #include<stdio.h> #include<conio.h> #include<string.h> void main() { Char text[15]; Puts(Enter string); gets(text); puts(Reverse string); puts(strrev(text)); getch(); } Output: Enter string ANANDAMURUGAN Reverse string NAGURUMADNANA Explanation:

The input of the string is obtained in the text[] array. The reverse functions simply reverse the given string. 86. Write a C program to replace a given string with a given symbol. #include<stdio.h> #include<conio.h> #include<string.h> void main() { char text[15]; char symbol; clrscr(); Puts(Enter string); gets(string); puts(Enter symbol for replacement:); scanf(%c, &symbol); printf(Before strset(): %s\n, string); strset(string, symbol); printf(After strset(): %s\n,r, string); getch(); } Output: Enter string: SAM Enter symbol for replacement: A Before strset(): SAM After strset(): AAA Explanation: The strset() function requires two arguments. The first one is the string and another is the character by which the string is to be replaced. Both these arguments are to be entered when the program is executed. The strset(0 function replaces every character of the first string with the given character/symbol. i.e every character of the string is replaced by the entered character A. 87. Write a C program to replace a given string with a given symbol for the given number of arguments. #include<stdio.h> #include<conio.h> #include<string.h>

void main() { char string[15]; char symbol; int n; clrscr(); Puts(Enter string); gets(string); puts(Enter symbol for replacement:); scanf(%c, &symbol); puts(how many string character to be replaced); scanf(%d, &n); printf(Before strset(): %s\n, string); strset(string, symbol); printf(After strset(): %s\n, string); getch(); } Output: Enter string: ANANDAMURUGAN Enter symbol for replacement: + How many string characters to be replaced 4 Before strset(): ANANDAMURUGAN After strset(): ++++DAMURUGAN Explanation: This program is the same as the previous one. The only difference is that instead of replacing all characters of the string only specified numbers of characters are replaced. Here the number entered is 4.Hence only the first four characters are replaced by the given symbol. The replacing process starts from the first character of the string. 88. Write a C program to enter two strings. Indicate after what character the lengths of the two strings have no match. #include<stdio.h> #include<conio.h> #include<string.h> void main() { char stra[10], strb[10]; int length;

clrscr(); Printf(First string:); gets(stra); printf(second string:); gets(strb); length=strspn(stra, strb); printf(After %d characters there is no match\n, length); getch(); } Output: First string: GOOD MORNING Second string: GOOD BYE After 5 characters there is no match Explanation: In this program two strings are entered. Both the strings are passed to the function strspn(). The function searches the second string in the first string. It searches from the first character of the string. If there is a match from the beginning of the string. The function returns the number of characters that are same This function return 0 when the second string mismatches with the first from the beginning. For example the first string is Bombay and the second Trombay on application of this function in the above case the function returns 0 and message displayed will be After 0 characters there is no match. 89. Write a C program to print the given string from the first occurrence of a given character. #include<stdio.h> #include<conio.h> #include<string.h> void main() { char *ptr; char text1[20], text2[2]; clrscr(); printf(Enter string:); gets(text1); printf(Enter character:); gets(text2); ptr=strpbrk (text1, text2); puts(string from given character);

printf(ptr); getch(); } Output: Enter a string: INDIA IS GREAT Enter character :G String from given character: GREAT Explanation: In the above program two strings and character pointer are declared. The strings are entered both the strings are used as arguments with function strpbrk(). This function finds first occurrence of the second string in the first string and returns that address which is assigned to character pointer *ptr. The pointer ptr displays the rest string. Here the first string is INDIA IS GREAT and the second string is G the G occurs at the beginning of the third word. Hence on execution of the program the string from G onwards is displayed. The output is only GREAT. 90. Write a C program to add two numbers through variables and their pointers. #include<stdio.h> #include<conio.h> void main() { int a,b,c,d,*ap,*bp; clrscr(); printf(Enter two numbers:); scanf(%d%d, &a,&b); ap=&a; bp=&b; c=a+b; d=*ap+*bp; printf(\n sum of A &B using variable:%d,c); printf(\n sum of A &B using pointer:%d,d); getch(); } Output: Enter two numbers: 8 4 Sum of a & B using variable:12 Sum of a & B using pointer:12

Explanation: In the above program the sum of two numbers are obtained in two ways. 1. Adding variables a and b directly. 2. Through pointers of a and b i.e ap and bp respectively. The address of a and b are stored in ap nad bp respectively. Thus adding *ap and *bp gives addition of a and b. Here ap and bp means address of a and b and *ap and *bp means their values at memory loctions. Hence the equation used here is d=*ap +*bp and not d=ap+bp 92. Write a C program to find length of a given string including and executing spaces using pointers. #include<stdio.h> #include<conio.h> void main() { Char str[20], *s; int p=0, q=0; clrscr(); printf(Enter String:); gets(str); s=str; while(*s!=\0) { Printf(%c, *s); P++; S++; If(*s= =32) q++; } printf(\n Length of string including spaces: %d, p); printf(\n Length of string excluding spaces: %d, p-q); getch(); } Output: Enter string: POINTER ARE EASY POINTERS ARE EASY Length of string including spaces: 17 Length of string excluding spaces: 15 Explanation:

In the above program the counter variables p and q are increased to count number of characters and spaces found in the string. The ASCII value of space is 32. Thus at the end of the program both the variables are printed. 93. Write a C program to interchange the elements of a character array using pointer. #include<stdio.h> #include<conio.h> void main() { char *names[]={anand,murugan,selvaraj, annammal,shrikarthick, renukadevi}; char*tmp; clrscr(); printf(original: %s%s, names[3], names[4]); tmp=names[3]; names[3]=names[4]; names[4]=temp; printf(\n New : %s%s,names[3],names[4]); getch(); } Output: Original : annammal shrikarthick New :shrikarthick annammal Explanation: In the above program character array *names [] is declared and initialized. Another character pointer *tmp is declared. The destination name that is to replaced is assigned to the variable *tmp. The destination name is replaced with the source name and the source name is replaced with *tmp variable. Thus simple assignments two names are interchanged. 94. Write a C program to copy structure elements from one object to another object #include<stdio.h> #include<conio.h> #include<string.h> void main() { struct disk

{ char co[15]; float type; int price; }; Struct disk d1={SONY,1.44,20}; Struct disk d2,d3; strcpy(d2.co,d1.co); d2.type=d1.type; d2.price=d1.price; d3=d2; clrscr(); printf(\n %s %g %d , d1.co.d1.type, d1.price); printf(\n %s %g %d , d2.co.d2.type, d2.price); printf(\n %s %g %d , d3.co.d3.type, d3.price); getch(); } Output: SONY 1.44 20 SONY 1.44 20 SONY 1.44 20 Explanation: In the above program d1, d2, and d3are objects that are defined based on structure disk. The object d1 is initialized. The content of d1 is copied to d2 and d3 objects. In the first method individual elements of d1 object are copied by using assignment statement. The strcpy() function is used because the first element of the structure is a string. In the second method all the d2 contents are copied to d3.here the statement d3=d2 performs this task. Thus in structure it is possible to copy elements of one object to another object of the same type at one stroke. 95. Write a C program to create the user defined data type hours on int data type and use it in the program #include<stdio.h> #include<conio.h> #define H 60 void main() { typedef int hours;

hours hrs; clrscr(); printf(Enter hours:); scanf(%d, &hrs); printf(\nMinutes: %d,hrs*H); printf(\n Seconds: %d,hrs*H*H); getch(); } Output: Enter hours: 2 Minutes: 120 Seconds: 7200 Explanation: In the above program using typedef we have declared hours as an integer data type. Immediately after the typedef statement hrs is a variable of hours data type which is similar to int. further the program calculates minutes and seconds using hrs variable. 96. Write a C program to store the information of vehicles. Use bit fields to store the status of information #include<stdio.h> #include<conio.h> #define PETROL 1 #define DISEL 2 #define TWO_WH 3 #define FOUR_WH 4 #define OLD 5 #define NEW 6 void main() { struct vehicle { unsigned type:3; unsigned fuel:2; unsigned model:3; }; struct vehicle v; v.type=FOUR_WH; v.fuel=DISEL;

v.model=OLD; clrscr(); printf(\n Type of vehicle: %d,v.type); printf(\n Fuel: %d,v.fuel); printf(\n Model: %d,v.model); getch(); } Output: Type of Vehicle : 4 Fuel :2 Model :5 Seconds: 7200 Explanation: In the above program macros are declared. The information about the vehicle is indicated between integers 1 to 6. the structure vehicle is declared with bit fields. The number of bits required for each member is initialized. As per the program type of the vehicle requires 3 bits, fuel requires 2 bits and the model requires 3 bits. An object v is declared using the object bit fields are initialized with data. The output of the program displays integer value stored in the bit f fields, which can be verified with macro definitions initialized at the beginning of the program. 97. Write a C program to create enumerated data type for 12 months. Display their values in integer constants #include<stdio.h> #include<conio.h> void main() { Enum month{Jan, Feb, mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec} clrscr(); printf(\n Jan=%d, Jan); printf(\n Feb=%d, Feb); printf(\n June=%d, June); printf(\n Dec=%d, Dec); getch(); } Output: Jan=0

Feb=1 June=5 Dec=11 Explanation: In the above program enumerated data type month is declared with 12 months names within two curly braces. The compiler assigns 0 value to the first identifier and 11 to the last identifier. Using printf() statement the constants are displayed for different identifiers. By default the compiler assigns values from 0 onwards. Instead 0 the programmer can initialize his/her own constant to each identifier. The program below illustrates this concept. 98. Write a C program to open a file in read/write mode. Read and Write new information in the file. #include<stdio.h> #include<conio.h> #include<process.h> void main() { FILE *fp; char c= ; clrscr(); fp=fopen(data.txt, r+); if(fp= = NULL) { Printf(cannot open file); exit(1); } Printf(\n Contents read:); While(!feof(fp)) Printf(%c getc(fp)); Printf(write data & to stop press . :); while(c=!) { C=getche(); fputc(c,fp); } getch(); }

Output: Contents read: Help me. Write data & to stop press.: I am in trouble. Explanation: In the above example file is opened in read and write mode(r+). The getc() function reads the contents of the file which is printed through printf() function. The getche() function reads character from the keyboard and the read characters are written to the file using fputc() function. 99. Write a C program to open a file for read/write operation in binary mode. Read and Write new information in the file. #include<stdio.h> #include<conio.h> #include<process.h> void main() { FILE *fp; char c= ; clrscr(); fp=fopen(data.dat, wb); if(fp= = NULL) { Printf(cannot open file); exit(1); } Printf(\n Contents read:); While(!feof(fp)) Printf(%c getc(fp)); Printf(write data & to stop press . :); while(c=!) { C=getche(); fputc(c,fp); } fclose(fp); fp=fopen(data.dat, rb); printf(\n contents read:); while(!feof(fp)) printf(%c, getc(fp)); getch(); }

Output: Contents read: Help me. Write data & to stop press.: I am in trouble. Explanation: The program is the same as the one explained earlier and the only difference is that the file opening mode is binary. 100. Write a C program to display number of arguments and their names. #include<stdio.h> #include<conio.h> main(int argc, char *argv[]) { Int x; clrscr(); Printf(\n Total number of arguments are %d \n , argc); for(x=0; x<argc; x++) Printf(%s\t, argv[x]); getch(); return 0; } Output: Total numbers of arguments are 4 C:\TC\C.EXE A B C Explanation: To execute this program one should create its executable file and run it from the command prompt with required arguments. The above program is executed using the following steps. a. compile the program b. makes its exe file (executable file) c. switch to the command prompt(C:\TC>) d. makes sure that the exe file is available in the current directory e. type following bold line C:\TC c.exe HELP ME In the above example c.exe is an executable file HELP ME is taken as an argument. The total number of arguments including the program file name are three c.exe, HELP and ME are three arguments

You might also like