C language for Semester Exams for Engineers

71
LANGUAGE Language: A language is a communication media between two parties. Programming languages: A programming language is a language used in writing programs to direct processing steps to be carried out by a computer. Programming languages are classified into 3 categories 1. Low level language (or) Machine Language (or) Binary language 2. Middle level language (or) Assembly language 3. High level language Machine level Language Although computers can be programmed to understand many different computer languages, there is only one language understood by the computer without using a translation program. This language is called the machine language or the machine code of the computer. Machine code is the fundamental language of a computer and is normally written as strings of binary 1’s and 0’s. The circuitry of a computer is wired in such a way that it immediately recognizes the machine language and converts it into the electrical signals needed to run the computer. Programs written in machine language can be executed very fast by the computer. This is mainly because the CPU directly understands machine instructions and no translation of the program is required. Advantages:- If we know this language we can directly interact with the system, with out depending on any other applications. Assembly language One of the first steps in improving the program preparation process was to substitute letter symbols-mnemonics for the numeric operation codes of machine language. A mnemonic (or memory aid) is any kind of mental trick we use to help us remember. Mnemonics come in various shapes and sizes, all of them useful in their own way. All computers have the power of handling letters as well as numbers. Hence, a computer can be taught to recognize certain combination of letters or numbers. In this way, the computer can be trained to translate a program written with symbols instead of numbers into the computer’s own machine language. Then we can write program for the computer using symbols instead of numbers, and have the computer do its own translating. This makes it easier for the programmer, because he can use letters, symbols, and mnemonics instead of numbers for writing his programs.

Transcript of C language for Semester Exams for Engineers

Page 1: C language for Semester Exams for Engineers

LANGUAGE

Language: A language is a communication media between two parties.

Programming languages: A programming language is a language used in writing programs to direct processing steps to be carried out by a computer.Programming languages are classified into 3 categories1. Low level language (or) Machine Language (or) Binary language2. Middle level language (or) Assembly language3. High level language

Machine level Language

Although computers can be programmed to understand many different computer languages, there is only one language understood by the computer without using a translation program. This language is called the machine language or the machine code of the computer. Machine code is the fundamental language of a computer and is normally written as strings of binary 1’s and 0’s. The circuitry of a computer is wired in such a way that it immediately recognizes the machine language and converts it into the electrical signals needed to run the computer.

Programs written in machine language can be executed very fast by the computer. This is mainly because the CPU directly understands machine instructions and no translation of the program is required.

Advantages:- If we know this language we can directly interact with the system, with out depending on any other applications.

Assembly language

One of the first steps in improving the program preparation process was to substitute letter symbols-mnemonics for the numeric operation codes of machine language. A mnemonic (or memory aid) is any kind of mental trick we use to help us remember. Mnemonics come in various shapes and sizes, all of them useful in their own way. All computers have the power of handling letters as well as numbers. Hence, a computer can be taught to recognize certain combination of letters or numbers. In this way, the computer can be trained to translate a program written with symbols instead of numbers into the computer’s own machine language. Then we can write program for the computer using symbols instead of numbers, and have the computer do its own translating. This makes it easier for the programmer, because he can use letters, symbols, and mnemonics instead of numbers for writing his programs.

Page 2: C language for Semester Exams for Engineers

The language, which substitutes letters and symbols for the numbers in the machine language program, is called an assembly language or symbolic language. The translator program that translates an assembly code into the computer’s machine code is called assembler. The assembler is a system program, which is supplied by the computer manufacturer.Advantages of Assembly language:1. Easier to understand and use2. Easy to locate and correct errors3. Easier to modify4. No worry about addresses5. Easily re locatable.

High level language

While writing programs in any of the above languages, a programmer has to remember all the operation codes of the computer and now in detail what each code does and how it affects the various registers of the computers. High-level languages, instead of being machine based, are oriented more towards the problem to be solved. These languages enable the programmer to write instructions using English words and familiar mathematical symbols. So it becomes easier for his to concentrate on the logic of his problem rather than getting involved in programming details. Every instruction, which the programmer writes in a high-level language, is translated into many machine language instructions. This is one-to-many translation and not one-to-one as in the case of assembly language.Compiler: A compiler is software that translates a program from high level language to machine language.Interpreter: An interpreter is software that translates a program from high level language to machine language.

Differences between Compiler and interpreterCompiler Interpreter

1. Compiler converts all statements at a time, if errors are there, it displays all errors as a list.

1. Interpreter converts line by line, at the time of interpreting any error is there, it displays that error.

2. After Compiling the whole program, if the program is error free then it will execute the program.

2. After interpreting the first line, if it is error free then it will execute that line.

3. After Compilation, it creates an executable file, using that executable file we can run the program any number of times.

3. It does not create any executable file, every time we need to interpret the program.

4. It is fast. 4. It is slow.

Page 3: C language for Semester Exams for Engineers

What is C?C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritche.

Features of C1. Portability or machine independent2. Sound and versatile language3. Fast program execution.4. An extendible language.5. Tends to be a structured language.

Historical developments of CYear Language Developed by Remarks1960 ALGOL International committee Too general, too

abstract1963 CPL Cambridge University Hard to learn, difficult

to implement1967 BCPL Martin Richards at

Cambridge universityCould deal with only specific problems

1970 B Ken Thompson at AT & T Could deal with only specific problems

1972 C Dennis Ritche at AT & T Lost generality of BCPL and B restored

Character set of the C language

This indicates group of characters which are useful to write the programming statements. It contains 3 parts.

Alphabets: C language supports upper case letters (A to Z), lower case letters from (a to z). But both are different. C is a case sensitive language.

Numeric digits: C language contains the numeric digits from 0 to 9. Special Characters: The characters other than alphabets and numeric digits

are called as special characters.

Special Character Name+ Plus- Minus* Asterisk/ Slash/ forward slash% Modulator (percentage)

Page 4: C language for Semester Exams for Engineers

< Less than> Greater than= Equal to. Full stop, Comma; Semi colon: Colon‘ Single quotation“ Double quotation? Question mark$ Dollar! Exclamatory| Pipe or Bar^ Cap& Ampersand( Left parenthesis) Right parenthesis[ Open square bracket] Close square bracket{ Open brace} Close brace\ Back slash or Reverse slash

White space charactersThese are also called as escape sequence characters. These are the controlling characters. These characters should start with \ , then followed by a single character.

White space character

name

Usage

\a Bell sound or beep sound\n New line\t Tab space\b Back space\r Carriage return\’ Single quotation\” Double quotation\\ For back slash\? For question mark

Identifiers: It identifies a memory location. In order to identify any value identifier is used.

Constants:- It is a quantity which does not change its value during the program execution. Constants are 4 types.

1. Integer Constants: These are the numbers without decimal point or exponent.

Page 5: C language for Semester Exams for Engineers

Ex: int a=10;

2. Float constants: These are the numbers with decimal point or exponent.Ex: float pie=3.14;

3. Single Character Constants: It is any one of the single character enclosed in single quotation.

Ex: char ch=’a’;

char section=’b’;

4. String constants: Group of characters enclosed with in double quotations.Ex: char name[20]= “Chandra”;char nation[10]= “India”;

Variables: It is a value that changes its value during program execution. Variables are 4 types.

1. Integer variables2. Float variables3. Single character variables4. String variables.

Rules to write variable names:1. A variable name contains maximum of 30 characters.2. A variable name includes alphabets and numbers, but it must start with an

alphabet.3. It cannot accept any special characters, blank spaces except under score( _ ).4. It should not be a reserved word.

key words (or) Reserved words

Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names. They are

auto break case char constdefault do double else continueenum extern float for gotoif int long register returnshort signed sizeof static structswitch typedof union unsigned voidvolatile while

Data types

Data type Range Bytes Formatsigned char -128 to +127 1 %cunsigned char 0 to 255 1 %cshort signed int -32,768 to +32,767 2 %d

Page 6: C language for Semester Exams for Engineers

short unsigned int 0 to 65,535 2 %ulong signed int -2147483648 to +2147483647 4 %ldlong unsigned int 0 to 4294967295 4 %luFloat -3.4e38 to +3.4e38 4 %fDouble -1.7e308 to +1.7e308 8 %lflong double -1.7e4932 to 1.7e4932 10 %Lf

Input and Output functions

Output Functions:-printf( ): This function is used to display the information on the screen. It displays the variable values and the string values. This function belongs to stdio.h.

Syntax: printf(“control string” ,variable list);

Where control string is used to control the output. It contains the conversion characters, white space characters and the string. The conversion character specifies the position and data type of a variable.

The compiler displays the common message as it is on the screen. The variable list specifies the list of variables to be displayed and they are separated by a comma (,)

Syntax: printf(“\n Welcome to C”);

Ex;- int a=10;printf(“\n The value of a is %d”,a);

float pi=3.14;printf(“\n The value of pi is %f”, pi);

