Anda di halaman 1dari 74

C Language

Material

INTERNATIONAL SCHOOL OF ADVANCED NETWORKING


Thadala Complex, Opp. Charminar Tea Center, Bhanugudi Jn., Kakinada
Cell: 9177789444, 878989444
C LANGUAGE
Introduction:
 C is one of the foundations for information technology and computer science.
 We use system in Computer architecture, Operating system, Networking communication,
Database, graphics……..etc.,
 C is most commonly use programming language in industries.
 Most of the web browsers and word process are written in c language.
 C language is a base for almost all programming language.
Ex: C++,JAVA,Python,Perl,PHP,Ruby…….etc.,

Generations:
According to c….
 In 1960 ALGOL (Algorithmic language) it is developed by international committer.
 In 1963 CPL(Combined programming language) it is developed by Cambridge university.
 In 1967 BCPL(Basic combined programming language) it is developed by Martin Richard at
Cambridge university.
 In 1970 B language Ken Thomson at AT&T Bell Labs. (American Telephone and Telegraph
Company).
 In 1972 C language was introduced by Dennis Ritche at AT&T Bell Labs .

How C used in other languages:

 C++: C with classes in objects is known as C++.


 JAVA: In java we used in that language like C, C++.
 C#: It is a .net subject in this one of the package class based on c language.
 PHP (Personal home page): In this php we used scripting language is based on c language.
 JAVA Script: In this java script the syntax is same as c language.

Applications of C:
1. OS (operating Systems): These are like UNIX, Linux, window XP……etc…. In this operating
systems are used in c coding.
2. ES (Embedded System): These are nothing but the combination of software and hardware
is known as c in embedded systems.
Ex: TV remote controls, ticket printing machines,…..etc.,
3. DD (Device Drivers): Software we can use for devices. In this device driver it stores
audios/videos configuration etc….,
Ex: printer, scanner, camera, Bluetooth etc.,
4. Compiler: These are nothing but the apps to check the errors in program
Ex: C language, C++, java…compilers
5. Text editors: These are the nothing but the ribbons in MS office and in other software.
Ex: Notepad, Word document,

Levels of language:
They are 3 types of levels of language.

 High level language: It is a user understandable level of language.


Ex: A,B,C,D,a,b,c….,
 Middle level language: It is the language of ASCII (American Standard Coding for
Information Interchange) and the middle language is also known as C language.
Ex: a-97, A-65, B-66, C-67…..etc…,
 Low level language: It is nothing but machine language and it is system understandable
language, also called Binary language.
Ex: 65 – 1000001.

C Tokens:
Character sets: These are nothing but the set of alphabets; letters and some special
characters that are valid in c language.
Alphabets:
Upper Case: A to Z
Lower Case: a to z
Specials Characters: These are the special characters are ~,!,@,#,$,%,^,&,*,(,),_,
,+,=,|,\,{,},[,],:,;,”,’,<,>,,,.,?,/.

Key Words:
These are the reserved words used in programing, each key word has a fixed meaning that
cannot be changed.

1. Auto
2. Break
3. Case
4. Char
5. Const
6. Continue
7. Default
8. Do
9. Double
10. Else
11. Enum
12. Extern
13. Float
14. for
15. Goto
16. If
17. Int
18. Long
19. Register
20. Return
21. Short
22. Signed
23. Size of
24. Static
25. Struct
26. Switch
27. Typedef
28. Union
29. Unsigned
30. Void
31. Volatile
32. While

Input and Output functions:


Input function: scanf(“-----“); it is an input function. This is the function which can be used to
read an input from the command prompt.
Output function: printf(“-----“); it is a output function. This is the function which can be used to
write the function an output from the command prompt.

STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:


Below are the steps to be followed for any C program to create and get the output. This is
common to all C program and there is no exception whether it’s a very small C program or very
large C program.

1. Create
2. Compile
3. Execute or Run
4. Get the Output

KEY POINTS TO REMEMBER IN C PROGRAMING BASICS:

1. C programming is a case sensitive programming language. Only lowercase letters are


used in C language, because the ASCII values are different for lower case and upper case
letters.
2. Each C programming statement is ended with semicolon (;) which are referred as
statement terminator.
Dev C++ shortcuts:
Ctrl N ------ new file
Ctrl A -----------select all
Ctrl V--------------paste
Ctrl Z---------------undo
Ctrl Y---------------redo
Ctrl S---------------save
F9-------------compile (to check for errors)
F10----------Run (to see the output)
F11----------Compile and Run at a time
Sample Program Syntax:
#include<stdio.h>
#include<conio.h>
main()
{
printf(“my name is ISAN”);
getch();
}

 # Preprocessor directive.
 include- It is a folder.
 stdio.h – Standard input output.header. It can store the printf & scanf functions.
 conio.h --- console input output.header. It can store clrscr and getch commands.
 main()- Heart of the program.
 Getch ---- get the character., clrscr ---- clear the screen

C – Data Types

1. C data types are defined as the data storage format that a variable can store a data to
perform a specific operation.
2. Data types are used to define a variable before to use in a program.
3. Size of variable, constant and array are determined by data types.
Types Data Types
Basic data types int, char, float, double
Enumeration data type enum
Derived data type pointer, array, structure, union
Void data type void
Data types: There are 4 types and their formats are:

 Int (0 to 9) %d
 Float (decimal value) %f
 Char (A to Z or a to z) %c
 Double (big decimal values) %lf

Identifiers:
An identifier is a string of alphanumeric characters that begins with an alphabetic character or
an underscore character that are used to represent various programming elements such as
variables, functions, arrays, structures, unions and so on.
Ex: int a=20;
Variables and Constants:
Variables are 2 types.
1. Local variables: In this int a is written in the main function and always checks the main
function itself.
2. Global variables: But in this global variable int a will be declared outside of the main
function.

Examples:
#include<stdio.h>
#include<conio.h>
int a=25; Global variable
main()
{
int a=25; Local variable
printf(“a=%d”,a);
getch( );
}
Constants:
Constants are 2 types.

