c programs

139
Introduction to C Programming

Upload: sriram

Post on 28-Nov-2014

214 views

Category:

Documents


4 download

DESCRIPTION

great language.....study well dudes....keep in touch....enjoy the c language....

TRANSCRIPT

Page 1: C Programs

Introduction to

C Programming

C CONCEPTS

Page 2: C Programs

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 sectionGlobal declaration sectionMain(){Declaration partExecutable 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:

Page 3: C Programs

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:

Letters Digits White SpacesCapital A to Z All decimal digits 0 to

9Blank space

Small a to z Horizontal tabVertical tabNew lineForm feed

Page 4: C Programs

Special Characters:

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

1.5 Delimiters:

Delimiters Use: Colon Useful for label; Semicolon Terminates the statement( ) Parenthesis Used in expression and

function[ ] Square Bracket Used for array declaration{ } Curly Brace Scope of the statement# hash Preprocessor directive, Comma Variable separator

1.6 C Keywords:

Auto Double Int StructBreak Else Long SwitchCase Enum Register TypedefChar Extern Return UnionConst Float Short UnsignedContinue For Signed VoidDefault Goto Sizeof Volatile

Page 5: C Programs

Do If Static while

1.7 Identifiers:

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 constantsThese 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 constantsIt is also known as floating point constants.

Eg: 2.5, 5.342

2. Character constants:

- Single charcter constantsA 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 constantsString constants are sequence of charcters enclosed within double quote marks.

Page 6: C Programs

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 Size (Bytes)

Range Format Specifiers

Char 1 -128 to 127 %cUnsigned char

1 0 to 255 %c

Short or int 2 -32,768 to 32, 767 %i or %dUnsigned int 2 0 to 655355 %uFloat 4 3.4e-38 to +3.4e +38 %f or %gLong 4 -2147483648 to

2147483647%ld

Unsigned long

4 0 to 4294967295 %lu

Double 8 1.7e-308 to 1.7e+308 %lfLong double 10 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 Symbolic representation

Arithmetic operators +,-,*,/,%Relational operators >,<,==,>=,<=,!=Logical operators &&, ||, !=Increment and decrement operator

++ and --

Assignment operator =Bitwise operator &,|,^,>>,<<, ~Comma operator ,Conditional operator ?:

Page 7: C Programs

1.12 Input and Output: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 OutputScanf() printf()

Unformatted functions:

- The unformatted input/output functions only work with the charcter data type

Input Outputgetch() putch()getche() putchar()getchar() put()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. If statement2. If-else statement3. Nested if-else statement4. Break statement5. Continue statement6. goto statement7. switch() statement8. nested switch ()case9. switch() case and nested if

Statement Syntax

Page 8: C Programs

If statement if(condition)Statement;

If-else statement If (condition){Statement 1;Statement 2;}else{Statement 3;Statement 4;}

Nested if-else statement

If (condition){Statement 1;Statement 2;}else if (condition){Statement 3;Statement 4;}else{Statement 5;Statement 6;}

Break statement Break;Continue statement Continue;Goto statement goto label;Switch() statement Switch (variable or expression)

{Case constant A:Statement;break;

Case constant B:Statement;break;

Page 9: C Programs

default:Statement;}

1.14 Loop Control statements:

Loop is a block of statements which are repeatedly executed for certain number of times.

Types:

1. for loop2. nested for loops3. while loop4. do while loop5. do-while statement with while loop

Statement SyntaxFor loop for(initialize counter; test condition; re-

evaluation parameter{Statement;Statement;}

Nested for loop for(initialize counter; test condition; re-evaluation parameter){Statement;Statement;for(initialize counter; test condition; re-evaluation parameter)Statement;Statement;}}

While loop While (test condition){Body of the loop}

Page 10: C Programs

Do while loopdo{Statement;}While(condition);

Do-while with while loop

do while(condition){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 array2. Two dimensional arrays3. Three or multi dimensional arrays

Operations:

1. Insertion2. Deletion3. Searching4. Sorting5. 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():

Page 11: C Programs

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 DescriptionStrlen() Determines the length of a stringStrcpy() Copies a string from source to destinationStrncpy() Copies characters of a string to another string up to the

specified lengthStricmp() Compares characters of two stringsStrcmp() Compares characters of two strings up to the specified

lengthStrncmp() Compares characters of two strings up to the specified

lengthStrnicmp() Compares characters of two strings up to the specified

lengthStrlwr() Converts uppercase characters of a string to lower caseStrupr() Converts lowercase characters of a string to upper caseStrdup() Duplicates a stringStrchr() Determines the first occurrence of a given character in a

stringStrrchr() Determines the last occurrence of a given character in a

stringStrstr() Determines the first occurrence of a given string in

another stringStrcat() Appends source string to destination stringStrrev() Reverses all characters of a stringStrset() Sets all characters of a string with a given argument or

symbolStrspn() Finds up to what length two strings are identicalStrpbrk() Searches the first occurrence of the character in a given

string and then displays the string starting from that character

Page 12: C Programs

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.

Page 13: C Programs

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.

Page 14: C Programs

File types:

1. Sequential file 2. Random access file

Steps for file operations:

Opening a file Reading or writing a file Closing a file

File functions:

Function Operationfopen() Creates a new file for read/write operationfclose() Closes a file associated with file pointercloseall() Closes all opened files with fopen()fgetc() Reads the character from current pointer

position and advances the pointer to next character

getc() Same as fgetc()fprintf() Writes all types of data values to the filefscanf() Reads all types of data values from a fileputc() Writes character one by one to a filefputc() Same as putc()gets() Reads string from the fileputs() Writes string to the fileputw() Writes an integer to the filegetw() Reads an integer from the filefread() Reads structured data written by fwrite()

functionfwrite() Writes block of structured data to the filefseek() Sets the pointer position anywhere in the filefeof() Detects the end of the fileferror() Reports error occurred while read/write

operationsperror() Prints compilers error messages along with

user-defined messagesftell() Returns the current pointer positionrewind() Sets the record pointer at the beginning of the

fileunlink() Removes the specified file from the diskrename() Changes the name of the file

Page 15: C Programs

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:

Page 16: C Programs

1. wb(write) This mode opens a binary file in write mode2. rb(read) This mode opens a binary file in read mode3. ab(append) This mode opens a binary file in append mode, i.e.,

data can be added at the end of file.

4. r+b(read+write) This mode opens a pre-existing file in read and write mode

5. w+b(read+write) This mode creates a new file in read and write mode

6. a+b(append+write) This mode opens a file in append mode, i.e. data can be written at the end of the file

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

Page 17: 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);elseprintf(“c is greatest %d”,c);getch();}

