SlideShare a Scribd company logo
1 of 71
Download to read offline
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.
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 use
2. Easy to locate and correct errors
3. Easier to modify
4. No worry about addresses
5. 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 interpreter
Compiler 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.
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 C
1. Portability or machine independent
2. Sound and versatile language
3. Fast program execution.
4. An extendible language.
5. Tends to be a structured language.
Historical developments of C
Year Language Developed by Remarks
1960 ALGOL International committee Too general, too
abstract
1963 CPL Cambridge University Hard to learn, difficult
to implement
1967 BCPL Martin Richards at
Cambridge university
Could 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)
< 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 characters
These 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.
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 variables
2. Float variables
3. Single character variables
4. 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 const
default do double else continue
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedof union unsigned void
volatile while
Data types
Data type Range Bytes Format
signed char -128 to +127 1 %c
unsigned char 0 to 255 1 %c
short signed int -32,768 to +32,767 2 %d
short unsigned int 0 to 65,535 2 %u
long signed int -2147483648 to +2147483647 4 %ld
long unsigned int 0 to 4294967295 4 %lu
Float -3.4e38 to +3.4e38 4 %f
Double -1.7e308 to +1.7e308 8 %lf
long 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
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 functions
main( )
{
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:
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 C
Course name : ‘C’
lang
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);
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 valuet:");
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;
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”);
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 operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or decrement operators
6. Conditional operators
 Arithmetic Operators
Arithmetic 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%b
Ex: a=10, b=3
a+b = 10+3 =13
a-b = 10 - 3 = 7
a*b = 10 * 3 =30
a/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.
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
to
a>=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 Table
Expression1 &&
Expression2
Result
T T T
T F F
F T F
F 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 Table
Expression1 || Expression2 Result
T T T
T F T
F T T
F 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
T F
F 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 operator
2) -- 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”)
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( );
}
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>
#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( );
}
Conditional statements
 Conditional statements:- The statements which are executed according to
some condition are called as conditional statements.
 If
Statement: 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-else
Syntax:
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-else
Statement:- 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;
}
else
if(condition2)
{
statement2;
}
else
{
statement3;
}
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”);
}
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);
}
else
if(b<c)
{
printf(“n %d is the least value”, b);
}
else
{
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 statement
It is used to exit from a looping statement. We can use this in for, while , do
while, and switch statement.
Ex:- break;
Switch case
Syntax: switch(expression)
{
case 1:
{
}
break;
case 2:
{
}
break;
default:
{
}
}
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;
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;
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++)
{
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 loop
2) Do while loop
3) For loop
4) 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.
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( )
{
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( );
}
7
4) 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;
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.
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.
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)
{
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>
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++)
{
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 %dn",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++)
{
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 2
3 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);
}
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 2
1
#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 2
1
#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”);
}
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");
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
}
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);
}
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++)
{
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
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 arrays
2) 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 array
Syntax:- 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>
#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]);
}
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]);
}
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 display
them.
#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++)
{
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”);
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( );
}
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();
}
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 th
e 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 string
Syntax:- 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.
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>
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);
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
using
Ascii 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]));
i++;
}
getch( );
}
Functions
FUNCTION
A function is a set of statements that performs a specific task. Functions are 2 types
1) Pre defined functions or Standard functions
2) 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
Function
Heading
Block of
Code
Return
Statement
Return
Type
Function
Name
Specification of
Parameters
Formal
Parameter
Actual
Parameter
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 Prototype
It 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 Function
From 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;
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);
}
}
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)
{
if(a>b&&a>c)
{
return a;
}
else
if(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( );
}
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;
else
f=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)
return 1;
else
s=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( )
{
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 declaration
Ex:- 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
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( );
}
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=a
pb=&b; // *pb=b
pc=&c; // *pc=c
*pa=20;
*pb=30;
*pc=*pa+*pb;
printf(“C = %d”, *pc);
getch ( );
}
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);
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
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=r
pc=&c; //*pc=c
printf("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++)
{
printf("%3d", *(*(a+i)+j));
}
printf("n");
}
getch();
}
STRUCTURES
Structure is a user defined data type. A structure is a collection of variables that is
referenced 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 structure
Ex:- 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;
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 display
them 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);
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
{
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( );
}
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
{
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 ");
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.
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( );
}

More Related Content

What's hot

Compiler vs interpreter
Compiler vs interpreterCompiler vs interpreter
Compiler vs interpreterParas Patel
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming languagesanjay joshi
 
Program & language generation
Program & language generationProgram & language generation
Program & language generationBuxoo Abdullah
 
A classification of programing languages
A classification of programing languagesA classification of programing languages
A classification of programing languagesom collins
 