1. Numerical
2. Character

Numerical: Character:
Int  (0-9) Single  ‘A’
Float  0.1, 0.2------- String  “Name”
Escape sequences:

1. \n  new line
2. \t  tab space
3. //  double slash (to block a single line)
4. /*……….*/  to block some more lines
Sample program of escape sequences:
#include<stdio.h>
#include<conio.h>
main()
{
printf("My name is ISAN \n");
printf("\t\t ISAN \n");
//printf("\t\t ISAN \n");
/*printf("\t\t I am in kakinada\n");*/
getch();
}
Sample programs of without scanf in Data types:

Int: Float:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=20; float a=2.25;
printf("the value of a is %d",a); printf("the value of a is %f",a);
} }

Char: Double:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
char a='X'; double a=24536996546978678;
printf("the value of a is %c",a); printf("the value of a is %lf",a);
} }
Write all data types in a single program without scanf

Sample programs of with scanf in Data types:


Int: Float:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a; float a;
printf("Enter the value of a \n"); printf("Enter the value of a \n");
scanf("%d",&a); scanf("%f",&a);
printf("the value of a is %d",a); printf("the value of a is %f",a);
} }
Char: Double:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
char a; double a;
printf("Enter the value of a \n"); printf("Enter the value of a \n");
scanf("%c",&a); scanf("%lf",&a);
printf("the value of a is %c",a); printf("the value of a is %lf",a);
} }

Write all data types in a single program with scanf

Operators
An operator is a symbol that else the compiler to perform specific mathematical, logical
operations and C language is which inbuilt in the operation and provides the following types of
operators. C language offers many types of operators. These are
 Arithmetic Operators
 Assignment Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Conditional operator (ternary operator)
 Increment/ decrement operator
 Special operator
Arithmetic operators:
+  addition  a+b , -  subtraction  a-b , *  multiplication  a*b ,
/  division  a/b , %  modulus  a%b

Write a program of using addition operator:


Model 1: (Without using scanf) Model 2 :( using scanf)
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=10,b=20,c; int a,b,c;
c=a+b; printf("enter the two values is:");
printf("the value of c is %d \n",c); scanf("%d %d",&a,&b);
} c=a+b;
printf("the value c is %d \n",c);
}
Model 3: (Without using extra variables) (Without extra variable in with scanf)
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=15,b=20; int r,h;
printf("%d+%d=%d",a,b,a+b); printf("enter the value of r and h is \n");
} scanf("%d %d",&r,&h);
printf("%d + %d = %d",r,h,r+h);
}
Write a program of using Subtraction operator:

Model 1:(using scanf) Model 2: (Without using scanf)


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a,b,c; int a=10,b=20,c;
printf("enter the two values is:"); c=a-b;
scanf("%d %d",&a,&b); printf("the value of c is %d \n",c);
c=a-b; }
printf("the value c is %d \n",c);
}

Model 3: (Without using extra variables) Model 4:(Without extra variable with
#include<stdio.h> scanf)
#include<conio.h> #include<stdio.h>
main() #include<conio.h>
{ main()
int a=15,b=20; {
printf("%d-%d=%d",a,b,a-b); int r,h;
} printf("enter the value of r and h is \n");
scanf("%d %d",&r,&h);
printf("%d - %d = %d",r,h,r-h);
}
Write a program of using multiplication operator:

Model 1:(using scanf) Model 2: ( Without using scanf)


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a,b,c; int a=10,b=20,c;
printf("enter the two values is:"); c=a*b;
scanf("%d %d",&a,&b); printf("the value of c is %d \n",c);
c=a*b; }
printf("the value c is %d \n",c);
}

Model 3: (Without using extra variables) Model 4:(Without extra variable with
#include<stdio.h> scanf)
#include<conio.h> #include<stdio.h>
main() #include<conio.h>
{ main()
int a=15,b=20; {
printf("%d*%d=%d",a,b,a*b); int r,h;
} printf("enter the value of r and h is \n");
scanf("%d %d",&r,&h);
printf("%d * %d = %d",r,h,r*h);
}
Write a program of using division operator:

Model 1:(using scanf) Model 2: ( Without using scanf)


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
float a,b,c; float a=10,b=20,c;
printf("enter the two values is:"); c=a/b;
scanf("%f %f",&a,&b); printf("the value of c is %f \n",c);
c=a/b; }
printf("the value c is %f \n",c);
}

Model 3: (Without using extra variables) Model 4:(Without extra variable with
scanf)
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
float a=15,b=20; int r,h;
printf("%f/%f=%f",a,b,a/b); printf("enter the value of r and h is \n");
} scanf("%d %d",&r,&h);
printf("%d / %d = %d",r,h,r/h);
}
Write a program of using Modulus operator:

Model 1:(using scanf) Model 2: (Without using scanf)


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a,b,c; int a=30,b=15,c;
printf("enter the two values is:"); c=a%b;
scanf("%d %d",&a,&b); printf("the value of c is %d \n",c);
c=a%b; }
printf("the value c is %d \n",c);
}