Output:enter the three numbers908967a 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>

Page 18: C Programs

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 value3area=28.26circumference=18.84

Explanation:

r=3a=3.14*3*3b=2*3.14*3area =28.26circumference=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();

Page 19: C Programs

}

Output:enter the three real numbers:345average=4.000000Explanation:Here 3,4,5 are made in float format asfloat a=3.000000 b=4.000000 c=5.000000x=(3.000000+4.000000+5.00000)/3x=12.000000/3x=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:54sum=9Explanation:a=5,b=4c=a+b + operator performs addition on both the operands.c=5+4c=9

Page 20: C Programs

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:8minutes=480.000000Explanation:

Hour=8.000000M=8.0000000*60Minutes=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();

Page 21: C Programs

}

Output:enter the p,n,r value:3000023simple interest=1800.000000

Explanation:P=30000,n=2,r=3s=(p*n*r)/100s=(30000.000000*2.000000*3.0000)/100s=180000.000000/100s=1800.0000007. 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:37fahrenheit value=98.599998

Explanation:Celsius=37.000000f=((c*9)/5)+32f=((37.000000*9)/5)+32f=((333.000000)/5)+32;f=66.599998+32f=98.599998

Page 22: C Programs

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:68area=48.000000perimeter=28.000000

Explanation:L=6.0000000,b=8.000000a=l*b 6.0000000*8.000000=48.000000p=2*(l+b) 2*(6.000000+8.0000000) 2*(14.000000)area=48.000000perimeter=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;