char ch=’y’;printf(“The option is %c”,ch);

char name[20]=”India” ;printf(“\n The name is %s”,name);

Input functions:Scanf( ):- It is an input function, that is used to accept the values into variables at the time of executing a program. This function belongs to stdio.h .

Syntax: Scanf(“control string”, variable list);Where control string is used to control the input format. It contains the

conversion characters that specify the data type of the variable. Where variable list

Page 7: C language for Semester Exams for Engineers

specifies one or more variables and a comma separates them. Each variable should start with ‘&’, that indicates the address of the variables. This symbol is not required for string variables, because a string is a pointer to itself.

Ex:- int a;scanf(“%d”, &a);

float b;scanf(“%f”, &b);

char ch;scanf(“%c”, &ch); char name[20];scanf(“%s”,name);

int a,b; scanf(“%d%d”,&a,&b);

int a;float b;scanf(“%d%f”,&a,&b);

int a;float b;char ch,name[20];scanf(“%d%f%c%s”, &a, &b, &ch, name);

Structure of a C program

/* Comment line section *\ Documentation optional# header file section when we use predefined functionsmain( ){ Declaration part ; To declare the variables which are used in the

program. Initialization part ; To initialize i.e. giving values to the variables. Execution part ; To execute as output.}

A C program starts with the include statement. This statement is used to link the header files into our program. This statement should start with # symbol.

Ex-: # include <stdio.h>stdio.h stands for standard input output . header file

Comment Line Section:

Page 8: C language for Semester Exams for Engineers

In order to give documentation for a program comment line is includes. It is enclosed in between a /* *\ because in the compilation process these lines are not includes.

Header file section:‘C’ program consists of predefined functions for that reason we should include

the files in which they are defined. Which are saved with .h as extension.

Main( ) :The compilation and the running process is done with the help of Main( ). A

‘C’ program definitely requires Main( ).

Declaration part:This area is where we declare all the variables which are used in the program.

Initialization part:Here, we give values to the declared values.

Executable part:The output is seen from the executable part. By using output functions.

Programming rules: A ‘C’ program should be written in lower case. Every statement should end with; . The pair of { } should be matched.

Compilation and Execution process:After writing the program we should compile by pressing on the Compile

option of Compile menu. This converts the text format that is source code into Binary format which is called as object code. After that by pressing Run option the output can be seen.

Sample programs

1. To print some messages

#include<stdio.h>#include<conio.h>void main( ){

clrscr( );printf(“Welcome to C”);printf(“ Course name \t : \t ‘C’ lang \n”);getch( ) ;

}

Output

Welcome to CCourse name : ‘C’ lang

Page 9: C language for Semester Exams for Engineers

2. Write a program to add two numbers.

#include<stdio.h>#include<conio.h>void main ( ){

int a, b, c;a=20;b=30;c=a+b;printf(“C = %d”, c);getch ( );

}

Output

C = 50

3. Write a program to calculate Area and Perimeter of a Rectangle.

#include<stdio.h>#include<conio.h>void main ( ){

float length, breadth, area, perimeter;clrscr ( );length=4.5;breadth=3.5;area=l*b;perimeter=2*(length + breadth);printf(“\n The area of the rectangle is %f sq units”, area);printf(“\n The perimeter of the rectangle is %f units”, perimeter);getch ( );

}

4. Write a program to calculate Area and Perimeter of a Square.

#include <stdio.h>#include <conio.h>void main ( ){

float side, area, perimeter;clrscr( );printf(“\n Enter side of the square”);scanf(“%f ”, &side);area=side*side;perimeter=4*side;printf(“\n The area of a square is %f squints”, area);

Page 10: C language for Semester Exams for Engineers

printf(“\n The perimeter of a square is %f units”, perimeter);getch( );

}

5. Write a program to calculate the Radius and Area of the Circle.

#include<stdio.h>#include<conio.h>void main ( ){

float radius, area;float const pie =3.14;clrscr ( );printf(“\n Enter radius of the circle”);scanf(“%f ”, &radius);area=pie*radius*radius;printf(“\n The area of the circle is %f sq units”, area);getch( );

}

6) Write a program by using power function

#include<stdio.h>#include<conio.h>#include<math.h>main( ){ int x,y,z; clrscr( ); printf("\n Enter the Base and Exponent value\t:"); scanf("%d %d", &x,&y); z=pow(x,y); printf("\n The result is %d", z); getch( );}

6) Write a program to calculate employee salary.

# include <stdio.h># include <conio.h>void main( ){ int eno;

Page 11: C language for Semester Exams for Engineers

float basic_salary,hra,da,ta,gross; char name[20]; clrscr( ); printf("\n Enter eno, name , basic salary "); scanf("%d %s %f", &eno, name, &basic_salary); hra=basic_salary*15/100; da=basic_salary*12/100; ta=basic_salary*13/100; gross=basic_salary+hra+da; printf("\n Employee number is %d",eno); printf("\n Employee name is %s",name); printf("\n Basic is %f",basic_salary); printf("\n Hra is %f",hra); printf("\n Da is %f",da); printf("\n Gross is %f",gross); getch( );}

7) -..Write a program to calculate telephone bill of a month.

#include<stdio.h>#include<conio.h>void main( ){

int nc;float const rate=2.50;float bill;clrscr( );printf(“\n Enter nc per month \t:\t”);scanf(“%d”, &nc);bill=nc*rate;printf(“\n The bill of the month for %d is Rs. %f”, bill);getch( );

}

8) Write a program to take student roll no, student name, 6 subject marks and calculate total and average for the marks.

#include<stdio.h>#include<conio.h>void main( ){

int rollno, s1, s2, s3, s4, s5, s6, total;float avg;char name[20];clrscr( );printf(“\n Enter rollno”);

Page 12: C language for Semester Exams for Engineers

scanf(“ %d”, &rollno);printf(“\n Enter name of the student”);scanf(“ %s”, name);printf(“\n Enter subject marks”);scanf(“ %d %d %d %d %d %d”, &s1, &2, &s3, &s4, &s5, &s6);total=s1+s2+s3+s4+s5+s6;avg=total*100/600;printf(“\n Rollno=%d”, rollno);printf(“\n Name=%s”, name);printf(“\n Total=%d”, total”);printf(“\n Avg=%f”, avg);getch( );

}

Operators

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment or decrement operators6. Conditional operators

Arithmetic OperatorsArithmetic operators are used to perform arithmetic operations like addition,

subtraction, multiplication, division and remainder.

Operator Name Meaning Example+ Plus Addition a+b- Minus Subtraction a-b* Asterisk Multiplication a*b/ Slash Division a/b% Modulator Remainder a%bEx: a=10, b=3

a+b = 10+3 =13a-b = 10 - 3 = 7a*b = 10 * 3 =30a/b= 10 / 3 = 3 a%b=10%3=1 b%a =3%10=3

Relational operators:-These operators are used to check the relation between the values.

Note:- When we used relational operators the output is seen in the form of 0 or 1. If the relation is true the output will be in 1. If the relation is false the output will be 0.

Page 13: C language for Semester Exams for Engineers

Ex:-a=10; b=3;

Operator Name Example Result< Less than a<b False or 0> Greater than a>b True or 1<= Less than or equal to a<=b False or 0>= Greater than or equal

toa>=b True or 1

== Equal to a= =b False or 0!= Not equal to a!=b True or 1

Logical operators: logical operators are used to combine two or more relational expressions. C language contains 3 logical operators.

Operator name && And || Or ! Not

i. && : (And)

Statement:- When all arguments are true then only the total condition is true. Any one of the arguments is false the total condition is false.

Truth TableExpression1 && Expression2

Result

T T TT F FF T FF F F

ii. || : (Or)

Statement:- When one of the argument is true the total condition is true. If all the arguments are false then only the condition is false.

Truth TableExpression1 || Expression2 ResultT T TT F TF T TF F F

iii. ! (Not):Statement:- This is the negative operator, we can place the ‘not’ operator before

any one of the condition. It returns the opposite result of the condition. i.e. It converts true to false and false to true.

Truth Table! expression result

Page 14: C language for Semester Exams for Engineers

T FF T

Assignment operator: C language contains equal to (=) operator to assign a value or expression into a variable.

Ex:- a=10; a=a+10;

Increment and decrement operators:

1) ++ increment operator2) -- decrement operator

Increment operator (+ +)Increment operator is used to increase the value by 1.

Pre Increment( ++a) First the value will be incremented, and then the new value will be printed.

Ex:- printf(“%d”,++a);

Post Increment(a++) First the value will be printed and then the value will be incremented.

Ex:- printf(“%d”,a++);

Decrement operator ( - - )Decrement operator is used to decrease the value by 1.

Pre Decrement (--a)If the value is decreased before execution it is called as pre decrement.

Ex:- printf(“%d”,--a);

Post Decrement (a--)If the value is decreased after the execution it is called as post decrement.

Ex:- printf(“%d”,a--)

Conditional operators:- C language contains conditional operators (?, : ). By using conditional operators we can get the output in the form of statements also. ? and : are called as conditional or temporary operators.

Syn: (condition) ? printf(“value 1”) : printf(“ value 2”)

Ex:- (a>b) ? printf(“a is greater than b”):printf(“a is less than b”)

Page 15: C language for Semester Exams for Engineers

If the condition is true then value1 will be returned, if the condition is false then value2 will be returned

9) Write a program using Arithmetic operators.

#include<stdio.h>#include<conio.h>void main( ){

int a, b;clrscr( );printf(“\n Enter a and b values \t:\t”);scanf(“%d %d”, &a, &b);printf(“\n The sum of %d & %d is %d”, a,b, a+b);printf(“\n The difference of %d & %d is %d”, a,b, a-b);printf(“\n The product of %d & %d id %d”, a,b, a*b);printf(“\n The division of %d & %d is %d”, a,b, a/b);printf(“\n The reminder of %d & %d is %d”, a,b, a%b);getch( );

}

10)Write a program by using Relational operators.

#include<stdio.h>#include<conio.h>#include<math.h>void main( ){

int a, b, c, d, e, f, g, h;clrscr( );printf(“\n Enter a and b values”);scanf(“%d %d”, &a,&b);c=a>b;d=a<b;e=a>=b;f=a<=b;g=a= =b;h=a!=b;printf(“\nThe result of c is %d”,c);printf(“\nThe result of d is %d”,d);printf(“\nThe result of e is %d”,e);printf(“\nThe result of f is %d”,f);printf(“\nThe result of g is %d”,g);printf(“\nThe result of h is %d”,h);getch( );

}

Page 16: C language for Semester Exams for Engineers

11)Write a program by using logical operators.

#include<stdio.h>#include<conio.h>#include<math.h>void main( ){

int m, p, c, d, e;clrscr( ); printf(“\n Enter the subject marks”);scanf(“ %d %d %d”, &m, &p, &c);d=(m>=35 && p>=35 && c>=35);e=(m>=35 || p>=35 || c>=35);printf(“\n The output using ‘and’ operator is %d”, d);printf(“\n The output using ‘or’ operator is %d”, e);getch( );

}

12)Write a program using Increment and Decrement operator.

#include<stdio.h>#include<conio.h>#include<math.h>void main( ){

int a,b,c,d,e;clrscr( );printf(“\n Enter the value of ‘a’”);scanf(“%d”, &a);b=a++;c=++a;d=a--;e=--a;printf(“\n The value of b=%d”,b);printf(“\n The value of c=%d”,c);printf(“\n The value of d=%d”,d);printf(“\n The value of e=%d”,e);getch( );

}

13)Write a program to check whether the given number is even or odd using conditional operator.

#include<stdio.h>

Page 17: C language for Semester Exams for Engineers

#include<conio.h>void main( ){

int n;clrscr( );printf(“\n Enter any value”);scanf(“%d”,&n);(n%2= =0) ? printf(“\n The number is Even”) : (“\n The number is Odd”);getch( );

}

14)Write a program to check whether the student is passed or failed, by using conditional operator.

#include<stdio.h>#include<conio.h>void main( ){

int s1, s2, s3;clrscr( );printf(“\n Enter 3 subjects marks \t:\t”);scanf(“%d %d %d”, &s1, &s2, &s3);(s1>=35&&s2>=35&&s3>=35) ? printf(“\n The student is passed”) : printf(“\n The student is filed”);getch( );

}

15)Write a program to find the highest among the three given values.

#include<stdio.h>#include<conio.h>void main( ){

int a,b,c;clrscr( );printf(“\n Enter any 3 values”);scanf(“%d %d %d”, &a, &b, &c);(a>b&&a>c) ? printf(“ A is the highest value”) : (b>c) ? printf(“ B is the highest value”) : printf(“ C is the highest value”);getch( );

}

Page 18: C language for Semester Exams for Engineers

Conditional statements

Conditional statements:- The statements which are executed according to some condition are called as conditional statements.

IfStatement: This statement is used to perform conditional operations.Syntax:

if(condition){ statement;}

If the condition is true then statement1 will be executed. If the condition is false then it will not execute statement1.

If-elseSyntax:

if(condition) { statement1; }else{ statement2;}

If the condition is true then statement1 will be executed, if the condition is false then statement2 will be executed.

Nested if-elseStatement:- If condition1 is true, then it will check condition2, if it is true then statement1 will be executed. If condition1 is false it will not check condition2.Syntax :

if(condition1){statement1;}elseif(condition2){statement2;}else{statement3;}

Page 19: C language for Semester Exams for Engineers

If the condition1 is true then statement1 will be executed and the remaining statements will be skipped. If the condition1 is false then it will check the condition2,if it is true then statement2 will be executed. If both condition1 and condition2 are false then it will execute statement3.

If- else

1. Write a program to check whether a citizen is eligible for voting are not using if else.

#include<stdio.h>#include<conio.h>Void main( ){

int age;clrscr( );printf(“\n Enter the age of the citizen”);scanf(“%d”, &age);if(age>18)

{ printf(“\n Eligible for voting”); }

else {

printf(“\n Not eligible for voting”); }

getch( );}

2. Write a program to check whether the entered year is leap year or not.

#include<stdio.h>#include<conio.h>main( ){

int year;clrscr( );printf(“\n Enter any year”);scanf(“%d”, &year);if(year%4= =0); { printf(“\n Leap year”);

}else

{ printf(“\n Non leap year”);

}

Page 20: C language for Semester Exams for Engineers

getch( );}

3. Write a program to find the entered alphabet is vowel or consonant using if else.

#include<stdio.h>#include<conio.h>void main( ){ char ch; clrscr( ); printf("Enter any alphabet \t:\t"); scanf("%c",&ch); if(ch= ='a'||ch= ='A'||ch= ='e'||ch= ='E'||ch= ='i'||ch= ='I'||ch= ='o'||ch=='O'||ch= ='u'||ch= ='U'){ printf("It is a vowel");} else{ printf("It is a consonant");}getch( );}

Nested if-else

1. Write a program to check the least among the three given values.

#include<stdio.h>#include<conio.h>main( ){

int a,b,c;clrscr( );printf(“\n Enter any 3 values”);scanf(“%d %d %d”, &a,&b,&c);if(a<b&&a<c)

{ printf(“\n %d is the least value”, a);

}elseif(b<c)

{ printf(“\n %d is the least value”, b);

}else

Page 21: C language for Semester Exams for Engineers

{ printf(“\n %d is the least value”, c);

}getch( );

}

Switch statement

It is used to execute one of the options from no. of options. It is also called as multi branching statement.

Switch (expression){case value:

statements;case value:

statements;default:

statements; }

The expression value may be int or character type. The switch statement evaluates the expression. It will select one of the cases based on expression. It will execute default statements when no case is selected.

Break statementIt is used to exit from a looping statement. We can use this in for, while , do

while, and switch statement.Ex:- break;Switch caseSyntax: switch(expression)

{case 1:{}break;case 2:{}break;default:{}}

Page 22: C language for Semester Exams for Engineers

1. Write a program to print the name of the day using switch case.

#include<stdio.h>#include<conio.h>main( ){

int n;clrscr( );printf(“\n Enter any number”);scanf(“ %d”, &n);switch(n)

{case 1:printf(“\n The name of the day is Sunday”);break;case 2:printf(“\n The name of the day is Monday”);break;case 3:printf(“\n The name of the day is Tuesday”);break;

case 4:printf(“\n The name of the day is Wednesday”);break;case 5:printf(“\n The name of the day is Thursday”);break;case 6:printf(“\n The name of the day is Friday”);break;case 7:printf(“\n The name of the day is Saturday”);break;default:printf(“\n Invalid number”);

}getch( );

}

2. Write a program to check whether the enter alphabet is vowel or consonant.

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

main( ){

char c;clrscr( );printf(“\n Enter any Alphabet”);scanf(“%c”, &c);switch(c)

{case ‘a’:printf(“\n It is a vowel”);beak;case ‘e’:printf(“\n It is a vowel”);beak;case ‘i:printf(“\n It is a vowel”);break;

Page 23: C language for Semester Exams for Engineers

case ‘o’:printf(“\n It is a vowel”);beak;case ‘u’:printf(“\n It is a vowel”);break;default:printf(“\n It is a consonant”);

} getch( );

}

3. Write a program Arithmetic operator according to the entered choice.

#include<stdio.h>#include<conio.h>main( ){

int a, b;char op;printf(“\n enter the operator symbol”);scanf(“%s”, &op);printf(“\n enter a & b values”);scanf(%d %d”, &a,&b);switch(op)

{case ‘+’:printf(“\n The sum of %d and %d is %d”, a,b, a+b);break;case ‘-‘:printf(“\n The difference of %d and %d is %d”, a,b, a-b);break;case ‘*’:printf(“\n The product of %d and %d is %d”, a,b, a*b);break;default:printf(“\n Invalid operator”);

}getch( );

}

Goto statement

Goto statement: It is used to transfer the control from one place to another place in the program. It is also called as unconditional jumping statement

Syntax-: goto <label name> ;Ex:- goto print;

Page 24: C language for Semester Exams for Engineers

1) Write aprogram to print the numbers from 1 to 10.

#include<stdio.h>#include<conio.h>main( ){

int i=1;clrscr( );orbit:printf(“%d”, i);i++;if(i<=10)goto orbit;getch( );

}

Continue statement

Continue statement: It is used to transfer the control to the beginning of the looping statements. If the condition is true then the statement is not executed. If it false then the statement is executed.Ex: continue;

#include<stdio.h>#include<conio.h>main( ){

int i;clrscr( );for(i=1;i<=100;i++)

{if(i%10= =0)continue;printf(“%d”,i);

}getch( );

}

#include<stdio.h>#include<conio.h>main( ){

int i;clrscr( );for(i=1;i<=10;i++)

Page 25: C language for Semester Exams for Engineers

{if(i= =5)continue;printf(“%d”,i);

}getch( );

}

Loop control structures

LOOPING:- The process of executing a block of code repeatedly is called as looping.

1) While loop2) Do while loop3) For loop4) Nested for loops

All the four loops are used for same process but there syntax is different.All the four loops have 3 steps in common.

1) Initialization:- It is the starting point of the loop process.2) Condition:- In this step logical test is applied. It is true the block of code is

executed. Till the condition fails.3) Increment / Decrement:- In order to proceed or stop the loop increment or

decrement is required.

While loop

While statement:It is used to execute a set of statements repeatedly as long as the given condition is true.

Syntax:while (condition)

{statements; //body of while loop

}

First the condition is tested, if it is true the body of the while loop will be executed first time, again the control is transferred back to while loop and checks the condition, If it is false the control will come out of the while loop.

Page 26: C language for Semester Exams for Engineers

1) Write a program to print the numbers divisible by 5 between 50 and 100.

#include<stdio.h>#include<conio.h>main( ){

int i=50;clrscr( );while(i<=100)

{if(i%5 = =0)printf(“%d”, i);i++;

}getch( );

}

2) Write a program to print multiplication tables from 1 to 20 using while loop.

# include <stdio.h># include <conio.h>void main( ){ int n,i; clrscr( ); n=1; while(n<=20) { i=1; while(i<=10) { printf("\n%d X %d = %d",n,i,n*i); i++; } n++; printf("\n Press any key for the next table "); getch( ); }}

2) Write a program to sum the digits of a given number.

#include<stdio.h>#include<conio.h>main( )

Page 27: C language for Semester Exams for Engineers

{int i, n, rem, sum=0;clrscr( );

printf(“\n Enter any 3 digit number”); scanf(“%d”, &n); while(n>=1){ rem=n%10;

sum=sum+rem; n=n/10;} printf(“\n The sum of digits of given number is %d”, sum); getch( );}

3) Write a program to reverse the given number.

#include<stdio.h>#include<conio.h>main( ){

int n, sum, rev=o, rem;clrscr( );

printf(“\n Enter any number”); scanf(“%d”, &n); while(n>=1){ rem=n%10; rev=rev*10+rem; n=n/10;} printf(“\n The reverse of the given number is %d”, rev); getch( );}

74) Write a program to test for given number is Palindrome.

#include<stdio.h>#include<conio.h>main( ){

int n, rem, rev=0, temp;clrscr( );

printf(“\n Enter any number”); scanf(“%d”, &n); temp=n;

Page 28: C language for Semester Exams for Engineers

while(n>=1){ rem=n%10; rev=rev*10+rem; n=n/10;} printf(“\n The reverse of the number is %d”, rev); if(rev= =temp){ printf(“\n The number is a Palindrome number”); else{ printf(“\n The number is not a Palindrome number”);} getch( );

}

5) Write a program to test for Armstrong number.

#include<stdio.h>#include<conio.h>main( ){

int n, rem, sum=0, temp;clrscr( );

printf(“\n Enter any number”); scanf(“%d”, &n); temp=n; while(n>=1){ rem=n%10; sum=sum+rem*rem*rem; n=n/10;} if(sum= =temp){ printf(“\n The number is Armstrong number”);} else{ printf(“\n The number is not a Armstrong number”);} getch( );

}Do While Loop

Do while loop:- This statement executes a set of statements as long as the condition is true.

Page 29: C language for Semester Exams for Engineers

Syntax: do {

statements; statements;}while(condition);

This is similar to while loop, but the difference is this loop will execute the statements at least once.

1) Write a program to print the natural numbers of the given number.

# include <stdio.h># include <conio.h>void main(){ int n,i; clrscr(); printf("\n Enter a number "); scanf("%d",&n); i=1; do{

printf("\t%d",i); i=i+1; }

while(i<=n); getch();}

For loop

It is used to execute a set of statements repeatedly as long as the given condition is true.Syntax:-

for(initial value ; test condition ; increment /decrement)

{statements; //body of for loop

}

When the for loop is executing for the very first time the initial value is stored in the given variable. Then the condition will be tested. If it is true, the statements will be executed. After executing the last statement the control will return back to the for loop. Then the value will be incremented / decremented. Again the condition is tested, if it is false the control will come out of the for loop.

Page 30: C language for Semester Exams for Engineers

Ex:- for(i=1; i<=10; i++)

1) Write a program to print the name 10 times using ‘for loop’.

#include<stdio.h>#include<conio.h>main( )

{int i;clrscr( );for (i=1;i<=10;i++)

{printf(“\n cyberaegis”);

}getch( );

}

2) Write a program to print the numbers between 1 to 100.

#include<stdio.h>#include<conio.h>main( )

{int i;clrscr( );for(i=1;i<=100;i++)

{printf(“\n %d”, i);

}getch( );

}

3) Write a program to print the even numbers from 1 to 50.

#include<stdio.h>#include<conio.h>main( )

{int i;clrscr( );for(i=1;i<=50;i++)

{if(i%2= =0)

Page 31: C language for Semester Exams for Engineers

{printf(“\n %d”, i);

}}

getch( );}

4) Write a program to print odd numbers from 10 to 100.

#include<stdio.h>#include<conio.h>main( )

{int i;clrscr( );for(i=10;i<=100;i++)

{if(i%2!=0)

{printf(“%d”, i);

}}

getch( );}

5) Write a program to print the Multiplication table of the given number.

#include<stdio.h>#include<conio.h>main( )

{int n,i,r;clrscr( );printf(“\n Enter any number”);scanf(“%d”, &n);for(i=1;i<=10;i++)

{r =n*i;printf(“%d*%d=%d”,n, i, r);

}getch( );

}6) Write a program to find the factorial of a given number.

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

Page 32: C language for Semester Exams for Engineers

main( ) {

int i, fact=0, n;clrscr( );printf(“\n Enter any number”);scanf(“%d”, &n);for(i=1;i<=n;i++)

{fact=fact*i;

}printf(“\n Factorial of %d=%d”, n, fact);getch( );

}

7) Write a program to print prime numbers.

#include<stdio.h>#include<conio.h>void main( ){ int n,i,count=0; clrscr( ); printf("Enter a numbe"); scanf("%d",&n); for(i=1;i<=n;i++){ if(n%i==0) count++;} if(count= =2) printf("prime"); else printf("not prime"); getch( );}

8) Write a program to print sum of digits of a given number.

#include<stdio.h>#include<conio.h>main( ){int i,n,sum=0;clrscr( );printf("enter any number");scanf("%d",&n);for(i=0;i<=n;i++){

Page 33: C language for Semester Exams for Engineers

sum=sum+i;//printf("%d",i);}printf("%d",sum);getch( );

}

9) Write a program to print the squares of a given number.

#include<stdio.h>#include<conio.h>main( ){int i,n,sum=0;clrscr( );printf("enter any number");scanf("%d",&n);for(i=1;i<=n;i++){printf("the square of %d is %d\n",n,n*n);}getch( );}

Nested for loop

In order to get the output in the form of rows and columns we use nested for loops. If the outer loop condition is true it enters into the inner loop. Till the outer loop condition is false the looping process is continued.

1) Write a program to get the * output as using nested for loop.* ** * *

#include <stdio.h>#include<conio.h>main( ){

int n,i,j;clrscr( );printf(“\n Enter the value of n”);scanf(“%d”, &n);for(i=1;i<=n;i++)

{for(j=1;j<=i;j++)

Page 34: C language for Semester Exams for Engineers

{printf(“*”);

}printf(“\n”);

} getch( );

}

2) Write a program to get the output as 1 using nested for loop. 1 2 1 2 3

#include<stdio.h>#include<conio.h>main( ){

int n, i, j;clrscr( );printf(“\n Enter the value of n”);scanf(“%d”, &n);for(i=1;i<=n;i++)

{for(j=1;j<=i;j++)

{printf(“%d”, j);

}printf(“\n”);

}getch( );

}

3) Write a program to get the output in the form of 1 by using nested loop.2 23 3 3

#include<stdio.h>#include<conio.h>main( ){

int n, i, j;clrscr( );printf(“\n Enter the value of n”);scanf(“%d”, &n);for(i=1;i<=n;i++)

{for(j=1;j<=i;j++)

{printf(“%d”, i);

Page 35: C language for Semester Exams for Engineers

}printf(“\n”);

}getch( );

}

4) Write a program to get the output in the form of 1 2 3 4 by using nested for loop. 1 2 3

1 21

#include<stdio.h>#include<conio.h>main( ){

int n, i, j;clrscr( );printf(“\n Enter the value of n”);scanf(“%d”, &n);for(i=n;i>=1;i--)

{for(j=1;j<=i;j++)

{printf(“%d”, j);

}printf(“\n”);

}getch( );

}

5) Write a program to get the output in the form of 4 4 4 4 by using nested for loop. 3 3 3

2 21

#include<stdio.h>#include<conio.h>main( ){

int n, i, j;clrscr( );printf(“\n Enter the value of n”);scanf(“%d”, &n);for(i=n;i>=1;i--)

{for(j=1;j<=i;j++)

{printf(“%d”, i);

}printf(“\n”);

}

Page 36: C language for Semester Exams for Engineers

getch( ); }

6) Write a program to get the output as 1 using nested for loop 1 0 1 0 1

#include<stdio.h>#include<conio.h>main(){int i,j,n;clrscr();printf("Enter any number");scanf("%d",&n);for(i=1;i<=n;i++){for(j=1;j<=i;j++){printf("%3d",j%2);}printf("\n");}getch();}

7) Write a program to get the output in the form of by using nested for loop.

# include <stdio.h># include <conio.h>void main( ){

int i,j;clrscr( );for(i=1;i<=5;i++)

{for(j=1;j<=i;j++)printf("%3d",j);printf("\n");

}for(i=4;i>=1;i--)

{for(j=1;j<=i;j++)printf("%3d",j);printf("\n");

11 21 2 31 2 3 41 2 3 4 51 2 3 41 2 31 21

Page 37: C language for Semester Exams for Engineers

}getch( );

}

8) Write a program to get the output as * using nested for loop * * * * *

#include<stdio.h>#include<conio.h>main(){int i,j,k,n;clrscr();printf("Enter any number");scanf("%d",&n);for(i=1;i<=n;i++){for(k=n;k>i;k--)printf(" ");for(j=1;j<=i;j++){printf("*");}printf("\n");}getch();}

9) Write a program to get the output as 1 using nested for loop 1 2 1 2 3

#include<stdio.h>#include<conio.h>main(){int i,j,k,n;clrscr();printf("Enter any number");scanf("%d",&n);for(i=1;i<=n;i++){for(k=n;k>i;k--)printf(" ");for(j=1;j<=i;j++){printf("%d",j);

Page 38: C language for Semester Exams for Engineers

}printf("\n");}getch();}

10) Write a program to get the output as 1 using nested for loop 1 0 1 0 1

#include<stdio.h>#include<conio.h>main(){int i,j,k,n;clrscr();printf("Enter any number");scanf("%d",&n);for(i=1;i<=n;i++){for(k=n;k>i;k--)printf(" ");for(j=1;j<=i;j++){printf("%2d",j%2);}printf("\n");}getch();}

11) Write a program to get the output as C using nested for loop C Y

C Y B C Y B E R O R B I T

#include<stdio.h>#include<conio.h>main(){char name[]="CYBER";int i,j;clrscr();for(i=0;i<=4;i++)

Page 39: C language for Semester Exams for Engineers

{for(j=0;j<=i;j++){printf("%c",name[j]);}printf("\n");}getch();}

12) Write a program to get the output as O using nested for loop R R

B B B I I I I I T T T T T

#include<stdio.h>#include<conio.h>main(){char name[]="orbit";int i,j;clrscr();for(i=0;i<=4;i++){for(j=0;j<=i;j++){printf("%c",name[I]);}printf("\n");}getch();}

ARRAYS

An array is contiguous area in the memory referred by a common name. The array allows the storage of a number of data values in one variable. Each array element i.e. each individual data item is referred by specifying the array name

Page 40: C language for Semester Exams for Engineers

followed by one or more subscripts. Each subscript is enclosed with square brackets. Each subscript indicates the position of the element in the array. Arrays are divided into 2 types.

1) Single dimensional arrays. or One dimensional arrays2) Multi dimensional arrays

1) One dimensional arrays:- The array which is using only 1 subscript is known as one dimensional array. In one dimensional array the elements are represented in single row or single column.Syntax:- Data_type variable_name[subscript]Ex: int a[5]={40, 50, 70,90,100};

Float b[4]={20.5, 40.9, 45.7, 23.8}; Char c[5]={‘C’,’Y’,’B’,’E’,’R’};

The above declaration states that ‘a’ is an array variable in which we can store 5 values of integer data type. Similarly ‘b’ is an array variable in which we can store 4 values of float data type. Similarly ‘c’ is an array variable in which we can store 5 characters.

2) Two dimensional arrays: The array which is using two subscripts is known as 2 – dimensional arraySyntax:- Data_type variable_name [subscript][subscript]

Ex:- int a[2][2]={{1,2,},{3,4}};

The above declaration states that ‘a’ is an two dimensional array variable in which the values are stored in 2 rows and in2 columns.

One dimensional Array

1) Write a program to access the elements from an Array.

#include<stdio.h>#include<conio.h>main( ){

int a[5]={40,50,60,90,100};int i;clrscr( );for(i=0;i<=4;i++)

{printf(“%d”, a[i]);

}getch( );

} 2) Write the program to print the name from an array.

#include<stdio.h>

Page 41: C language for Semester Exams for Engineers

#include<conio.h>main( ){

char c[5]={‘C’, ‘Y’, ‘B’, ‘E’, ‘R’};int i;clrscr( );for(i=0;i<=4;i++)

{printf(“%c”, c[i]);

}getch( );

}

3) Write a program to add the values of two arrays.

#include<stdio.h>#include<conio.h>main( ){

int a[3]={100,102,110};int b[3]={60,80,90};int I;clrscr( );printf(“\n Addition of two arrays”);for(i=0;i<=2;i++)

{printf(“%d+%d=%d”, a[i],b[i], a[i]+b[i]);

}getch( );

}

4) Write to print the entered string in reverse order.

#include<stdio.h>#include<conio.h>main( ){

char string[6];int i;clrscr( );printf(“\n Enter any string”);gets (strings);printf(“\n Reverse of a string”);for(i=6;i>=0;i--)

{printf(“%c”, string[i]);

Page 42: C language for Semester Exams for Engineers

}getch( );

}

5) Write a program to find the no. of times a character appears in a string.

#include<stdio.h>#include<conio.h>main( ){

char string[10], f;int i, c=0;clrscr( );printf(“\n Enter the string”);gets(string);printf(“\n Enter a letter to find in the string”);scanf(“%d”, &f);for(i=0;i<=9;i++)

{if(string[i]= =f)

{c++;

}}

printf(“\n The letter %c appears %d times in the %s”, f, c, string);getch( );

}

6) Write a program to print the name of a city and pincode using arrays.

#include<stdio.h>#include<conio.h>main( ){

char city[5]={‘N’,’A’,’N’’D’,’E’,’D’};int pin[6]={5,0,0,0,2,8};int i;clrscr( );for(i=0;i<=5;i++)

{printf(“%c”, city[i]);

}printf(“-“);for(i=0;i<=5;i++)

{printf(“%d”, pin[i]);

Page 43: C language for Semester Exams for Engineers

}getch();

}

Two dimensional Array

1) Write a program to access the elements of a two dimensional array.

#include<stdio.h>#include<conio.h>main( ){

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};int i, j;clrscr( );for(i=0;i<=2;i++)

{for(j=0;j<=2;j++)

{printf(“%d”, a[i][j]);

}printf(“\n”);

}getch( );

}

2) Write a program to enter the values of matrix in the output and displaythem.

#include<stdio.h>#include<conio.h>main( ){

int a[3][3];int i,j;clrscr( );printf(“\n Enter values into3*3 matrix”);for(i=0;i<=2;i++)

{for(j=0;j<= 2;j++)

{scanf(“%d”, &a[i][j]);

}}

for(i=0;i<=2;i++)

Page 44: C language for Semester Exams for Engineers

{for(j=0;j<=2;j++)

{printf(“%3d”, a[i][j]);

}printf(“\n”);

}getch( );

}

3) Write a program to add 2 matrices.

#include<stdio.h>#include<conio.h>main( ) {

int a[2][2], b[2][2], c[2][2];int i,j;clrscr( );printf(“\n Enter the values in

‘a’ matrix”);for(i=0;i<=1;i++)

{for(j=0;j<=1;j++)

{scanf(“%d”, &a[i][j]);

}}printf(“\n Enter the values of

‘b’ matrix”);for(i=0;i<=1;i++)

{for(j=0;j<=1;j++)

{

scanf(“%d”, &b[i][j]);}}

printf(“\n Addition of matrices”);

for(i=0;i<=1;i++){

for(j=0;j<=1;j++){

c[i][j]=a[i][j]+b[i][j];printf(“%d”, c[i][j]);

}printf(“\n”);

}getch( );}

4) Write a program to enter rows and columns into matrix and output display them.

#include<stdio.h>#include<conio.h>main( ){

int a[10][10];int i, j, r, c;clrscr( );printf(“\n Enter no. of Rows and Columns”);

Page 45: C language for Semester Exams for Engineers

scanf(“%d %d”, &r, &c);printf(“\n Enter the values into matrix”);for(i=0;i<r;i++)

{for(j=0;j<c;j++)

{scanf(“%d”,&a[i][j]);

}}

for(i=0;i<r;i++){

for(j=0;j<c;j++){

printf(“%d”, a[i][j]);}

printf(“\n”);}

getch( );}

5) Write a program multiplication of matrix.

#include<stdio.h>#include<conio.h>main( ){

int a[2][2], b[2][2], c[2][2];int i, j, k;printf(“\n Enter the values in ‘a’

matrix”);for(i=0;i<2;i++)for(j=0;j<2;j++)printf(“Enter %d %d values”, i,

j);scanf(“%d”, &a[i][j]);

}printf(“\n Enter the values in ‘b’

matrix”);fo r(i=0;i<2;i++)for(j=0;j<2;j++)printf(“Enter %d %d values”, i,

j);scanf(“%d”, &b[i][j]);

}

printf(“\n Product of matrices”);

for(i=0;i<2;i++){for(j=0;j<2;j++){

c[i][j]=0;for(k=0;k<=1;k++)c[i][j]=c[i][j]+a[i][k]*b[k][j];

}}

for(i=0;i<2;i++){

for(j=0;j<2;j++)printf(“%3d”,c[i][j]);

}printf(“\n”);

}getch( );

}

Page 46: C language for Semester Exams for Engineers

6) Write a program to multiply the matrix to given number.

#include<stdio.h>#include<conio.h>main(){int a[2][2], b[2][2];int i,j,n;clrscr();printf("Enter any number");scanf("%d",&n);printf("\n Enter the values in 'A' matrix");for(i=0;i<=1;i++){for(j=0;j<=1;j++){scanf("%d",&a[i][j]);}}for(i=0;i<=1;i++){for(j=0;j<=1;j++){b[i][j]=n*a[i][j];printf("%d", b[i][j]);}printf("\n");}getch();}

Page 47: C language for Semester Exams for Engineers

String Functions

A character array is defined as a string. A group of characters is called a string. We cannot handle with string same like integers or real values.For example, if you want to compare an integer value with another int value.We can do that by using = = operator. But the same procedure cannot be applied for strings.In order to handle with strings there are some string handling functions.

1) strlen( ):- This function is used to find the length of a string.Syntax:- strlen(string);

Note:- When we are using string functions we have to include a header file

<string.h>

2) strcpy( ):- This function copies a string from one string variable to another string variable.

Syntax:- strcpy(target_string , source_string);

3) strcat( ): (String concatenation) This function adds a string at the end of another string

Syntax:- strcat(string1,stirng2);

4) strcmp( ): (String comparison)This compares one string with another string, if two strings are equal this function returns 0, else it returns the numeric difference between the non-matching characters.

Syntax:- strcmp(string1, string2);

5) stricmp( ): This function is similar to strcmp, but this function ignores the case sensitivity.

Syntax:- stricmp(string1, string2);

6) strrev( ): This function reverses the given stringSyntax:- strrev(string);

7) strupr( ): This function converts the given string into upper case(capital letters)Syntax:- strupr(string);

8) strlwr( ): This function converts the given string into lower case.Syntax:- strlwr(string);

Single character

1) toupper( ) :- This function converts a single character to upper case.Syntax:- toupper(character);

2) tolower( ) :- This function converts a single character to lower case.

Page 48: C language for Semester Exams for Engineers

Syntax:- tolower(character);

Note:- when we are using single character functions we have to include a header file <ctype.h>

1) Write a program to find the length of an entered string.

#include<stdio.h>#include<conio.h>#include<string.h>void main( ){

int length;char string[20];clrscr( );printf(“\n Enter any string”);gets(string);length=strlen(string);printf(“\n The length of the string=%d”, length);getch( );

}

2) Write a program to copy a string into another string.

# include <stdio.h># include <conio.h># include <string.h>void main( ){ char name[20],name1[20]; clrscr( ); printf("\n Enter your string "); scanf("%s",name); strcpy(name1,name); printf("\n The given string is %s",name); printf("\n The new string is %s",name1); getch( );}

3) Write a program to compare one string to another string.

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

Page 49: C language for Semester Exams for Engineers

void main( ){ char name[20],name1[20]; clrscr( ); printf("\n Enter your first string "); scanf("%s",name); printf("\n Enter your second string "); scanf("%s",name1); if(strcmp(name,name1)= =0) printf("\n Two strings are equal "); else printf("\n Two strings are not equal"); getch( );}

4) Write a program to print the reverse string of the given string.

# include <stdio.h># include <conio.h># include <string.h>void main( ){ char name[20]; clrscr( ); printf("\n Enter your first string "); scanf("%s",name); printf("\n The given string is %s",name); strrev(name); printf("\n The reverse string is %s",name); getch( );}

5) program to input a string and convert it into upper case and lower case

# include <stdio.h># include <conio.h># include <string.h>void main( ){ char name[20]; clrscr( ); printf("\n Enter your string "); scanf("%s",name); printf("\n The given string is %s",name); strupr(name); printf("\n the string in upper case is %s",name);

Page 50: C language for Semester Exams for Engineers

strlwr(name); printf("\n The string in lower case is %s",name); getch( );}

6) Write a program to convert uppercase string to lower case string by usingAscii code.

#include<stdio.h>#include<conio.h>#include<string.g>main( ){char str[30];clrscr( );printf(“\n Enter any string”);gets(str);while(str[i]!=’\0’){if(str[i]>=’A’&&str[i]<=’Z’)str[i]=str[i]+32;i++;}printf(“\n Converted given string from uppercase to lowercase is %S”, str);getch( );}

7) Single Character Functions

//toupper(), tolower()# include <stdio.h># include <conio.h># include <ctype.h>void main( ){ char name[20]; int i=0; clrscr( ); printf("\n Enter a string "); scanf("%s",name);

while(name[i]!='\0') { printf("%c",toupper(name[i]));

Page 51: C language for Semester Exams for Engineers

i++; } getch( );

}

Functions

FUNCTION

A function is a set of statements that performs a specific task. Functions are 2 types1) Pre defined functions or Standard functions2) User defined functions

1) Pre defined Functions:- These functions which are already defined (in built) along with C are called as pre defined functions.Ex:- printf( ), scanf( ), pow( ), strlen( ), strcpy( ), toupper( ),……

Functions

Pre defined User defined

User defined Functions

Functions

Function Definition Function Definition Function Definition

FunctionHeading

Block ofCode

ReturnStatement

ReturnType

FunctionName

Specification ofParameters

FormalParameter

ActualParameter

Page 52: C language for Semester Exams for Engineers

2) User defined functions:- These functions defined by the user in order to work with complex program and to develop the efficiency of the program are called as user defined functions. In order to define a function we have 3 types.

Function definition Function prototype Invoking a function

Function definition:-a) Function heading

i. Return type:- Return is called as data type mention according to the type of value returned from the function.

Note:- When there is no return statement we should mention void as a default return type.

ii. Function name:- Here we mention the name of a function. It is just like a variable name

iii. Specification of parameters:- The specify the number of values are variables taken by the called function from main program.

Note:-The parameters mentioned in the main program for calling a function are called as actual parameters.

The parameters mentioned in the function which are received from the main program are called formal parameters.

b) Block of code:- The code which is written with in the braces of a function is called as block of code.

c) Return statement:- This is the last statement of a function it is to written a value from the user defined function to the main program.

Function PrototypeIt is declared in the main program about the function.Note:-Function prototype is optional if the function is defined before the main. It is compulsory if the function is defined after the main.

Invoking a FunctionFrom here we call the function. A function as no live when it is not Invoked.

Uses of functions:a. Dividing the task into sub tasks.b. If a particular task is repeated number of times in a program we can create

a function and call that function wherever we want.c. Whenever a function is called in a statement the control will be transferred

to that called function. After executing all statements it returns back to the calling function.

d. The length of the source program will be reduced by using functions at appropriate places.

e. A function can be used in other programs also.Syntax of a function

Return_type function_name (argument list){ declarations;

Page 53: C language for Semester Exams for Engineers

statements; ------------- return value;}

Return statement: It returns a value of the expression to the calling function.

Syntax:- return(expression)Ex:- return(0);

return(a);return(a+b);return a;return;

1) Write a program with parameters with return value by using functions.

#include<stdio.h>#include<conio.h>int sum(int x, int y){

return(x+y);}

void main( ){

int a, b, c;clrscr( );printf(“\n Enter a & b values”);scanf(“%d %d”, &a, &b);c=sum(a,b);printf(“\n c=%d”, c);getch( ) ;

}

2) Write a program to print the multiplication table using with parameters, no return value by using functions.

#include<stdio.h>#include<conio.h>void table (int n){

int i,r;for (i=1;i<=10;i++)

{r=n*i;printf(“%d * %d = %d”, n,i,r);

}

Page 54: C language for Semester Exams for Engineers

}void main( )

{int no;clrscr( );printf(“\n Enter any number”);scanf(“ %d”, &no);table (no);getch( );

}

3) Write a program to calculate sum of digits of a given number using functions.

#include<stdio.h>#include<conio.h>long sum_digits(long n){

int rem;long sum=0;while (n>0)

{rem=n%10;sum=sum+rem;n=n/10;

}return sum;

}void main( )

{long no;clrscr( );printf(“\n Enter any long number”);scanf(“ %ld”, &no);printf(“\n Sum of digits = %ld”, sum_digits(no));getch( );

}

4) Write a program to find the largest value among 3 given values.

#include<stdio.h>#include<conio.h>int compare(int a, int b, int c){

Page 55: C language for Semester Exams for Engineers

if(a>b&&a>c){

return a;}

elseif(b>c)

{return b;

}else

{return c;

}}

void main( ){

int x, y, z;int compare(int, int, int);clrscr ( );printf (“\n Enter any 3 values”);scanf (“%d %d %d”, &x, &y, &z);printf (“\n Highest value is %d”, compare(x,y,z);getch ( );

}

5) Write a program the reverse of the given number using functions.

#include<stdio.h>#include<conio.h>void reverse(int n){

int rev=0, rem;while(n>0)

{rem=n%10;rev=rev*10+rem;n=n/10;

}printf(“Reverse of the given number = %d”, rev);

}void main( )

{int no;clrscr( );printf(“\n Enter any number”);scanf(“%d”, &no);reverse(no);getch( );

Page 56: C language for Semester Exams for Engineers

}

Recursive Function

1) Write a program to calculate the factorial of a given number using a recursive function.

# include <stdio.h># include <conio.h>void main( ){

int n;int fact(int);clrscr( );printf("\n enter a number ");scanf("%d",&n);if(n>0)printf("\n The factorial of %d is %d ",n,fact(n));getch( );

}int fact(int num)

{int f;if(num= =1)return 1;elsef=num*fact(num-1);return f;

}

2) Write a program to calculate the sum of first n natural numbers using Recursive function.

# include <stdio.h># include <conio.h>void main(){

int n;int sum(int);clrscr( );printf("\n enter a number ");scanf("%d",&n);printf("\n The sum of first %d numbers is %d ",n,sum(n));getch( );

}int sum(int num){

int s;if(num= =1)

Page 57: C language for Semester Exams for Engineers

return 1;elses=num+sum(num-1);return s;

}

Functions with Arrays

1) Write a program to print 10 numbers.

#include<stdio.h>#include<conio.h>void display(int b[] ){

int i;for(i=0;i<10;i++)

{printf(“\n %d”, b[i] );

}}

void main( ){

int a[10], i;clrscr( );printf(“\n Enter 10 values”);for(i=0;i<10;i++)

{printf(“\n Enter %d value”, i);scanf(“%d”, &a[i]);

}display(a);getch( );

}

2) Write a program to print 5 students, 3 subject marks and calculate total.

#include<stdio.h>#include<conio.h>int total(int s1, in s2, int s3)int tot;tot=s1+s2+s3;return tot;}

void main( ){

Page 58: C language for Semester Exams for Engineers

int i, sno, sub1, sub2, sub3;char name[20];clrscr( );for(i=0;i<=4;i++)

{printf(“\n Enter student no”);scanf(“%d”, &sno);printf(“\n Enter student name”);scanf(“%s”, &name); printf(“\n Enter 3 subject marks”);scanf(“%d %d %d”, &sub1, &sub2, &sub3);printf(“total = %d”, total(sub1, sub2, sub3));

}getch( );}

POINTERS

A pointer is a variable which holds the address of another variable. Since addresses are whole numbers pointers would always contain whole numbers.

Consider the following declarationEx:- int i=10;

The declaration tells the C compiler,

1) Reserve space in memory to hold the integer value.2) Associate the name ‘i’ with memory location.3) Store the value 10 at this location.

Memory map:-i

65524

‘i’ - Location name 10 - Value at location 65524 – Location number or address.

Declaration of a pointer:Int a, *x;Float b, *y;Char c, *z;

Pointer variable is same as normal variable. But a * symbol is added before the variable.

10

Page 59: C language for Semester Exams for Engineers

Usage of pointers:- As pointers wok with addresses accessing through addresses first then through a normal variable. When the values are called with the help of address by a function the modifications done to the variables shows the reflection.Indirectly we can get the value of a variable by using *. So * is called as indirection operator. Whatever the data type may be a pointer variable occupies only 4 bytes of memory.

1) Program to display the address of a variable.# include <stdio.h># include <conio.h>void main( ){ int i=10; clrscr( ); printf("\n The value of i is %d",i); printf("\n The address of i is %u",&i); printf("\n The value of i is %d",*(&i)); getch( );}

Note:-In the above program '&' is called 'address of operator', '*' is called 'value at address' operator.

2) Example for a pointer# include <stdio.h># include <conio.h>void main( ){

int i=10,*j;j=&i;clrscr( );printf("\n the address of i is %u ",&i);printf("\n the address of i is %u",j);printf("\n the value of i is %d ",i);printf("\n the value of i is %d",*(&i));printf("\n the value of i is %d",*j);printf("\n the address of j is %u",&j);printf("\n the value of j is %u",j);getch( );

}

Page 60: C language for Semester Exams for Engineers

Note:- j -- address of i -- 65524 &j -- j's own address – 65522 *j -- value at j i.e i value -- 10

3) W.A.P. To calculate all arithmetic operations of two numbers using pointers

# include <stdio.h># include <conio.h>void main( ){

int a,b,add,sub,mul,div;int *x,*y;clrscr( );x=&a;y=&b;printf("\n Enter a,b values ");scanf("%d%d",&a,&b);// scanf("%d%d",x,y);add=*x + *y;sub=*x - *y;mul=*x * *y;div=*x / *y;printf("\n Addition is %d",add);printf("\n Subtraction is %d",sub);printf("\n Multiplication is %d",mul);printf("\n Division is %d",div);getch( );

}

4) Write a program to add two numbers using pointers.

#include<stdio.h>#include<conio.h>void main ( ){

int a, b, c, *pa,*pb,*pc;clrscr( );pa=&a; // *pa=apb=&b; // *pb=bpc=&c; // *pc=c*pa=20;*pb=30;*pc=*pa+*pb;printf(“C = %d”, *pc);getch ( );

}

Page 61: C language for Semester Exams for Engineers

Parameter passing mechanism

Call by value Call by address

Call by value:- When the function calls the parameters by taking values the modifications done to the parameters by the function doesn’t reflect.

Call by address;- When the parameters are called by address the changes done to the values within the function shows the reflection.

1) Example program for call by value# include <stdio.h># include <conio.h>void main( ){void swap(int,int);int a,b;clrscr( );printf("\n Enter a b values ");scanf("%d%d",&a,&b);printf("\n Before swap function the values of a and b are %d

%d",a,b);swap(a,b);printf("\n After swap function the values of a and b are %d %d

",a,b);getch( );

}void swap(int x,int y){int t;t=x;x=y;y=t;printf("\n In swap function the values of x and y are %d %d ",x,y);

}

2) Example program for call by address# include <stdio.h># include <conio.h>void main( ){void swap(int *,int *);int a, b;clrscr( );printf("\n Enter a , b values ");scanf("%d %d", &a, &b);printf("\n Before swap function the values of a and b are %d %d", a, b);

Page 62: C language for Semester Exams for Engineers

swap(&a, &b);printf("\n After swap function the values of a and b are %d %d ", a, b);getch( );}void swap(int *x, int *y){int t;t=*x;*x=*y;*y=t;printf("\n In swap function the values of a and b are %d %d ",*x,*y);}

Pointers & Arrays

One dimensional array

1) Write a program to input 10 integer values into a one dimensional array and display them using pointers.

# include <stdio.h># include <conio.h>void main(){ int a[10],i; clrscr(); printf("Enter 10 values \n"); for(i=0;i<10;i++) { printf(" Enter %d number ",i); scanf("%d",&a[i]); } printf("\nThe given values are \n"); for(i=0;i<10;i++) printf("\n The %d value is %d",i,*(a+i)); getch();}

Two dimentional array

Page 63: C language for Semester Exams for Engineers

1) Write a program to access the elements of a two dimensional array using pointers.

#include<stdio.h>#include<conio.h>main(){int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};int i,j;clrscr();for(i=0;i<=2;i++){for(j=0;j<=2;j++){printf("%d", *(*(a+i)+j));}printf("\n");}getch();}

2) Write a program to print the matrix by taking rows and columns using pointers.

#include<stdio.h>#include<conio.h>main(){int a[10][10];int i,j,r,c,*pr,*pc;clrscr();pr=&r; //*pr=rpc=&c; //*pc=cprintf("\n Enter no. of rows & columns \t:\t");scanf("%d %d", pr,pc);printf("\n Enter values into matrix");for(i=0;i<*pr;i++){for(j=0;j<*pc;j++){scanf("%d", (*(a+i)+j));}}for(i=0;i<*pr;i++){for(j=0;j<*pc;j++)

Page 64: C language for Semester Exams for Engineers

{printf("%3d", *(*(a+i)+j));}printf("\n");}getch();}

STRUCTURES

Structure is a user defined data type. A structure is a collection of variables that isreferenced under a single name. A structure contains a number of data types grouped together. These data types may or may not be of the same type.

Definition of a structure: - Structure is a collection of variables which are of dissimilar data types.Declaring a structure:-

struct <structure name>{structure element 1;structure element 2;---structure element n;};structure variables;

Ex:- struct book { int pages; char author[20]; float price; }a,b,c;

The above declaration states that struct is a keyword which is called as a data type in variables is declared which are of different data types.In the above declaration book is called Tag name and pages, Author, price are called as data members of the structure.

Declaring a variable for a structureEx:- Student S1;Here, b1 is a variable of a structure to which we can give 3 details.The data members of the structure are called by the variable using ( . ) operator.For example:- S1.sno = 1;

S1.name = kittu; S1.marks= 500;

Page 65: C language for Semester Exams for Engineers

Features of a structure:- With the help of structure we can maintain a data in a systematic order. We can handle a structure within a structure. And also we can call the structure variable through functions and Arrays also can be implemented through structures. Pointer to structure is also possible.

1) Write a program to initialize the structure variable and print them.

# include <stdio.h># include <conio.h>void main( ){struct student{ int sno; char name[20]; int tot;};struct student s={1,"kittu",500};clrscr( );printf("\n the struct values are ");printf("\n %d %s %d ",s.sno,s.name,s.tot);getch( );

}

Note:- In the above program student is the name of the structure. sno,name,tot are the members of the structure. 's' is the structure variable.

2) Write a program to take the values of structure elements and displaythem back.

#include<stdio.h>#include<conio.h>main( ){struct employee{

int emp_id;char emp_name[20];float emp_sal;

};clrscr( );struct employee e1;printf(“\n Enter employee id no, employee name & employee

salary”);scanf(“%d %s %f”, &e1.emp_id, e1.emp_name, &e1.emp_sal);printf(“\n Employee Id no = %d”, e1.emp_id);printf(“\n Employee name = %s”, e1.emp_name);printf(“\n Employee salary = %f”, e1.emp_sal);

Page 66: C language for Semester Exams for Engineers

getch( );}

Structures & Arrays

1) Write a program to print more details using array of structures.

#include<stdio.h>#include<conio.h>Void main( ){

int i;struct student

{int sno;char sname[20];

};struct student s[5];for(i=0;i<5;i++)

{printf(“Enter student number”);scanf(“%d”, &s[i].sno);printf(”Enter student name”);scanf(“%s”, s[i].sname);

}clrscr( );for(i=0;i<5;i++)

{printf(“Student number is %d \n”, s[i].sno);printf(“Student name is %s \n”, s[i].sname);

}getch( );

}

Nested structures

1) Example program for nested structures

# include <stdio.h># include <conio.h>void main( ){

struct address

Page 67: C language for Semester Exams for Engineers

{char phone[15];char city[15];long pin;

};struct emp

{char name[10];struct address a;

};struct emp e={"Naveen","55353434","hyderabad",500010};clrscr( );printf("\n %s %s %s %ld",e.name, e.a.phone, e.a.city, e.a.pin);getch( );

}

2) Example program for nested structures

# include <stdio.h># include <conio.h>void main( ){

struct address{ char phone[15]; char city[15]; long pin;

};struct emp

{ char name[20]; struct address a;

};struct emp e;clrscr( );printf("\n Enter emp name ");scanf("%s", e.name);printf("\n Enter emp phone no ");scanf("%s", e.a.phone);printf("\n Enter emp city ");scanf("%s", e.a.city);printf("\n Enter pin code ");scanf("%ld",&e.a.pin);printf("\n %s %s %s %ld",e.name,e.a.phone,e.a.city,e.a.pin);getch( );

}

Page 68: C language for Semester Exams for Engineers

Structures & pointers

3) Example program for pointer to a structure

# include <stdio.h># include <conio.h>void main( ){

struct student{

int sno;char name[20];int total;

};struct student a,*ptr;clrscr( );ptr=&a;printf("\n Enter student number ");scanf("%d",&a.sno);printf("\n Enter student name ");scanf("%s",a.name);printf("\n Enter student marks ");scanf("%d",&a.total);printf("\n the size of a is %d",sizeof(a));printf("\n the size of ptr is %d",sizeof(ptr));printf("\n The address of a is %u",&a);printf("\n The address of sno is %u the value is %d",&a.sno,a.sno);printf("\n The address of name is %u the value is %s",a.name,a.name);printf("\n The address of total is %u the value is %d",&a.total,a.total);printf("\n Student number is %d",ptr->sno);printf("\n Student name is %s",ptr->name);printf("\n Student marks %d",ptr->total);getch( );

}

4) Example program for displaying the address of a struct variable

# include <stdio.h># include <conio.h>void main( ){

struct student{

Page 69: C language for Semester Exams for Engineers

int sno;char name[20];int total;

};struct student a;clrscr( );printf("\n Enter student details ");printf("\nEnter student no ");scanf("%d",&a.sno);printf(" Enter student name ");scanf("%s",a.name);printf(" Enter student marks ");scanf("%d",&a.total);printf("\n The address of a is %u",&a);printf("\n The address of sno is %u the value is %d",&a.sno,a.sno);printf("\n The address of name is %u the value is %s",a.name,a.name);printf("\n The address of total is %u the value is %d",&a.total,a.total);getch( );

}

Structures & Functions

1) Example program for passing the struct values individually into a function and display them in the function

# include <stdio.h># include <conio.h>void main( ){

struct student{ int sno; char name[20]; int total;

};struct student a;void display(int,char[],int);clrscr( );printf("\n Enter student details ");printf("\nEnter student no ");scanf("%d",&a.sno);printf(" Enter student name ");

Page 70: C language for Semester Exams for Engineers

scanf("%s",a.name);printf(" Enter student marks ");scanf("%d",&a.total);display(a.sno,a.name,a.total);getch( );

}void display(int no, char n[],int tot)

{printf("\n Student no is %d",no);printf("\n Student name is %s",n);printf("\n Student total is %d ",tot);

}

2) Example program for passing a struct variable into a function

# include <stdio.h># include <conio.h>struct student{ int sno; char name[20]; int total;

};void main( )

{struct student a;void display(struct student);clrscr( );printf("\n Enter student details ");printf("\nEnter student no ");scanf("%d",&a.sno);printf("\n Enter student name ");scanf("%s",a.name);printf("\n Enter student total marks ");scanf("%d",&a.total);display(a);getch( );

}void display(struct student b)

{printf("\n Student no is %d",b.sno);printf("\n Student name is %s",b.name);printf("\n Student total is %d ",b.total);

}

Note:- If we write the structure definition out side of main( ), then that is treated as a global structure, we can declare variables of this type in all functions throughout the program.

Page 71: C language for Semester Exams for Engineers

Structure sorting

1) Write a program using structure sorting.

# include <stdio.h># include <conio.h># include <string.h>void main( ){

char name[20],ch,tmp;int i,j,len;clrscr( );printf("\n Enter a string ");scanf("%s",name);len=strlen(name);for(i=0;i<len;i++)for(j=i+1;j<len;j++)if(name[j]<name[i])

{ tmp=name[i]; name[i]=name[j]; name[j]=tmp;

}printf("\n the result is %s",name);getch( );

}