Model 3: (Without using extra variables) Model 4:(Without extra variable with
#include<stdio.h> scanf)
#include<conio.h> #include<stdio.h>
main() #include<conio.h>
{ main()
int a=15,b=10; {
printf("%d %% %d=%d",a,b,a%b); int r,h;
} printf("enter the value of r and h is \n");
scanf("%d %d",&r,&h);
printf("%d %% %d = %d",r,h,r%h);
}

Write a program of all arithmetic operators using scanf.


Assignment operators:
Operator Example Explanation
Simple ass opr (=) sum=10 10 is assigned to variable sum
Compound ass opr (+=) sum+=10 This is same as sum=sum+=10
(-=) sum-=10 This is same as sum=sum-=10
(*=) sum*=10 This is same as sum=sum*=10
(/=) sum/=10 This is same as sum=sum/=10
(%=) sum%=10 This is same as sum=sum%=10

Write a sample program of assignment operators with out scanf:

#include<stdio.h>
#include<conio.h>
main()
{
int a=10,b;
b=a;
printf("b=%d\n",b);
b+=a;
printf("b=%d\n",b);
b-=a;
printf("b=%d\n",b);
b*=a;
printf("b=%d\n",b);
b/=a;
printf("b=%d\n",b);
b%=a;
printf("b=%f\n",b);
}
Conditional operators:
It returns one value if condition is true and return another value if condition is false.
Syntax: (condition)?T:F

Write a program of conditional operator:


#include<stdio.h>
#include<conio.h>
main()
{
int a=10,b=20,c,d;
c=(a==b)?1:0;
d=(a!=b)?1:0;
printf("c=%d \n",c);
printf("d=%d \n",d);
}

For practice:
Write a sample program of conditional operators with scanf

Relational operators:
Operator Example Description
“>” X>Y X is greater than Y
“<” X<Y X is less than Y
“>=” X>=Y X is greater than or equal to Y
“<=” X<=Y X is less than or equal to Y
“==” X==Y X is equal to Y
“!=” X!=Y X is not equal to Y

Write a program of relational operator:


#include<stdio.h>
#include<conio.h>
main()
{
int a=10,b=20,c,d,e,f,g,h;
c=a<b;
d=a>b;
e=a<=b;
f=a>=b;
g=a==b;
h=a!=b;
printf("c=%d\n d=%d\n e=%d\n f=%d\n g=%d\n h=%d\n",c,d,e,f,g,h);
}
Write a program of relational operator:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d>%d=%d\n",a,b,(a>b));
printf("%d<%d=%d\n",a,b,(a<b));
printf("%d>=%d=%d\n",a,b,(a>=b));
printf("%d<=%d=%d\n",a,b,(a<=b));
printf("%d==%d=%d\n",a,b,(a==b));
printf("%d!=%d=%d\n",a,b,(a!=b));
getch();
}

Increment & Decrement operator:


These operators are used for either Increment or decrement the value by 1.
In increment and decrement operator are two types:
Post fix(variable ++,variable --)
Pre fix(++variable,--variable)
Write a program of post operator:
Example 1: Example 2:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=5; int a=5;
printf("a is %d \n",a++); printf("a is %d \n",a--);
printf("the value of a is %d \n",a); printf("the value of a is %d \n",a);
} }

Write a program of pre fix operator:


Example 1: Example 2:
#include<stdio.h> #include<conio.h> #include<stdio.h> #include<conio.h>
main() main()
{ {
int a=5; int a=5;
printf("a is %d \n",++a); printf("a is %d \n",--a);
} printf("the value of a is %d",a);
}
Logical operator:
Operator Name Example Description
&& Logical AND (x>5)&(y<5) It returns true when both condition are true.
|| Logical OR (x>5)|(y<5) It returns true when at least condition is true.
! Logical NOT !((x>5)&(y<5)) It reverse the state of the operand
If “!((x>5)&&(y<5))” is true, logical NOT
operator makes it false.
Write a sample program of logical operator: X Y X&Y X|Y
#include<stdio.h> 0 0 0 0
#include<conio.h> 0 1 0 1
main() 1 0 0 1
{ 1 1 1 1
int a=20,b=30,c,d,e;
c=(a<b)&(a>b);
d=(a<b)|(a>b);
e=!((a<b)&(a>b));
printf("c=%d \n",c);
printf("d=%d \n",d);
printf("e=%d \n",e);
}

For practice:
Write a sample program of logical operators with output values

Special operator:
This operators are ,,*,&,,.,sizeof();………….,
Sizeof(); :

Data types 16 bit 32 bit 64 bit


Int 2 4 8
Float 4 4 4
Char 1 1 1
Double 8 8 8

Write a sample program of sizeof(); operators:


#include<stdio.h>
#include<conio.h>
main()
{
int a;
float b;
char c;
double d;
printf("the int size is %d \n",sizeof(a));
printf("the float size is %d \n",sizeof(b));
printf("the char size is %d \n",sizeof(c));
printf("the double size is %d \n",sizeof(d));
//printf("int=%d\nfloat=%d\nchar=%d\ndouble=%d\n",sizeof(a),sizeof(b),sizeof(c),sizeof(d);
}

Bit wise operators:


These operators are used to perform bit wise operators decimal values are converted in to
binary values which are and bit wise operators is work on bits.

Bit wise operators in C are &-AND, |-OR, ^- XOR, ~- NOT, <<- left shift, >>- 0 shift.

Operator symbols Operator name


X Y X&Y X|Y X^Y
& Bit wise AND
0 0 0 0 0
| Bit wise OR
0 1 0 1 1
^ Bit wise XOR
1 0 0 1 1
~ Bit wise NOT
1 1 1 1 0
>> Right shift
<< Left shift
Binary values: Ex: 98

64 32 16 8 4 2 1
1 1 0 0 0 1 0
For practice:
Convert 25 , 40 into binary values and write all bitwise values
Write a program of bit wise operators:
AND operators: OR operators:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=25,b=40; int a=25,b=40;
printf("the AND operator a&b=%d printf("the OR operator a|b=%d\n",a|b);
\n",a&b); }
}

XOR operators: NOT operators:


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=25,b=40; int a=25;
printf("the XOR operator a^b=%d\n",a^b); printf("the NOT operator ~a=%d\n",~a);
} }

Left shift: Right Shift:


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int a=40 ; int a=40 ;
printf("the << operator a<<1=%d\n",a<<1); printf("the >> operator a>>1=%d\n",a>>1);
} }

For practice:
Write a sample program of all bitwise operators with scanf
Predicate table:
Write a sample program of Predicate table:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
a=5+2*6-2+6/3-4+2*5/2;
printf("the value of a is %d \n",a);
}

Expressions:

1. These symbols used to perform logical and mathematical expression in a c programming


are called as operator expression.
2. These c operators join individual constant and variables to form expressions.
3. Operators function constants and variables are combine together to perform
expressions.
4. Consider the expressions as a+b*5; Here *,+ symbols is a expression a, b is a variables
and 5 is a constant this combination is called a expression.