Page 23: C Programs

printf(“area=%f\n perimeter=%f\n”,a,p);getch();}

Output:enter the s value:5area=25.000000perimeter=20.000000

Explanation:S=5.000000a=s*s 5.000000*5.000000=25.000000p=4*s 4*.5.000000 =20.000000area=25.000000perimeter=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:8798787689

Page 24: C Programs

sum=428percentage=85.000000

Explanation:a=87,b=98,c=78,d=76,e=89s=a+b+c+d+e 87+98+78+76+89 = 428x=s/5 =428/5.0 (integer by float results in float) =85.000000

sum=428percentage=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:98a=8b=9Explanation:a=9,b=8

a=a+b a=8+9 =17b=a-b b=17-8=9a=a-b a=17-9=8

Page 25: C Programs

a=8b=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:98a=8b=9

Explanation:a=9,b=8c=a c=9 c is assigned with a valuea=b a=8 a is assigned with b value then a value is changed with bb=c b= 9 b is assigned with c value then b value is changed with ca=8b=9

13. Write a C program to check the given year is Leap Year or not

#include<stdio.h>

Page 26: C Programs

#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:1998not 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 yearif 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”);

Page 27: C Programs

elseprintf(“not eligible”);getch();}

Output:enter the age:21eligible to voteExplanation: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”);elseprintf(“less than 100”);getch();}Output:enter the number366greater than 100

Explanation:A=366

Page 28: C Programs

(366>=100) here the result of the relational expression is trueso the true part of the if branching or decision statement is carried out so the result isgreater 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”);elseprintf(“b is biggest”);getch();}

Output:enter the two numbers:67b 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);

Page 29: C Programs

if(a%2==0)printf(“even number”);elseprintf(“odd number”);getch();}

Output:enter the number9odd 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.6celsius value=37.00000Explanation:Fareheit value=98.600000

Page 30: C Programs

c=((f-32)*5)/9c=((98.60000-32)*5)/9c=((66.599998*5)/9c=333.00000/9c=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 numbers63a is greaterExplanation:a=6, b=36>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();

Page 31: C Programs

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,c283the roots are real and distinct-6.418861 -9.581139Explanation:a=2,b=8,c=3d=8*8-4*2*3d=40here 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

Page 32: C Programs

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);

Page 33: C Programs

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.add2.subtract3.multiply4.division5.remainderenter your choice2enter the values of a and b74the answer is 3Explanation:Ch=2So the case constant value 2 of the switch is alone brancheda=7,b=4 c=a-b c=7-4c=7the answer is 3

22. Write a C program to covert Decimal to Binary Conversion

#include<stdio.h>#include<conio.h>

Page 34: C Programs

#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 number8the binary value is 1000Explanation:No=8, i=0while(8>0)r=8%2 r=0sum=0+pow(10, 0)* 0n0=8/2 n0=4again 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 loopthen 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”);

Page 35: C Programs

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 n3the number is 1 and its square is 1the number is 2 and its square is 4the number is 3 and its square is 9Explanation:I=1,n=3for(i=1;1<=3;)condition is true so the body of the loop is executedin 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();

Page 36: C Programs

}

Output:enter the value of n5sum=15average=3Explanation:N=5,sum=0, i=1for(i=1;1<=5;i++)sum=0+1sum=1+2sum=3+3sum=6+4sum=10+5sum=15this is calculated still the condition is trueavg=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 n44321Explanation:

Page 37: C Programs

p=4, this is initialization of the for loopfor(;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 3so 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 n10sum=55Explanation:N=10,sum=0For(i=1;1<=10;i++)Sum=0+1, sum=1+2, sum=3+2, sum=5+3…………sum=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”);