4 evolution-of-programming-languages
4 evolution-of-programming-languages4 evolution-of-programming-languages
4 evolution-of-programming-languagesRohit Shrivastava
 
2. operators in c
2. operators in c2. operators in c
2. operators in camar kakde
 
C++ language basic
C++ language basicC++ language basic
C++ language basicWaqar Younis
 
C programming presentation for university
C programming presentation for universityC programming presentation for university
C programming presentation for universitySheikh Monirul Hasan
 
Techniques & applications of Compiler
Techniques & applications of CompilerTechniques & applications of Compiler
Techniques & applications of CompilerPreethi AKNR
 
Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentationfazli khaliq
 
Bootstrapping in Compiler
Bootstrapping in CompilerBootstrapping in Compiler
Bootstrapping in CompilerAkhil Kaushik
 

What's hot (20)

C program
C programC program
C program
 
Compiler vs interpreter
Compiler vs interpreterCompiler vs interpreter
Compiler vs interpreter
 
Computer programming
Computer programmingComputer programming
Computer programming
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
 
Lecture 1- History of C Programming
Lecture 1- History of C Programming Lecture 1- History of C Programming
Lecture 1- History of C Programming
 
Features of c
Features of cFeatures of c
Features of c
 
History of c
History of cHistory of c
History of c
 
Computer Languages.
Computer Languages.Computer Languages.
Computer Languages.
 
Program & language generation
Program & language generationProgram & language generation
Program & language generation
 
A classification of programing languages
A classification of programing languagesA classification of programing languages
A classification of programing languages
 
Interpreter
InterpreterInterpreter
Interpreter
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
4 evolution-of-programming-languages
4 evolution-of-programming-languages4 evolution-of-programming-languages
4 evolution-of-programming-languages
 
2. operators in c
2. operators in c2. operators in c
2. operators in c
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
C programming presentation for university
C programming presentation for universityC programming presentation for university
C programming presentation for university
 
Techniques & applications of Compiler
Techniques & applications of CompilerTechniques & applications of Compiler
Techniques & applications of Compiler
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentation
 
Bootstrapping in Compiler
Bootstrapping in CompilerBootstrapping in Compiler
Bootstrapping in Compiler
 

Viewers also liked

Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Appili Vamsi Krishna
 
BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015Appili Vamsi Krishna
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and unionAppili Vamsi Krishna
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing TechniquesAppili Vamsi Krishna
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programmingAppili Vamsi Krishna
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Planers machine
Planers machinePlaners machine
Planers machineBilalwahla
 
Conventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningConventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningonlinemetallurgy.com
 

Viewers also liked (12)

Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and union
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programming
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Planers machine
Planers machinePlaners machine
Planers machine
 
Conventional machining vs. non conventional machining
Conventional machining vs. non conventional machiningConventional machining vs. non conventional machining
Conventional machining vs. non conventional machining
 

Similar to C language for Semester Exams for Engineers

Similar to C language for Semester Exams for Engineers (20)

C Lang notes.ppt
C Lang notes.pptC Lang notes.ppt
C Lang notes.ppt
 
cunit1.pptx
cunit1.pptxcunit1.pptx
cunit1.pptx
 
Msc prev completed
Msc prev completedMsc prev completed
Msc prev completed
 
Msc prev updated
Msc prev updatedMsc prev updated
Msc prev updated
 
C programme presentation
C programme presentationC programme presentation
C programme presentation
 
C_NOTES.pdf
C_NOTES.pdfC_NOTES.pdf
C_NOTES.pdf
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programming
 
C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdf
 
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshu
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshuunit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshu
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshu
 
Unit 1
Unit 1Unit 1
Unit 1
 
SPC Unit 2
SPC Unit 2SPC Unit 2
SPC Unit 2
 
C language
C language C language
C language
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
C notes
C notesC notes
C notes
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
C language
C languageC language
C language
 
Introduction to Computers Lecture # 12
Introduction to Computers Lecture # 12Introduction to Computers Lecture # 12
Introduction to Computers Lecture # 12
 
C.pdf
C.pdfC.pdf
C.pdf
 
Basics of c
Basics of cBasics of c
Basics of c
 
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
Unit - 1.ppt
 

Recently uploaded

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