Sample program:
#include<stdio.h>
#include<conio.h>
main()
{
int a=2, b=3,c;
c=a+b*5;
printf(“the value of c is %d \n “, c);
}
Type casting and type conversion:
If it is type casting in program is used to modifies a variables from new data types should
be mentioned before a variable name and values in “()” it known as type conversion.

Write a sample program of type casting and type conversion:


Example 1:
#include<stdio.h>
#include<conio.h>
main()
{
float x;
x=(float)20/8;
printf("the value of x is %f \n",x);
}
Example 2:

#include<stdio.h>

#include<conio.h>

main()

int a;

a=(int)10.12/4.52;

printf("a is %d",a);

}
LOOPS
A loop in programming comes into use when we need to repeatedly execute a block of
statements.
Loops are three types. They are

 Decision control loop (if, else, nested if else)


 Loop control statements (for, while, do while)
 Case control statements or Jump controls statements (switch, break, continue, goto)

Decision controls loops:


In this statements we have if, if else, nested if else., statements In these statements, groups of
statements are executed where condition becomes true. If condition false then else statements
will be printed.
IF statements:
In this statements check whether the condition and text expression inside parenthesis “()” is
true are not. If the text expression is true statements inside the condition is executed. If it is
false it ignores.
Syntax:
if(expression)
{
Stmts;
}
Write a sample program of if statements:
Example 1:
#include<stdio.h>
#include<conio.h>
main()
{
int a=10,b=20;
if(a==b)
{
printf("condition is satisfied");
}
getch();
}
For practice:
Write a sample program of if using different conditions and see the output

If_else statements:
In this statements when the if condition becomes false then the else part is printed. When the
if condition is true then the else part is not printed.
Syntax:
if(condition)
{
Stmts;
}
Else
{
Stmts;
}
Write a sample program of if else statements:
Example 1:
#include<stdio.h>
#include<conio.h>
main()
{
int a=10,b=20;
if(a==b)
{
printf("condition is satisfied");
}
else
{
printf("not satisfied");
}
}
For practice:
Write a sample program of if else using different conditions and see the output

Nested if_ else statements:

In this statements if condition one is false then the condition two is checked and statements are
executed if it is true. When condition two is also false then else part will be executed.
Syntax:
if(condition)
{
Stmts;
}
else if(condition)
{
Stmts;
}
else
{
Stmts;
}

Write a sample program of nested_if_else program:


#include<stdio.h>
#include<conio.h>
main()
{
int a=10,b=20;
if (a==b)
{
printf("condition 1 is satisfied");
}
else if (a!=b)
{
printf("condition 2 is satisfied");
}
else
{
printf("not satisfied");
}
}
For practice:
Write a sample program to check even or odd number

Loop control statements:


In this statements in c are used to perform looping operation until the given condition is
true. Control comes out of the loop statements once condition becomes false. In this loop
control statements are 3 types.
for loop
while loop
do while loop
For loop:
In this statements loop is executed and until condition becomes false.
Syntax:
for(exp 1:exp 2:exp 3)
{
Stmts;
}
Write a sample program of for loop:
Example 1:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
for(a=20;a>10;a--)
{
printf("%d \n",a);
}
}
For practice:
Write a sample program with for loop using different operator
Write a sample program to print squares of numbers from 1 to 10

While loop : In this statements loop is executed until condition becomes false.
Syntax:
while(condition)
{
Stmts;
Increments or decrements;
}
Write a sample program of while loop program:
Example 1:
#include<stdio.h> Example 2(even numbers)
#include<conio.h> #include<stdio.h>
main() #include<conio.h>
{ main()
int i=1; {
while(i<10) int i=1;
{ while(i<=10)
printf("%d \n",i); {
i++; printf("%d \n",i*2);
} i++;
} }
}

Do while loop:

In this loop is executed for the first time it ignores the condition after execution of the while
loop for the first time the condition will be checked.
Syntax:
do
{
Stmts;
Increment or decrement;
}
while(condition)
Write a sample program of do while loop:
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
do
{
printf("%d \n",i);
i++;
}
while(i<=10);
}

Case control statements:


In these statements which are used to execute only specific block of statements is a
series of block are called case control statements.
Switch case
break
continue
goto

Switch case: In these statements which are used to execute only specific block of statements is
a series of block are called case control statements.
Syntax:
Switch(condition)
{
Case 1:stmts;
Case 2:stmts;
Case 3:stmts;
--------
--------
default: stmts;
}
Break case:
It is mainly used in 2 ways in c programming. The first one is used to terminate the loop, the
second one is used for true condition in the switch.
Syntax: break();
Write a sample program using of switch case and break case:
Example 1:
#include<stdio.h>
#include<conio.h>
main()
{
int num;
scanf("%d",&num);
switch(num)
{
case 1:
printf("hello");
break;
case 2:
printf("hai");
break;
case 3:
printf("happy");
break;
case 4:
printf("isan");
break;
default:
printf("none of the above");
}
}
Example 2:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,j;
printf("enter two values \n");
scanf("%d %d",&a,&b);
printf("case 1:Add\n case 2:sub\n case 3:mul\n case 4:div\n case 5:mod\n");
printf("enter the case user want \n");
scanf("%d",&j);
switch(j)
{
case 1:c=a+b;
printf("the value of c is %d \n",c);
break;
case 2:c=a-b;
printf("the value of c is %d \n",c);
break;
case 3:c=a*b;
printf("the value of c is %d \n",c);
break;
case 4:c=a/b;
printf("the value of c is %f \n",c);
break;
case 5:c=a%b;
printf("the value of c is %d \n",c);
break;
default:
printf("there is no values \n");
}
}
Example 3: vowels program
#include<stdio.h>
#include<conio.h>
main()
{
char i;
printf("Enter the charcter \n");
scanf("%c",&i);
switch(i)
{
case 'a':
printf("It is vowel");
break;
case 'e':
printf("It is vowel");
break;
case 'i':
printf("It is vowel");
break;
case 'o':
printf("It is vowel");
break;
case 'u':
printf("It is vowel");
break;
default:
printf("It is not a vowel");
}
}
Continue:
In continue, statements are used to continue the next iteration for loop, while loop and
so that the remaining statements are striked with in the loop for the particle interaction.
Syntax: Continue;
Write a sample program of continue:
#include<stdio.h>
#include<conio.h>
main()
{
int a=15;
do
{
if(a==20)
{
a++;
continue;
}
printf("value of a: %d \n", a);
a++;
}
while(a<25);
}
Goto statements:
In this statements is used to transform the a normal flow a program to specific table program.
Syntax:
goto label
stmts;
stmts;
------
------
label
Write a sample program of goto program:
#include<stdio.h>
#include<conio.h>
main()
{
printf("www.");
goto x;
y:
printf("expert");
goto z;
x:
printf("c programming");
goto y;
z:
printf(".com");
}