Page 38: C Programs

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 terms40112Explanation:A=0,b=1,c=0n=4a and b value is printed as 0 and 1for(i=3;3<=4;i++)c=a+b =0+1 c=1 in body of the for loopa=b a=1b=c b=1so 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);

Page 39: C Programs

getch();}

Output:enter the number5the factorial of given number is 120Explanation:Fact=1N=5for(i=5;5>=1;5--)fact=fact*ifact=1*5,fact=5*4,fact=20*3 fact=60*2 fact=120*1the 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 n5sum=15Explanation:

Page 40: C Programs

i=1,sum=0 n=5while(1<=5)sum=0+1i=2sum=1+2i=3sum=3+3i=4sum=6+4i=5sum=10+5i=6condition 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);elseprintf(“rupees=%f”,r*c);getch();}

Output:enter the readings140rupees=280.000000Explanation:a=2.5,b=3.5,c=1.5r=140.000000the condition matches in else if (140.00000>=100 && 140.000000<200)

Page 41: C Programs

140.00000*2280.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 499Explanation: Here we used the nested for loopI=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

Page 42: C Programs

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”);elseprintf(“the number is not armstrong”);getch();}

Output:

enter the number153the number is Armstrong

Explanation:Sum=0

Page 43: C Programs

N=153While(153!=0)r=153%10 r=3Sum=0+pow(3,3) sum=0+27n=153/10 n=1515!=0r=15%10 r=5sum=27+pow(5,3) sum=27+125n=15/10 n=11!=0r=1%10 r=1sum=152+pow(1,3)= 152+1n=1/10condition 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 notso 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”);elseprintf(“the number is not palindrome”);getch();}

Page 44: C Programs

Output:enter the number323the number is palindromeExplanation:N=323r=323%10 r=3,sum=0*10+r,sum=3, n=323/10,n=32r=32%10 r=2 sum=30+2 sum=32 n=32/10 n=3r=3%10 r=3 sum=320+3 n=3/10 n=0if 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 array4638

Page 45: C Programs

5the maximum value is 8Explanation:Size is 46,3,8,5max=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 loopif(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++)

Page 46: C Programs

{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”);}}elseprintf(“the matrix are not multiplied”);getch();}

Output:enter the no.of rows and columns for 1st matrix:33enter the values of 1st matrix:111111111enter the rows and columns for 2nd matrix:33enter the values of 2nd matrix:

Page 47: C Programs

111111111resultant matrix is:3 3 3 3 3 3 3 3 3Explanation:r1=3,c1=3,r2=3,c2=3By 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 loopThen 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(“ “);}

Page 48: C Programs

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:

Page 49: C Programs

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”);elseprintf(“element not found”);getch();}

Output:enter the elements of array:12345enter the elements to search3element foundExplanation:Elements are x[5]={1, 2, 3, 4, 5}

Page 50: C Programs

This is obtained by the scanf statement which is inside the forloopN=3X[0],x[1],x[2],x[3],x[4]1==3,1==2,1==3condition 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 elements4enter elements123

Page 51: C Programs

5enter the element and position to be inserted441 2 3 4 5Explanation: Array size 4 elements are 1 2 3 4Elements are num[5]={1, 2, 3, 4, 5}This is obtained by the scanf statement which is inside the for loopElement 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

Page 52: C Programs

3enter elements123enter the position to delete 21 3 Explanation:Array size 3 num[]={1,2,3}This is obtained by the scanf statement which is inside the for loopPosition 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];

Page 53: C Programs

a[j]=t;}}}printf(“Sorted elements”);for(j=0;j<n;j++){Printf(“%d\n”, a[j]);}getch();}

Output:enter the number of elements35383 5 8Explanation:In the above program the n value =3Three values are obtained and stored in the num array. 5 3 8By 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++)