C language for Semester Exams for Engineers

  • 1. 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.
  • 2. 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 use 2. Easy to locate and correct errors 3. Easier to modify 4. No worry about addresses 5. 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 interpreter Compiler 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.
  • 3. 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 C 1. Portability or machine independent 2. Sound and versatile language 3. Fast program execution. 4. An extendible language. 5. Tends to be a structured language. Historical developments of C Year Language Developed by Remarks 1960 ALGOL International committee Too general, too abstract 1963 CPL Cambridge University Hard to learn, difficult to implement 1967 BCPL Martin Richards at Cambridge university Could 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)
  • 4. < 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 characters These 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.
  • 5. 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 variables 2. Float variables 3. Single character variables 4. 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 const default do double else continue enum extern float for goto if int long register return short signed sizeof static struct switch typedof union unsigned void volatile while Data types Data type Range Bytes Format signed char -128 to +127 1 %c unsigned char 0 to 255 1 %c short signed int -32,768 to +32,767 2 %d
  • 6. short unsigned int 0 to 65,535 2 %u long signed int -2147483648 to +2147483647 4 %ld long unsigned int 0 to 4294967295 4 %lu Float -3.4e38 to +3.4e38 4 %f Double -1.7e308 to +1.7e308 8 %lf long 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
  • 7. 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 functions main( ) { 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:
  • 8. 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 C Course name : ‘C’ lang
  • 9. 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);
  • 10. 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 valuet:"); 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;
  • 11. 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”);
  • 12. 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 operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment or decrement operators 6. Conditional operators  Arithmetic Operators Arithmetic 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%b Ex: a=10, b=3 a+b = 10+3 =13 a-b = 10 - 3 = 7 a*b = 10 * 3 =30 a/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.
  • 13. 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 to a>=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 Table Expression1 && Expression2 Result T T T T F F F T F F 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 Table Expression1 || Expression2 Result T T T T F T F T T F 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
  • 14. T F F 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 operator 2) -- 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”)
  • 15. 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( ); }
  • 16. 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>
  • 17. #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( ); }
  • 18. Conditional statements  Conditional statements:- The statements which are executed according to some condition are called as conditional statements.  If Statement: 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-else Syntax: 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-else Statement:- 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; } else if(condition2) { statement2; } else { statement3; }
  • 19. 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”); }
  • 20. 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); } else if(b<c) { printf(“n %d is the least value”, b); } else
  • 21. { 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 statement It is used to exit from a looping statement. We can use this in for, while , do while, and switch statement. Ex:- break; Switch case Syntax: switch(expression) { case 1: { } break; case 2: { } break; default: { } }
  • 22. 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;
  • 23. 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;
  • 24. 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++)
  • 25. { 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 loop 2) Do while loop 3) For loop 4) 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.
  • 26. 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( )
  • 27. { 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( ); } 7 4) 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;
  • 28. 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.
  • 29. 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.
  • 30. 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)
  • 31. { 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>
  • 32. 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++) {
  • 33. 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 %dn",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++)
  • 34. { 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 2 3 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);
  • 35. } 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 2 1 #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 2 1 #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”); }
  • 36. 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"); 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
  • 37. } 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);
  • 38. } 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++)
  • 39. { 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
  • 40. 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 arrays 2) 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 array Syntax:- 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>
  • 41. #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]);
  • 42. } 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]);
  • 43. } 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 display them. #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++)
  • 44. { 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”);
  • 45. 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( ); }
  • 46. 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(); }
  • 47. 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 th e 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 string Syntax:- 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.
  • 48. 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>
  • 49. 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);
  • 50. 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 using Ascii 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]));
  • 51. i++; } getch( ); } Functions FUNCTION A function is a set of statements that performs a specific task. Functions are 2 types 1) Pre defined functions or Standard functions 2) 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 Function Heading Block of Code Return Statement Return Type Function Name Specification of Parameters Formal Parameter Actual Parameter
  • 52. 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 Prototype It 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 Function From 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;
  • 53. 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); }
  • 54. } 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) {
  • 55. if(a>b&&a>c) { return a; } else if(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( );
  • 56. } 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; else f=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)
  • 57. return 1; else s=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( ) {
  • 58. 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 declaration Ex:- 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
  • 59. 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( ); }
  • 60. 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=a pb=&b; // *pb=b pc=&c; // *pc=c *pa=20; *pb=30; *pc=*pa+*pb; printf(“C = %d”, *pc); getch ( ); }
  • 61. 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);
  • 62. 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
  • 63. 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=r pc=&c; //*pc=c printf("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++)
  • 64. { printf("%3d", *(*(a+i)+j)); } printf("n"); } getch(); } STRUCTURES Structure is a user defined data type. A structure is a collection of variables that is referenced 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 structure Ex:- 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;
  • 65. 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 display them 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);
  • 66. 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
  • 67. { 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( ); }
  • 68. 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 {
  • 69. 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 ");
  • 70. 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.
  • 71. 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( ); }