Nested loop: a loop with in a loop


#include<stdio.h>
#include<conio.h>
main()
{
int i,j;
for(i=0;i<=5;i++)
{
for(j=0;j<=5;j++)
{
printf("%d",j);
}
printf("\n");
}
}

Arrays
1. An array is a data structure containing no. of data values which have the same type. These
values are knows as elements. It can be individuals sections by their position within the
array.
2. An array is a variable which is capable of holding many values where as that are older
variables can hold a single value at a time.
3. An array is a data structure in c, that can store a fixed size and sequential collection of
elements of same data type.
4. For example if u want to store 10 members then instead of defining 10 variables its easy to
define an array of 10 length.

But array a can store multiple values in a single variables.


In array we have three types:
One dimensional arrays
Two dimensional arrays
 Multi dimensional arrays
Declaration of an array:
Data type array name [array size];
Ex: int ten [10];
One dimensional arrays:
This is a simple kind of array as just One dimensional array. The elements are One
dimensional array of continuously arranged one after another in a single row and columns.
Declaration of an array:
Data type array name [array size];
Ex: int isan[10];
Initialization of One dimensional array:
isan[0]=10; int isan[5];
isan[1]=50; (OR) int isan[5]={10,50,100,150,200};
isan[2]=100;
isan[3]=150;
isan[4]=200;
Sorting elements of an one dimensional array:
a[0] a[1] a[2] a[3] a[4]

10 15 19 20 17

Write a sample program of an one dimensional array:


#include<stdio.h>
main()
{
int a[5]={10,20,30,40,50};
printf("%d\n",a[0]);
printf("%d\n",a[1]);
printf("%d\n",a[2]);
printf("%d\n",a[3]);
printf("%d\n",a[4]);
}
Write a sample program of one dimensional array using for loop:
#include<stdio.h>
#include<conio.h>
main()
{
int i,a[5]={1,2,3,4,5};
for(i=0;i<5;i++)
{
printf("a[%d]=%d \n",i,a[i]);
}
}
For practice :
Write a sample program of one dimensional array using for loop with scanf

Two dimensional array:


When the data is to be stored in the form of a matrix, we use the two dimensional array.
Declaration of two dimensional array:
Data type array name [row size][column size];
Ex: int a[2][2];
Initialization of two dimensional array: int a[2][2]= {10,20,30,40}
a[0][0]=10; a[0][1]=20 ;a[1][0]=30; a[1][1]=40;
The above declaration in two dimensional array consisting of two rows and two columns. So
that total no. of elements are four.
Write a sample program of two dimensional array:
#include<stdio.h>
main()
{
int a[2][2]={1,2,3,4},i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
#include<stdio.h>
main()
{
int a[2][3],i,j;
printf("enter matrix elements\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("the matrix A is\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
For practice :
Write a sample program of two dimensional array without using loops

Multi dimensional arrays:


Sum of two matrices:
#include<stdio.h>
main()
{
int a[2][2]={1,2,3,4},b[2][2]={1,2,3,4},c[2][2],i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%3d",c[i][j]);
}
printf("\n");
}
}
Sum of two matrices using loops:
#include<stdio.h>

#include<conio.h>

main()

int a[2][2],b[2][2],c[2][2],i,j;

printf("Enter array A elements\n");

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

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

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

printf("\nEnter Array B elements\n");

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

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

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

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

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

c[i][j]=a[i][j]+b[i][j];

printf("\nThe addition of two by two matrix is\n");

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

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

printf("%3d",c[i][j]);

printf("\n");

Multiplication of matrices:

#include <stdio.h>
#include<conio.h>
int main()
{
int a[2][2]={1,2,3,4}, b[2][2]={1,2,3,4}, c[2][2]={0,0,0,0}, i, j, k;
for(i=0; i<2; ++i)
{
for(j=0; j<2; ++j)
{
for(k=0; k<2; ++k)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("Output Matrix\n");
for(i=0; i<2; ++i)
{
for(j=0; j<2; ++j)
{
printf("%3d", c[i][j]);
}
printf("\n");
}
getch();
}
For practice :
Write a sample program of multi dimensional array without using loops
Strings
1. Strings are nothing but array of characters and entered with null characters [‘\0’]. This null
character indicates the end of the string.
2. String are always enclosed by (“---”) double equations were as character is enclosed by
string single quotation (‘----‘).

Declaration:
Data type string name [string size];
Ex: char s[10];

Initialization of string:
char s[10]={‘H’,’E’,’L’,’L’,’O’};
char s[6]=”hello”;
char s[]=”hai”;
Difference between above Declarations is when we declare char s[10] 10 bytes memory space is
allocated for holding the string value.
When we declare as s[ ]memory space will be allocated as per the required during for the
program.

Write a sample program of string:


Example 1: Example 2:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<string.h> #include<string.h>
main() main()
{ {
char s1[10]=”hello”; char s1[10]={'h','e','l','l','o'};
printf(“s1=%s \n”,s1); printf("s1=%c \n",s1[0]);
} }
String functions:
 strcat  strlen
 strncat  strupr
 strcpy  strlwr
 strncpy  strrev
 strcmp  strset

String concatenation:
In this function concatenation the position of one string is placed at the end of the other string.
Syntax: strcat(s1,s2);
Write a sample program of String concatenation:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="hello";
char s2[10]="everyone";
strcat(s1,s2);
printf("s1=%s \n",s1);
}
String unconcatenation:
It is also same as String concatenation but it will declare the length of the s1 or s2. So it will
print the length position.
Syntax: strncat(s1,s2,5);
Write a sample program of String unconcatenation:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="hello";
char s2[10]="everyone";
strncat(s1,s2,5);
printf("s1=%s \n",s1);
}
String copy function:
It copies the s1 content to the s2 content. In this s1 content has 30 bytes of memory and s2 has
declared 20 bytes of memory only means. It will only print 20 characters.
Syntax: strcpy(s1,s2);
Write a sample program of String copy function:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="hello";
char s2[10]="lucky";
strcpy(s1,s2);
printf("s1=%s \n",s1);
}
String uncopy function:
In this it will copy the lengthened position which will be mentioned in the function.
Syntax: strncpy(s2,s3,n);
Write a sample program of String uncopy function:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="hello";
char s2[10]="lucky";
strncpy(s1,s2,3);
printf("s1=%s \n",s1);
}
String length:
It will show the length of your given string
Syntax: len=strlen(s);
Write a sample program of string length:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="hello";
int len;
len=strlen(s1);
printf("len=%d \n",len);
}
String reverse:
It reverses the word which is given in a string.
Syntax: strrev(s);
Write a sample program of String reverse:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="apple";
strrev(s1);
printf("s1=%s \n",s1);
}
String lower:
In this string lower it will print the higher level language to the lower level language.
Syntax: strlwr(s);
Write a sample program of String lower:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="HELLO";
strlwr(s1);
printf("s1=%s \n",s1);
}
String upper:
In this function it will change lower case to upper case. Syntax: strupr(s)
Write a sample program of String upper:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="HELLO";
strupr(s1);
printf("s1=%s \n",s1);
}
String compare:
In this function s1 and s2 are same It will print 0. If s1 is less than s2 it will print -1. If s1
is greater than s2 it will print 1.
Write a sample program of String compare:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[10]="apple";
char s2[10]="app";
int x,y,z;
x=strcmp(s1,s2);
y=strcmp(s2,"app");
z=strcmp(s1,"app");
printf("x=%d \n",x);
printf("y=%d \n",y);
printf("z=%d \n",z);
}
String set:
In this program of string “ hello” is said to ‘&’ using string set function and output will be
display like ‘&&&&&’ .
Write a sample program of String set:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s1[7]="orange";
strset(s1,'*');
printf("s1=%s \n",s1);
}