Page 54: C Programs

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++];elsez[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:5 6 7 8array z:1 5 2 6 3 7 4 8Explanation:By using a for loop to print the first array elementsBy using another for loop to print the second array elementsThe 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(){

Page 55: C Programs

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:3enter str[1] rajaenter str[2] vigneshenter str[3] adhithe sorted strings in ascending order isadhirajavignesh

Page 56: C Programs

Explanation:N=3By 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);

Page 57: C Programs

count++;t1=t2;t2=t3;fibo(t1,t2);}}output:enter the number of terms50 1 1 2 3Explanation:First the t1 and t2 values are printed. t1=0 t2=1Then 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+1And the next term is printed and the count value is incremented and the t1 and t2 values are assigned as t1=t2 and t2=t3T1=1 and t2=1Again 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);

Page 58: C Programs

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 56pass by value before function call a=5 b=6with swapval x=6 y=5after function swapval a=5 b=6pass by referencebefore function call a=5 b=6with swapref x=6 y=5after 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 functionIn 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.

Page 59: C Programs

So the result is pass by value before function call a=5 b=6with swapval x=6 y=5after function swapval a=5 b=6A=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 functionIn 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 argumentsSo the result is pass by referencebefore function call a=5 b=6with swapref x=6 y=5after 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);

Page 60: C Programs

temp[cnt]=’\0’;strcat(temp,str+cnt+strlen(srt1));strcpy(str1,temp);puts(str);}getch();}

Output:enter the line of text... i love indiaenter the string to be replaced..indiaenter the replacing string...my parentsthe replaced line of texti love my parentsExplanation:

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 obtainedIn while conditionBy 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);

Page 61: C Programs

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..33enter the elementsenter m[1][1]=1enter m[1][2]=2

Page 62: C Programs

enter m[1][3]=3enter m[2][1]=4enter m[2][2]=5enter m[2][3]=6enter m[3][1]=7enter m[3][2]=8enter m[3][3]=9before transpose 1 2 34 5 67 8 9after transpose 1 4 72 5 83 6 9Explanation: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);

Page 63: C Programs

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 values5enter the elements

12345mean=3.000000sd=1.414200Explanation:

Page 64: C Programs

N=5, the five values is obtained and stored in the array aIn 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=1break;}}if flag==0printf(“it is palindrome”);elseprintf(“it is not a palindrome”);getch();}

Page 65: C Programs

Output:enter a string:malayalamit is palindromeExplanation: 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++)

Page 66: C Programs

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”);elsestrcpy(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]);}

Page 67: C Programs

printf (“\n total: %d”, st[i].total);printf(“\n average:%f”,st[i].avg);printf(“\n grade:%s”,st[i].grade);}getch();}

Output:enter2enter the roll no...105name...sheik rajaenter the three marks...898778enter roll no...110name...sriramenter the three marks...989695

the student details in rankwise

roll no:105name:sheik rajamarks in three subjects898778total:254average:84.666664grade:distinction

roll no:110name:srirammarks in three subjects989695total:289average:96.3333336

Page 68: C Programs

grade:distinction

Explanation:Structure stud is createdBy using the structure variable st.structure member the values are obtained for 2 students of n valueThe 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): 8The right shifted data is = 2Explanation:X=8X>>=2, x=x>>200001000 the last two bits is shifted in right side to get 00000010The 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(){

Page 69: C Programs

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): 2The left shifted data is = 16Explanation:X=2 the binary value is 00000010 the three bits shifted in left side to get 00010000The 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 4The answer after AND operation is (c)=0Explanation:00001000 binary value of 800000100 binary value of 4 by using AND truth table to and both 8 & 4 to get result as zero

Page 70: C Programs

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 4The answer after OR operation is (c)= 12Explanation:

00001000 binary value of 800000100 binary value of 4 by using OR truth table to and both 8 | 4 to get result as 1200001100 =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();}

Page 71: C Programs

Output:Read the integer from keyboard (a&b): 8 2The answer after XOR operation is (c)= 10Explanation:00001000 binary value of 800000010 binary value of 4 by using XOR truth table to and both 8 ^ 4 to get result as 1000001010

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’: 255A=-1Enter value of ‘A’: 256A=0Explanation: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(){

Page 72: C Programs

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:9Number entered is less than 10Explanation:

V=9If(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 5Two numbers are equalExplanation:m=5 and n=5if(5-5==0)

Page 73: C Programs

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);}elsePrintf(“\n Invalid number”);}