Write a program with all string functions and write the output
Functions
A function is a self contained block or a program of one or more statements that perform a
special task. In this function we have 2 types:
In built function
User defined function

1. In built function: This function is also called as library function. This function cannot be
changed by a user.
Example: Printf(); , Scanf(); ,main()……………
2. User defined function: In this function user can give the unique name to a function and to
create a function by using functional elements.
Example: variables , constants………
3. Uses of function: If we want to perform a task continuously then it is not necessary to
rewrite the program again and again. If we shift the particular statements in a user define
function. So it can be used many no of times.
4. Elements of user define function: They are 3 types:
Declaration function.
Called function.
Define function.
5. Declaration of a function: They are 4 types:
Function type
Function name
Parameter list
Semicolon(;)
6. Function type: They are 2 types:
Return type
Non return type
7. Return type: Int, float, char, double in this it only return one value at a time is known as
return type.
8. Non return type: Void is a non return type. It does not return a any value.
9. Function name: In this function name user can give a name to the function. Ex: int isan( );
10. Parameter list: It means how many inputs user giving or receiving is known as parameter
list. This parameter list we also called as arguments.
11. They are 2 types of parameter lists:
Actual parameter list
Formal parameter list
12. Actual parameter list: The arguments of calling function are known as Actual arguments.
Example: actual(10,20);
13. Formal parameter list: The arguments are called function is known as formal parameter
list but it copies the actual arguments values is also known as formal arguments.
Example: formal(int a, int b)
14. Semicolon: The terminating is used to terminate the function.
15. Function declaration:
int hello( );
int hello(int a,int b);
void hello( );
void hello (int a) ; semicolon

parameter list , arguments

function type function name

16. Called function: In function we have two types:


call function
calling function
17. Call function: This function which is calls the calling function is known as called function.
Example: hello()
18. Calling function: This function receives the called function is known as calling function.
Example: hello();

Syntax:
void name()
{
variables;
stmts;
return type
}
Example:
#include<stdio.h>
#include<conio.h>
void hello()
{
int a=10;
printf(“a=%d \n”, a);
}
main()
{
hello();
hello();
}
Functions are 4 types:

 function with no arguments and no return types


 function with arguments and no return types
 function without arguments function with return types
 function with arguments with return types

Function with no arguments and no return types:


There are the function in which no parameters are passed from calling function to the
called function. In values are return from called function to the calling function.

Write a sample program of Function with no arguments and no return types:


#include<stdio.h>
#include<conio.h>
void sum(); //function declaration
main() //calling function
{
sum(); //function calling statement
}
void sum() //function definition,called function
{
int a=2,b=3,c;
c=a+b;
printf("%d\n",c);
}
Function with arguments without return type:
These are the function in which arguments are passed from calling function to called
function but no values are return from called function to calling function.
Write a sample program of Function with arguments without return type:
#include<stdio.h>
#include<conio.h>
void sum(int a,int b); //function declaration
main() //calling function
{
int a=2,b=3;
sum(a,b); //function calling statement
}
void sum(int a,int b) //function definition,called function
{
int c;
c=a+b;
printf("%d\n",c);
}
Function without arguments function with return types: In this function category no
arguments are passing from calling function to called function but values are a return from
called function to the calling function.
Write a sample program of Function without arguments function with return types:
#include<stdio.h>
#include<conio.h>
int sum(); //function declaration
main() //calling function
{
int x;
x = sum(); //function calling statement
printf("%d\n",x);
}
int sum() //function definition, called function
{
int a=2,b=3,x;
x=a+b;
return(x);
}

Function with arguments with return types:


These are the function in which parameter is passed from calling function to the called
function and values are return from function to be calling function.

Write a sample program of Function with arguments with return types:


#include<stdio.h>
#include<conio.h>
int sum(int a,int b); //function declaration
main() //calling function
{
int a=2,b=3,x;
x = sum(a,b); //function calling statement
printf("%d\n",x);
}
int sum(int a,int b) //function definition,called function
{
int c;
c=a+b;
return(c);
}

Recursion: A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
void recurse( )
{
... .. ...
recurse( );
... .. ...
}
int main( )
{
... .. ...
recurse( );
... .. ...
}

Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int num);
int main()
{
int num, result;
printf("Enter a positive integer: ");
scanf("%d", &num);
result = sum(num);
printf("sum = %d", result);
return 0;
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return 0;
}
Call by value and Call by reference in C

There are two methods to pass the data into the function in C language, i.e., call by value and call by
reference.

Call by Value Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int a, int b);

int main()

int a = 10;

int b = 20;

swap(a,b);

void swap (int a, int b)

int temp;

temp = a;

a=b;

b=temp;
printf("a = %d, b = %d\n",a,b);

Call by reference Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int *a, int *b);

int main()

int a = 10;

int b = 20;

swap(&a,&b);

void swap (int *a, int *b)

int temp;

temp = *a;

*a=*b;

*b=temp;

printf("a = %d, b = %d\n",*a,*b);

}
Storage classes
A function can access a variable when it declared in a specific block other function
outside cannot be accessed. The space of a variable depends upon its storage classes.
They are 4 types:
Auto (Automatic)
External variable
Static variable
Register variable

Automatic variable (auto):


The space of this variable is within the function only it is equantly to local variable all
local variables are auto variable are auto variables by default.

Write a sample program of automatic variable:


#include<stdio.h>
#include<conio.h>
void sai()
{
auto float a=4.2;
printf("%f \n",a);
a++;
}
main()
{
sai();
sai();
}
Static variable:

1. It retains the value of the variable between different function calls.


2. When a variable is defining static it garbage value is removed and it is initialized to null
values.
3. The content store in this variable remains content though out the program.
4. A static variable is initialized only one it can’t be reinitialized.

Write a sample program of static variable:


#include<stdio.h>
#include<conio.h>
void deep()
{
static int a=4;
printf("%d \n",a);
a--;
}
main()
{
deep();
deep();
deep();
}
External variable:
The scope of the variable thought out the program it is the equitant to global variable
definition for external variable may be any were the program.
Write a sample program of external variable:
#include<stdio.h>
#include<conio.h>
sai ()
{
static int a=10;
extern int b;
printf("%d\n",a);
printf("%d\n",b);
}
main()
{
sai ();
}
int b=20;

Register variable:

1. It is also local variable but stored in the memory were as auto variable are stored in the
main memory.
2. Register variable will be accessed very faster the normal variable. Since they are stored in
register memory rather than main memory.
3. But only limited variable can be used as a register memory since it can used register size is
very low.

Write a sample program of external variable:


#include<stdio.h>
#include<conio.h>
main()
{
int num1=10,num2=15;
register int sum;
sum = num1 + num2;
printf("\n Sum of Numbers %d",sum);
}

Pointers
About the pointer:

1. A pointer is a variable that stores the address of another variable. C pointer is used to
allocate memory dynamically that is run time.
2. The pointer variable might be belonging to the data type such as int, float, char, double.
3. Normal variable store the value where as pointer variable stores the address of the variable
4. The content of the ‘C’ pointer always be a whole number that is address.
5. Always c pointer is initialized to null that is “int *p= null”. The null pointer is zero ‘0’.

Reference operator (&) or addresser operator:


If (isan) name is the variable & name is the address of the variable.
Pointer variable are the special type of the variable that holds the memory address
rather than the data that is a variable that holds address value is called a pointer variable.

Addresses of values:
%u (unsigned)
%X (HEXA DECIMAL)
%x (hexa decimal)

a means value of a
&a means address of a
p means pointer value (address)
*p means value of a

Write a sample program of pointers:


#include<stdio.h>
#include<conio.h>
main()
{
int a=10,*p;
p=&a;
printf("a=%d \n",a);
printf("&a=%u \n",&a);
printf("p=%u \n",p);
printf("*p=%d \n",*p);
printf("&p=%u \n",&p);
}
Pointer with two variables
#include<stdio.h>
#include<conio.h>
main()
{
int a=15,b=20,*p,*p1;
p=&a;
p1=&b;
printf("a=%d\nb=%d\n",a,b);
printf("&a=%u\n&b=%u\n",&a,&b);
printf("p=%x\np1=%x\n",p,p1);
printf("*p=%d\n*p1=%d\n",*p,*p1);
printf("&p=%u\n&p1=%u\n",&p,&p1);
getch();
}
Point of pointers: A point of pointer is a form of multiple in direction or a chain of a pointer it
contain the address of a variable. When we define a pointer to a pointer. In the first pointer
contains the address of the second pointer, which points to the location that contains the actual
value.
Write a sample program of point of pointer:
#include<stdio.h>
#include<conio.h>
main()
{
int a=15,*p,**p1;
p=&a;
p1=&p;
printf("a=%d \n",a);
printf("&a=%u \n",&a);
printf("p=%u \n",p);
printf("*p=%d \n",*p);
printf("&p=%u \n",&p);
printf("p1=%u \n",p1);
printf("*p1=%u \n",*p1);
printf("**p1=%d \n",**p1);
printf("&p1=%u \n",&p1);
}
Array of pointer:
Arrays are closed related to the pointer in the c programing but the important difference
between that is that , a pointer variable can take a address of then values were as array as a
fixed value.
Write a sample program of array of pointer:
#include<stdio.h>
#include<conio.h>
main()
{
int a[4]={10,20,30,40},*p;
p=&a[4];
// the following gives values in a (normal format)
printf("a[0]=%d \n",a[0]);
printf("a[1]=%d \n",a[1]);
printf("a[2]=%d \n",a[2]);
printf("a[3]=%d \n",a[3]);
// the following gives address of a
printf("a[0]=%u \n",&a[0]);
printf("a[1]=%u \n",&a[1]);
printf("a[2]=%u \n",&a[2]);
printf("a[3]=%u \n",&a[3]);

}
Example 2:
#include<stdio.h>
#include<conio.h>
main()
{
int a[4]={10,20,30,40},*p;
p=&a[4];
// the following gives values in a (pointer format)
printf("a[0]=%d \n",*(a+0));
printf("a[1]=%d \n",*(a+1));
printf("a[2]=%d \n",*(a+2));
printf("a[3]=%d \n",*(a+3));
// the following gives address of a (pointer format)
printf("a[0]=%u \n",(a+0));
printf("a[1]=%u \n",(a+1));
printf("a[2]=%u \n",(a+2));
printf("a[3]=%u \n",(a+3));
}
Structure
1. Structure is a collection of different data type which are grouped together and each in a
structure is called member. Structure is a user defined data type.
2. If you want access a structure member in C. Structure variable should be declared.
3. Many structure variables can be declared for some structure and memory with the allocated
for each separately.
4. A structure is a collection of one or more variable of different data type grouped together
under a single name.