Output:Enter a number: 25Square =625Explanation:S=25S%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:”);

Page 74: C Programs

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: 31Conversion of decimal to Hexa decimal number1FExplanation:X=31

Page 75: C Programs

z=x%16 31%16 =15x=x/16 31/16 =1

gotoxy function makes the cursor position to go in the place of FIn switch the case constant value 15 is matched and it is printed as FAnd in the net iteration of the for loop the value is 1

z=x%16 1%16 =1x=x/16 1/16 =0gotoxy function makes the cursor position to go one decrement to the place of FIn switch the case constant value nothing is matched so the default is printed with the Z value So the output is 1F61. 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]){case’1’:a++;break;case’0’:z++;break;

Page 76: C Programs

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 222Total spaces :1Total 1s :3Total 0s :2Others :5String length :11Explanation: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);

Page 77: C Programs

getch();}

Output:Number: 1 it’s square: 1Number: 2 it’s square: 4Number: 3 it’s square: 9Number: 4 it’s square: 16Number: 5 it’s square: 25Explanation: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:2Value of x= 1.2500Value of y=1.12500Explanation: Here the value of n=2

Page 78: C Programs

Until the n value the for loop runs twice as for this input is concernsIn order to get the x=x+(1/pow)i,2)) =x=0+(1/pow)1,2=1/1y=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/4y=y+(1/pow(i,3)) =y=1+(1/pow)2,3=1/8So the result is Value of x= 1.2500Value 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 5Multiplication of 5 *5 : 25Explanation 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 variableD=0-5D=5+5 d=10 (-*-=+)D=10+5 d=15D=15+5 d=20D=20+5 d=2565. Write a C program to perform multiplication of two integers by using repetitive addition.

Page 79: C Programs

#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 4Multiplication of 8 *4 : 32Explanation

A=8 b=4D=d+a =0+8 D=8 in the first iteration of the for loop1==4 condition not matchesc variable is incrementedd=8+8 d=162==4 condition not matchesc variable is incrementedd=16 +8=243==4 condition not matchesc variable is incrementedd=24 +8=324==4 conation matchescontrol goes to stop label by the unconditional branching goto statementand the result is printed Multiplication of 8 *4 : 3266. Write a C program to simulate a digital clock.#include<stdio.h>

Page 80: C Programs

#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 ss1 1 1Explanation 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>

Page 81: C Programs

#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:4687Sum of digits till a single digit4687257 Explanation:N=4687S=s+n%10 =0+4687%10 s =0+7n=n/10 4687/10 n=468here the if condition is not matches so the next iteration of the for loop isN=468S=s+n%10 =7+468%10 s =7+8 =15n=n/10 468/10 n=46here the if condition is not matches so the next iteration of the for loop isN=46S=s+n%10 =15+46%10 s =15+6 =21n=n/10 46/10 n=4

Page 82: C Programs

here the if condition is not matches so the next iteration of the for loop isN=4S=s+n%10 =21+4%10 s =21+4 =25n=n/10 4/10 n=0Here the is condition matches so the N=25 and s=0 so again the loop repeats N=25S=s+n%10 =0+25%10 s =0+5 =5n=n/10 25/10 n=2here the if condition is not matches so the next iteration of the for loop isN=2S=s+n%10 =5+2%10 s =5+2 =7n=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.12 13 2 14 3 2 1

4 3 2 13 2 12 11

#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);}

Page 83: C Programs

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: 412 13 2 14 3 2 1

4 3 2 13 2 12 11Explanation: 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++)

Page 84: C Programs

{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 10121012

3 210123Explanation: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--;

Page 85: C Programs

}return (NULL);getch();}

Output:Num[6]=18Num[5]=17Num[4]=16Num[3]=15Num[3]=14Num[1]=13Num[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;

Page 86: C Programs

if(m= =0)return(f);elsef=f+tri_num(m-1);return(f);getch();}