Syntax:
struct member
{
Datatype variable;
‘’’’’’’’’’’’’’’’’’’’’’’’’’’’
};
Declaration of structure:
struct student
{
char name[20];
int roll no;
float avg;
};
All the members of a structure are the related to the structure variable members are s1.name.
The dot(.) sign is used to access the structure member.
Write a sample program of structure:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[20];
int rollno;
float avg;
};
main()
{
struct student s1={"asdf",521,92.3};
struct student s2={"hjkl",522,95.3};
printf("name=%s\nrollno=%d\navg=%f\n",s1.name,s1.rollno,s1.avg);
printf("name=%s\nrollno=%d\navg=%f\n",s2.name,s2.rollno,s2.avg);
getch();
}
Structure with pointer:
In c language pointer can also be applied to structure that is we can have pointers pointing to
the structure in such the same way we have pointer pointing to int, float, char, double……….., in
such that pointer are known as structure pointer. Structure elements can be accessed by
structure variable and a dot operator are by using structure in arrow operator is used.

Write a sample of program in Structure with pointer:


#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[20];
int rollno;
float avg;
};
main()
{
struct student s={"sai",521,92.3},*p;
p=&s;
printf("name=%s \n rollno=%d \n avg=%f \n",s.name,s.rollno,s.avg);
printf("name=%s \n rollno=%d \n avg=%f \n",p->name,p->rollno,p->avg);
printf("name=%u \n rollno=%u \n avg=%u \n",&s.name,&s.rollno,&s.avg);
}

Nested structure:
A structure with another structure is called nested structure.

Write a sample program of Nested structure:


#include<stdio.h>
#include<conio.h>
#include<string.h>
struct address
{
char s[10];
int n;
};
struct student
{
char name[20];
int rollno;
struct address addr;
};
main()
{
struct student isan={"anu",1234,"isan",4567};
printf("%s\n%d\n%s\n%d\n",isan.name,isan.rollno,isan.addr.s,isan.addr.n);
}
Array of structure:
Array is a collection of similar data type grouping structure variable in to one array is a referred
to as on array of structure c permits us to declare of structure.
We know that structure is a collection of dissimilar data types. So, by using both array and
structure we can add more students details.

Write a sample program in array of structure:


Example 1:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[10];
int rollno;
float avg;
};
main()
{
struct student st[3]={{"sai",150,95.8},{"apple",152,982.5},{"isan",454,865.8}};
/*int i;
for(i=0;i<3;i++)
{
printf("\n %s %d %f \n",st[i].name,st[i].rollno,st[i].avg);
}*/
printf("%s %d %f\n",st[0].name,st[0].rollno,st[0].avg);
printf("%s %d %f\n",st[1].name,st[1].rollno,st[1].avg);
printf("%s %d %f",st[2].name,st[2].rollno,st[2].avg);
}
Structure padding:
 In order to align the data in memory, one or more empty bytes (addresses) are inserted (or
left empty) between memory addresses which are allocated for other structure members
while memory allocation. This concept is called structure padding.
 Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit
processor) from memory at a time.
 To make use of this advantage of processor, data are always aligned as 4 bytes package
which leads to insert empty addresses between other member’s address.
 Because of this structure padding concept in C, size of the structure is always not same as
what we think.
Write a sample program of structure padding:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{
int id1;
char name;
int id2;
char c;
float percentage;
};
main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n", sizeof(a));
printf(" size of structure2 in bytes : %d\n",sizeof(b));
getch();
}
With address values :
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{
int id1;
char name;
int id2;
char c;
float percentage;
};
int main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n", sizeof(a));
printf ( "%u\n", &a.id1 );
printf ( "%u\n", &a.id2 );
printf ( "%u\n", &a.name );
printf ( " %u\n", &a.c );
printf ( " %u\n",&a.percentage );
printf(" size of structure2 in bytes : %d\n",sizeof(b));
printf ( "%u\n", &b.id1 );
printf ( "%u\n", &b.name );
printf ( "%u\n", &b.id2 );
printf ( "%u\n", &b.c );
printf ( "%u\n ", &b.percentage );
}

Unions
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.

Defining a Union
To define a union, you must use the union statement in the same way as you did while defining
a structure. The union statement defines a new data type with more than one member for your
program.

Syntax :
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example :
union Data
{
int i;
float f;
char str[20];
} data;

The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union −

#include <stdio.h>
#include<conio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data: 20

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program −
#include <stdio.h>
#include<conio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.

Same example once again where we will use one variable at a time which is the main purpose of
having unions −
#include <stdio.h>
#include<conio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being used at a
time.

Anda mungkin juga menyukai