Output:Enter a number: 5Triangular number 5 is 15Explanation: Here the recursive function method is used. The n actual arguments in the tri_num() is n=5And in the called function f=0f=f+tri_num(m-1) = f=5+tri_num(m-1) = f= 5+4again by recursive functionf=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(){

Page 87: C Programs

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 s1 h2 r3 i

Explanation:By using the gets unformatted input statement we are getting an input as shriAt 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’}};

Page 88: C Programs

clrscr();printf(“\narray1=%s:”, arr1);printf(“\narray2=%s:”, arr2);printf(“\narray3=%s:”, arr3);getch();}

Output:Array1=WELCOMEArray2=WELCOMEArray3=WELCOMEExplanation: 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 belowSamLength of the string=3Explanation:

Page 89: C Programs

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: SACHINYour name is SACHIN & it contains 6 characters

Name& its ASCII equivalent= = = = = = = = = = = = = = =S 83A 65C 67H 72I 73N 78

Explanation:

Page 90: C Programs

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.anandamuruganText with vowels: anandamuruganText without vowels: nndmrgnExplanation:

Page 91: C Programs

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: anandamuruganText 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: SAMOriginal string: SAMDuplicate String: SAMExplanation:

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>

Page 92: C Programs

#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: ABCDEFGAfter 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: abcdefgAfter strupr(): ABCDEFGExplanation:

Page 93: C Programs

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 it’s 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: anandamuruganOriginal string: anandamuruganDuplicate String: anandamuruganExplanation:

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:”);

Page 94: C Programs

ch=getchar();chp=strchr(string,ch);if(chp)printf(“character %c found in string”,ch);elseprintf(“character %c not found in string”,ch);getch();}

Output:Enter text below: anandamuruganCharacter to find: rCharacter r found in stringExplanation:

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);elseprintf(“ ’%s’ string is not present in given string”, line2);

Page 95: C Programs

getch();}

Output:Enter line1: anandamurugan is an authorEnter 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”);

Page 96: C Programs

printf(“complete name after concatenation\n”);printf(“%s”, name);getche();}

Output:First name: ANANDASecond name: MURUGANLast name: SELVARAJ

Complete name after concatenation

ANANDA MURUGAN SELVARAJExplanation: 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();

Page 97: C Programs

}

Output:Enter text1:MAY IEnter text2: COME IN?Enter number of characters to add:4MAY 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:

Page 98: C Programs

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: SAMEnter symbol for replacement: ABefore strset(): SAMAfter 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>

Page 99: C Programs

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: ANANDAMURUGANEnter symbol for replacement: +How many string characters to be replaced 4Before strset(): ANANDAMURUGANAfter 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;

Page 100: C Programs

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 MORNINGSecond string: GOOD BYEAfter 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”);

Page 101: C Programs

printf(ptr);getch();}

Output:Enter a string: INDIA IS GREATEnter character :GString from given character: GREATExplanation: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 4Sum of a & B using variable:12Sum of a & B using pointer:12

Page 102: C Programs

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 EASYPOINTERS ARE EASY

Length of string including spaces: 17Length of string excluding spaces: 15Explanation:

Page 103: C Programs

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 shrikarthickNew :shrikarthick annammalExplanation:

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

Page 104: C Programs

{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 20SONY 1.44 20SONY 1.44 20Explanation:

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 60void main(){typedef int hours;

Page 105: C Programs

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: 2Minutes: 120Seconds: 7200Explanation:

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 6void main(){struct vehicle{unsigned type:3;unsigned fuel:2;unsigned model:3;};struct vehicle v;v.type=FOUR_WH;v.fuel=DISEL;

Page 106: C Programs

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 : 4Fuel : 2Model : 5Seconds: 7200Explanation: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

Page 107: C Programs

Feb=1June=5Dec=11Explanation:

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();}

Page 108: C Programs

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();}

Page 109: C Programs

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 4C:\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 programb. 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 directorye. type following bold line

C:\TC c.exe HELP MEIn 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

Page 110: C Programs