C Language All Theory
C Language All Theory
C-LANGUAGE
Features of C-Language:
Portability:
The Application developed in one System using C-Language can run on any
other System even if Operating System is different. If Operating System is
same in another system, then place .exe file. If Operating System is
different, then place Source Code File ( .c file ).
Extendibility:
We can extend the C-Library by adding our own header files. C-Language
provides C-Library to us to develop the C-Programs. C-Library is a collection
of Header Files where Header File is a collection of predefined functions.
C-Library
Extendibility
Structure of a C-Program:
C-Language is a Procedure-Oriented Programming Language. C-Program is
written in the form of functions.
Pre-processor Directives
Global Declaration
Function Declaration
<return_type> <function_name>([<arguments_list>])
{
//Local Declaration
//Statements
}
. Note:
.
Notation (Symbol) & Meaning in Syntaxes:
int/void main([ int argc,char *argv[ ] ])
{ Notation Meaning
//Local Declaration (Symbol)
<> Any
//Statements [] Optional
}
main() Function:
“main()” is a user-defined function in which we can write a set of
statements.
It is entry point of the program.
Every C-Program execution starts from “main” function. Because it is
entry point of the program.
Its return type is “int / void” in C-Language.
It can take two arguments. First argument is “int” type. Second
argument is “char*” type array. First argument takes number of
arguments. Second argument takes a set of strings. Passing
arguments to main function is optional. We can pass arguments to
main function from MS DOS command prompt. This mechanism is
called “Command Line Arguments”.
Writing arguments for “main” function is optional.
printf():
printf() is a predefined function or built-in function included in
“stdio.h” header file.
It is used to print the data on console screen [Output Screen].
Example-1:
printf(“hello”); //prints hello
Example-2:
int x=20;
printf(“x=%d”,x); //prints x=20
Output:
Hello
Output:
hello
welcome to C-Language
"hello"
'hi'
abcefg
Variable:
Variable is a name of storage location that can hold a value.
It can be changed.
A variable can hold one value only at a time.
rno
Example: int rno=15; //rno is a variable
15
Note:
Integer Type:
Number without decimal places is called “Integer Type”.
Example: 65 879 -16 -12
Integer Type:
Number without decimal places is called “Integer Type”.
Example: 65 879 -16 -12
There are Four Integer related Data Types in C-Language. They are:
1. short int
2. int
3. long int
4. long long int
There are Two types in every Integer related Data Type. They are:
i. signed
ii. unsigned
signed:
It can accept positive, zero and negative values.
unsigned:
It can accept positive values and zero only. It cannot accept
negative values.
There are Three Floating point related data types in C-Language. They are:
1. float
2. double
3. long double
float 4 Bytes 6 %f
double 8 Bytes 15 %lf
long double 16 Bytes 18 %Lf
Format Specifiers:
Format specifiers are used to read the data or print the data.
These are used in reading (input) and printing (output) statements.
Declaring Variable:
Assigning Values:
Assigning Charcater:
section=‘A’;
Example-1:
Reading an Integer value from keyboard:
int rno;
printf(“Enter rno:”);
scanf(“%d”,&rno);
Example-2:
Reading a float value from keyboard:
float radius;
printf(“Enter radius of circle:”);
scanf(“%f”,&radius);
C-Language Tokens:
A smallest individual unit of a C-program is called “C-Token”.
Identifiers:
The names of variables, functions, labels or any user-defined
name in the program is called “Identifier.
It is used for identification purpose.
Keywords:
Keywords are the Reserved Words.
Every keyword has specific meaning and that can perform
specific functionality.
We cannot use keywords as Identifiers.
C-Language initially introduced with 32 keywords only. “C-17”
version has 44 keywords.
Example:
if for while do switch else int float char
Constants [Literals]:
Constants are the fixed values.
We cannot change them.
Example:
Integer Constants:
17 459 -45 786 -68 => Decimal Constants
0b1110 => Binary constant [Prefix binary value with ‘0b’]
036 => Octal Constant [Prefix octal value with ‘0’]
0x1E => Hexa Decimal Constant [Prefix hexa decimal value with 0x]
Operators:
Operator is a symbol which is used to perform operations like
Arithmetic Operations or Logical operations.
Example:
+ - * / % > >= < <=
Separators:
Separators are:
variable separator ,
statement separator ;
block separator { } …etc
OPERATORS
Operator Precedence:
Operator Precedence is used to evaluate the Expressions. It determines
the order of operations to be performed in the Expression.
Example-1: x + y * z
In the above Expression, ‘*’ has highest priority than ‘+’. So y*z is
calculated first. Then ‘+’ operation will be done.
Example-2: (x+y)*z
In the above expression, (x+y) will be calculated first. Because, ‘(‘ has
highest priority than ‘*’.
Associativity:
Associativity is used when multiple operators have same level precedence.
Associative can be either Left to Right (or) Right to Left.
Example-1: a+b*c-d/e
In the above Expression, * and / are same level priorities. So, Associativity
will be used. For * and /, Associativity is Left to Right. So, ‘*’ will be
calculated first. Then / will be calculated.
+ and – are same level priorities. Associativity of + and – is Left to Right. So,
+ will be calculated first. Then – will be calculated.
Example-2: a=b=c=d=50
Control Structures
[Control Statements / Flow Control]
Advantage:
• It provides better control to programmer on flow of execution.
if:
Syntax:
if(<condition>)
{
//statements
}
Execution Process:
First, it checks the condition. If condition is true, executes the
statements. Otherwise, skips the statements.
Example:
if(age>=18)
printf(“Eligible to Vote”);
if else:
Syntax:
if(<condition>)
{
//statements
}
else
{
//statements
}
Execution Process:
First, it checks the condition. If condition is true, executes ‘if’ block
statements. Otherwise, it executes else block statements.
Example:
if(age>=18)
printf("Eligible to Vote");
else
printf("Not Eligible to Vote");
if else if:
Syntax:
if(<condition-1>)
{
//statements
}
else if(<condition-2>)
{
//statements
}
else if(<condition-3>)
{
//statements
}
.
.
else
{
//statements
}
Execution Process:
First, it checks the condition-1. If the condition is true, it executes the
statements of ‘if’ block and comes out of ‘if else if’. If condition-1 is
‘false’, then only it checks second condition. If second condition is
true, it executes the statements in this ‘else if’ block and comes out
of ‘if else if’. If second condition is ‘false’, then it checks another
condition and so on. If all conditions are false, ‘else’ block statements
get executed.
Example:
if(n>0)
printf("Positive");
else if(n<0)
printf("Negative");
else
printf(“Zero”);
nested If:
Syntax:
if(<condition-1>)
{
if(<condition-2>)
{
//statements
}
}
Execution Process:
First, it checks outer condition. If outer condition is true, it checks
inner condition. If it is also true, then statements get executed. If
outer condition is false, it will not check inner condition.
Example:
if(a>b)
{
if(a>c)
{
printf(“a is big”);
}
}
switch:
Syntax:
switch(<variable>/<expression>)
{
case <constant1>:
//statements
break;
case <constant2>:
//statements
break;
.
.
default:
statements
}
Execution Process:
First, it captures variable/expression value. It checks with first constant
value. If first constant value is matched with variable/expression value,
first case statements get executed and come out of switch. If first
constant value is not matched, checks with second constant value. If it
is matched, second case statements get executed and comes out of
switch. If not matched, checks with third constant and so on. If all
constant values are not matched with variable/expression value, it
executes ‘default’ statements.
Example:
switch(n%2)
{
case 0:
printf(“Even”);
break;
case 1:
printf(“Odd”);
}
Rules in ‘switch’:
• Constant values must be unique. They should not be duplicated.
• Constant data type and Expression data type should be same.
Because it tests equality only.
• Constant or expression can be of integer type or char type.
• Constant or Expression cannot be of float type or string type.
‘while’ loop:
Syntax:
while(<condition>)
{
//statements
}
Execution Process:
First, condition is tested. If condition is true, statements get executed.
After executing all statements of ‘while’ loop, condition is tested again.
If the condition is true, statements get executed again. It performs this
process as long as the condition is true. It terminates the Loop when the
condition is false.
Example:
i=1;
while(i<=10)
{
printf(“%d\n”,i);
i++;
}
Syntax:
do
{
//statements
} while(<condition>);
Execution Process:
First, it executes the statements. Then checks the condition. If condition
is true, statements get executed again. This process is performed as long
as the condition is true. When the condition is false it terminates the
loop.
Example:
i=1;
do
{
printf(“%d\n”,i);
i++;
} while(i<=10);
‘for’ Loop:
Syntax:
for(<Initialization>;<condition>;<step>)
{
//statements
}
Execution Process:
First, it takes initial value. Then it checks condition. If the condition is
true, statements get executed. After executing all statements of ‘for’
loop, it will take step. After taking step, it checks with the condition
again. If the condition is true, statements get executed again. This
process is performed as long as the condition is true. It terminates the
loop when the condition is false.
Example:
goto:
It is used to transfer the control to specified label.
Jumping Backward:
Syntax:
……………
……………
…………….
<Label_Name>:
……………
……………
goto <Label_Name>;
……………..
……………..
Example:
i=1;
nareshit:
printf(“%d\n”,i);
i++;
if(i<=10)
goto nareshit;
Jumping Forward:
Syntax:
……………
……………
goto <Label_Name>;
……………
……………
<Label_Name>:
……………..
……………..
Example:
if(n>0)
goto nareshit;
n=-n;
nareshit:
printf(“%d”,n);
break:
Syntax:
Loop
………….
………….
………….
………….
break;
………….
………….
………….
Example:
continue:
Syntax:
………….
………….
………….
………….
continue;
………….
………….
Example:
for(i=1; i<=10; i++)
{
if(i==7)
continue;
printf(“%d\n”,i);
}
// Above code prints 1 to 10 except 7
return:
• “return” is a Jumping Control Structure.
• It can be used to come out of the function.
• It can return a value to the function call.
Syntax:
return <variable> / <constant>;
Example:
int add(int x,int y)
{
return x+y;
}
Nested Loops:
Writing Loop in another Loop is called “Nested Loop”. A Loop is used to
execute the statement repeatedly. A Nested Loop is used to execute the
loop repeatedly.
Example:
for(i=1;i<=10;i++)
{
for(j=1;j<=5;j++)
{
printf(“hello\n”);
}
printf(“\n”);
}
Functions
Function:
• Function is a block of statements that gets executed on calling.
• It can be also called as a “Sub-Program”.
• Every Function is defined to perform specific task.
Advantages of Functions:
• It improves understandability.
• It decreases length of code.
• It allows reusability of code.
• We can define any number of functions.
• We can call a function for any number of times.
• We can call a function from anywhere within the program. But that
function must be called directly or indirectly from “main” function.
Because “main” is entry point of the program.
<return_type> <function_name>(<argument_list>)
{
//Statements
}
Example:
int add(int x,int y)
{
return x+y;
}
Function Header:
It contains return type, function name and argument list.
Example:
int add(int x,int y)
Function Body:
It contains a set of statements which should be executed when it is called.
Example:
{
return x+y;
}
Types of Functions:
There are two type of Functions. They are:
• Built-In Functions
• User-Defined Functions
Built-In Functions:
Built-In Functions can be also called as Predefined Functions (or)
System-Defined Functions (or) Library Functions. These Functions
were developed by C-Language developers. They placed related
functions in a file. This file is called “Header File”.
Example:
math.h string.h stdio.h
User-Defined Functions:
We can define our own functions in C-Language. These are called User-
Defined Functions.
Example:
fact() add() nareshit() add()
Function Definition:
Defining a function is called “Function Definition”. It contains Function
Header and Function Body.
Example:
add(int x,int y)
{
return x+y;
}
Call of Function:
Calling a Function is called “Call of Function”. A function does not get
executed without calling. So, we must call the function.
Example:
add(5,4);
#include<stdio.h>
void nareshit(); //Function Declaration (or) Function Prototype
void nareshit() // Function Definition
{
printf("hello from nareshit\n");
printf("Welcome to nareshit\n");
printf("Bye from nareshit\n");
}
void main()
{
printf("Hi from main\n");
nareshit(); //call of function
printf("Bye from main");
}
Output:
Hi from main
hello from nareshit
Welcome to nareshit
Bye from nareshit
Bye from main
Calling Function:
A function from where we are calling another function is called “Calling
Function” (or) “Caller Function”.
Called Function:
A function which is called by another function is called “Called
Function” (or) “Callee Function”.
Argument [Parameter]:
• An Argument can be also called as “Parameter”.
• Argument is a local variable declared in Function Header.
• It is used to bring a value into function.
• It acts like Input for a Function.
• We call it as local variable. Its scope is limited to function only. It
cannot be used outside of the function.
Example:
int add(int x,int y) => x,y are called arguments
Note:
• The arguments in function header are called “Formal Arguments” or
“Formal Parameters”.
Example:
int add(int x,int y) => x,y are Formal Arguments
Return:
• “return” is a jumping control structure.
• It can be used to come out of function.
• It can return a value to function call.
• “return” keyword is used to return a value.
• It is used to send a value outside of a function.
• In C-Language, a function can return one value only. It cannot return
many values.
• Default return type is “int” in C-Language. If we don’t specify return
type, int will be taken.
No Argument, No Return:
This kind of functions cannot take any arguments and cannot return any
value.
Example:
#include<stdio.h>
void add(); // Function Declaration
void add() //Function Definition
{
int x,y;
printf("Enter x,y:");
scanf("%d%d",&x,&y);
printf("sum=%d\n",x+y);
}
void main()
{
add();
add();
}
Output:
Enter x,y:6 4
sum=10
Enter x,y:10 20
sum=30
Argument, No Return:
This kind of functions can take arguments. But cannot return any value.
Example:
#include<stdio.h>
void add(int,int);
void add(int x,int y)
{
printf("sum=%d\n",x+y);
}
main()
{
add(5,4);
add(60,40);
}
Output:
sum=9
sum=100
No Argument, Return:
This kind of functions cannot take any arguments. But they can return a
value.
Example:
#include<stdio.h>
int add();
int add()
{
int x,y;
printf("Enter x,y:");
scanf("%d%d",&x,&y);
return x+y;
}
void main()
{
int k;
k=add();
printf("sum=%d\n",k);
printf("sum=%d\n",add());
}
Output:
Enter x,y:6 4
sum=10
Enter x,y:20 30
sum=50
Example:
#include<stdio.h>
int add(int,int);
int add(int x,int y)
{
return x+y;
}
void main()
{
int k;
k=add(1,2);
printf("sum=%d\n",k);
printf("sum=%d",add(4,3));
}
Output:
sum=3
sum=7
What is “void”?
• “void” is a data type which indicates “nothing” (or) “no value”.
• Generally, when a function does not return any value, we write
return as “void”. It indicates function is returning nothing.
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
• Save above code in a file with the name “nareshit.h”.
• Compile the code. [Execute menu => Compile or) Short cut key => F9]
• Open a new source file.
• Write following code in source file:
#include"nareshit.h" // "" searches in Current Directory
#include<stdio.h> // <> searches in C-Library
main()
{
printf("fact=%d\n",fact(4));
printf("power=%d\n",power(2,3));
printf("max=%d\n",max(10,20));
printf("min=%d",min(10,20));
}
• Save the file where “nareshit.h” header file is stored.
• Compile the Program & Run It.
Recursion:
• If a function is called with in the same function, then it is called
“Recursion”.
• Recursion is used to call a function within the same function for many
times based on the condition.
• All the tasks which we can do using Iterative control structures can
be done using “Recursion”.
• Recursion execution is slower than Iterative Control structures.
• To represent some solutions, to provide readability we use
Recursion.
Example:
int fact(int n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Types of Recursions:
Linear Recursion:
If a function has one recursive call, then it is called Linear Recursion.
Example:
Binary Recursion:
If a function has two recursive calls, then it is called Binary Recursion.
Example:
int fibo(int n)
{
if(n==0 || n==1)
return n;
else
return fibo(n-1)+fibo(n-2);
}
//In the above Example, fibo function has two recursive calls.
//First recursive call is evaluated first. Then Second.
Storage Classes:
auto:
• "auto" keyword is used to declare the auto variable.
• It can be also called as "Internal Variable" (or) "Automatic
Variable" (or) "Local Variable".
• A variable which is declared with in the function (or) block is
called "auto variable".
• Even if we use auto keyword or not, the variable declared in
function or block will be taken as auto variable by default.
• Scope of auto variable is limited to Function only.
extern:
• "extern" keyword is used to declare "extern variable".
• It can be also called as "External Variable" (or) "Global Variable".
• We declare it outside of all functions [Above of all].
• Scope of extern variable is limited to the Program.
• Lifetime of extern variable is limited to the Program.
• Its lifetime will be ended when the program is terminated.
• Other programs can also share extern variable.
static:
• A variable which is declared using "static" keyword is called
"static variable".
• It can be used in 2 ways:
▪ static local variable => it is declared in function
▪ static global variable => it is declared outside of all
functions
• For static variable memory will be allocated only once.
• It is initialized only once.
• Its lifetime is limited to program.
• When the program is terminated its lifetime will be ended.
• Its scope depends on the place where it is declared. If static
register:
• "register" is same as "auto" variable only.
• "register" variable will be stored in "CPU Registers".
• For fast accessing purpose we use it.
• Generally, loop variables are declared as registers.
• It cannot be declared outside of function.
Note:
A function must be called directly or indirectly from “main” function.
Because it is entry point.
Arrays
x
3200 Base Address
Advantages of Array:
Disadvantages of Array:
Types of Arrays:
Example:
10 80 50 10 x[0]
(OR)
80 x[1]
x[0] x[1] x[2]
50 x[2]
Row
Column
Syntax:
<type> <array_name>[<size>];
Example-1:
Example-2:
Example-3:
Syntax:
Example:
int x[5] = {50,80,40,90,20};
(or)
printf(“%d”,x[0]);
With above Loop, when i value 0 first element will be printed. When
i value is 1 second element will be printed and so on.
scanf(“%d”,&x[0]);
To read all elements from console screen, we write the Loop. Here,
Loop variable represents Array Index.
Multi-Dimensional Array:
Two-Dimensional Array:
• Two-Dimensional Array is a collection of single dimensional
arrays.
• It can represent rows and columns.
• In C-Language, Row Indexing starts from zero and Column
Indexing starts from zero.
• Like Single Dimensional Array, Double Dimensional Array
elements are stored in sequential memory locations.
Example:
Two-Dimensional Array
In above Example,
Syntax:
<type> <array_name>[<row_size>][<column_size>];
Example-1:
int x[2][3]; // 24 Bytes Memory will be allocated
We must specify the row size and column size when we declare
double dimensional array. But In case of initialization, we have no
need to specify row size. But we must specify column size. Based
on column size, number of elements in each row will be identified
here.
(OR)
To read one row use a loop. To read multiple rows use nested
loop.
printf(“Enter x-array elements:”);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf(“%d”,&x[i][j]);
Three-Dimensional Array:
Three-Dimensional Array is a collection of double dimensional
arrays.
Example:
Three-Dimensional Array
(OR)
(OR)
Printing 3D-Array:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<3;k++)
printf(“%d\t”,x[i][j][k]);
printf(“\n”);
}
printf(“\n”);
}
Strings
Example:
x
3200 Base Address
Declaring a String:
Syntax:
char <array_name>[<size>];
Example:
char x[20]; //20 Bytes memory will be allocated
In above example, x is array name. 20 is the maximum size. In C-
Language, 1 Byte memory will be allocated for 1 character. x-array
[String] can hold maximum of 20 characters. So, 20 Bytes memory
will be allocated.
Initializing a String:
Printing a String:
printf(“%s”,x);
(OR)
printf(x);
(OR)
puts(x);
(OR)
for(i=0;x[i]!=0;i++)
printf(“%c”,x[i]);
Reading a String:
printf(“Enter a String:”);
scanf(“%s”,x); // No need to use &. “x” itself is address
(OR)
printf(“Enter a String:”);
gets(x);
Syntax:
char <array_name>[<size1>][<size2>];
Example-1:
Syntax:
Example:
int x[5][10] = {“raju”, “sai”, “vijay”, “kiran”, “arun”};
(or)
printf(“%s”,x[0]);
printf(“%c”,x[0][0]);
for(i=0; i<5;i++)
printf(“%s\n”,x[i]);
printf(“Enter 5 strings:”);
for(i=0;i<5;i++)
scanf(“%d”, x[i]);
Pointers
Advantages:
• Pointers are used for fast accessing.
• provides Dynamic Memory Allocation.
• provides Call by Reference.
Disadvantages:
• Security problems may occur due to pointer arithmetic.
• pointer requires extra memory.
• Programmer may feel difficult to write programs using pointers.
Note:
There are 2 types of variables. They are:
• Data Variables
• Pointer Variables
Data Variable holds the data.
Pointer variable holds address of the variable.
<type> *<variable>;
Example:
int *p1; //8 Bytes memory will be allocated
p1 is pointer variable of integer type. It can hold Integer variable address
float *p2; //8 Bytes memory will be allocated
p2 is the pointer variable of float type. It can hold float variable address
Initializing a Pointer:
int x=20,*p;
p=&x; //Initializing a pointer
x p
20 4567
4567
&x
#include<stdio.h>
main()
{
double x=40,*p;
p=&x;
printf("value=%d\n",x);
Output:
printf("address=%d\n",&x);
value=40
printf("address=%d\n",p); address=6487572
address=6487572
printf("value=%d\n",*&x); value=40
value=40
printf("value=%d\n",*p); size of p=8
printf("size of p=%d",sizeof(p));
}
Pointer Arithmetic:
#include<stdio.h>
main()
{
short int x[] = {10,20,30,40,50},*p;
p=x;
printf("%d\n",*p); //10
p=p+4;
printf("%d\n",*p); //50
p--;
printf("%d\n",*p); //40 Output:
10
p=p-2; 50
printf("%d\n",*p); //20 40
20
p++; 30
printf("%d\n",*p); //30
}
int x={10,20,30,40,50},*p;
p++;
printf(“%d\n”,*p); //prints second element 20
Array of Pointers:
p[0] = &x[0];
p[1] = &x[1];
p[2] = &x[2];
printf(“%d\n”,*p[0]); //prints 10
printf(“%d\n”,*p[1]); //prints 20
printf(“%d\n”,*p[2]); //prints 30
x[3] p[3]
In above example,
x is array. It is holding set of values 10,20 and 30.
p is array of pointers. It is holding a set of addresses 2000,
2004 and 2008.
Call by Value:
• In this mechanism, values of variables (or) values are passed as
arguments to the Function.
• If we make any changes to the variables of called function,
those changes will not be applied to the variables of calling
function.
Example:
#include<stdio.h>
void swap(int,int);
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
main()
{
int a=20,b=30;
swap(a,b); // Call By Value
printf("a=%d\tb=%d",a,b);
}
Output:
a=20 b=30
Call by Reference:
Example:
#include<stdio.h>
void swap(int*,int*);
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
main()
{
int a=20,b=30;
printf("a=%d\tb=%d",a,b);
}
Output:
a=30 b=20
• malloc()
• realloc()
• calloc()
• free()
malloc():
• used to allocate specified number of bytes of memory at
run time on heap memory.
• This function returns address of first byte & its return
type is void. [void type address].
• Type conversion is required to store the data in this
memory.
Example:
int *p;
p = (int*)malloc(50) => allocates 50 bytes memory
float *x;
x = (float*)malloc(sizeof(float)) => allocates 4 bytes
realloc():
• used to reallocate the memory which is already allocated
by malloc() function.
• This function returns address of first byte & its return
type is void. [void type address].
• Type conversion is required to store the data in this
memory.
Example:
p = (int*)realloc(p,100) => reallocates 100 bytes memory
calloc():
• used to allocate a group of blocks of memory.
• It is used to allocate the memory to hold a set of values.
• This function returns address of first byte & its return
type is void. [void type address].
• Type conversion is required to store the data in this
memory.
Example:
p = (int*)calloc(10,sizeof(int));
free():
• used to destroy the memory which is allocated using
malloc() or realloc() or calloc().
• It is the responsibility of the programmer to destroy the
memory if memory allocated at run-time. Automatic
memory management is not available for dynamic
memory allocation in C-Language.
Example:
free(p);
Pointer to Pointer:
Example:
p1=&x;
p2=&p1;
printf(“%d\n”,x); //prints 50
printf(“%d\n”,*p1); //prints 50
printf(“%d”,**p2); //prints 50
x p1 p2
50 2000 3000
In C_Language, We can define our own data types like int, float and char.
These are called “User-Defined Data-Types”. User-Defined data types are:
• Structures
• Unions
• Enumerations
Structure:
• Structure is a User-Defined Data Type.
• Structure is a collection of elements of different data types.
• Structure encapsulates [combines] different data type variables in
one container. This container is called “Structure”.
• “struct” keyword is used to define the structure.
• To access structure elements, we use Dot Operator [ . ].
• Structure elements are stored in sequential memory locations.
• Every member of a structure has its own memory location.
• Sum of the sizes of the members is size of the structure variable.
Advantages:
• We can define our own data type.
• We can hold different type elements in one container.
• In C-Language, a function can return one value only. But using
structure we return group of values.
• Structure can contain another Structure. With this we can extend its
properties of structure.
Defining a Structure:
“struct” keyword is used to define a structure. Structure Definition will be
terminated with semicolon [ ; ]. It can be defined inside of main() or outside
of main().
Syntax:
struct <structure_name>
{
<type-1> <v1>[,<v2>,……..];
<type-2> <v1>[,<v2>,……..];
<type-3> <v1>[,<v2>,……..];
…………
…………
};
Example:
struct student
{
Members (or)
int rno; Member Variables (or)
char name[20]; Properties (or)
float avrg; Attributes (or)
Fields (or)
}; Instance Variables
Note:
Memory will not be allocated when we define the structure. Memory will
be allocated when the structure variable is declared.
s1
rno name
20 raju
avrg 56.78
Array of Structure:
In above example,
Structure of Array:
• Defining array as a member in structure is called “Structure of
Array”.
• To hold many members of same type, we can use Array as a
member in structure.
struct student
{
int rno;
char name[20];
int m[3]; //Structure of Array
};
In the above example, m is the array that can hold 3 subjects marks.
s1
rno name
10 raju
50 40 60
m[0] m[1] m[2]
int id
char name[20]
int age
Person p Person p
int job char section
double salary int marks
p job sal
id name age
clerk 10000.00
1234 raju 23
Pointer to Structure:
A pointer variable which holds address of a structure is called pointer to
structure.
For Example,
Define a structure as following:
typedef struct student
{
int rno;
float avrg;
}std;
[OR]
Structure as Argument:
#include<stdio.h>
typedef struct student
{
int rno;
char name[20];
int marks;
}std;
void show(std);
void show(std s)
{
printf("%d\t%s\t%d\n",s.rno,s.name,s.marks);
}
main()
{
std s1;
Output:
Enter rno,name and marks:
20 Sravan 500
20 Sravan 500
Returning Structure:
#include<stdio.h>
typedef struct student
{
int rno;
char name[20];
int marks;
}std;
std f1();
std f1()
{
std s={12,"Vijay",456};
return s;
}
main()
{
std s1;
s1 = f1();
printf("%d\t%s\t%d",s1.rno,s1.name,s1.marks);
}
Output:
12 Vijay 456
Union:
• Union is a User-Defined Data Type.
• Union is a collection of elements of different data types. But it can
hold one value at a time.
• Union encapsulates [combines] different data type variables in one
container. This container is called “Union”.
• “union” keyword is used to define the structure.
• To access union elements, we use Dot Operator [ . ].
• All Union members share common memory area.
• Maximum size required for individual members is size of the union
variable.
Defining a Union:
“union” keyword is used to define a union. Union Definition will be
terminated with semicolon [ ; ]. It can be defined inside of main() or outside
of main().
Syntax:
union <union_name>
{
<type-1> <v1>[,<v2>,……..];
<type-2> <v1>[,<v2>,……..];
<type-3> <v1>[,<v2>,……..];
…………
…………
};
Example:
union abc
{
Members (or)
int x; Member Variables (or)
double y; Properties (or)
char z; Attributes (or)
Fields (or)
}; Instance Variables
x
y
z
a1.x = 20;
printf("%d\n",a1.y); //20
a1.y = 30;
printf("%d",a1.x); //30
}
Output:
20
30
Enumeration:
• Enumeration is a user-defined data type.
• It is used to define string constants with integer equivalent values.
• “enum” keyword is used to define Enumeration.
• When we don’t give integer values to string constants in
enumeration definition, they take default values. This default
numbering starts from zero.
Syntax:
enum <union_name>
{
<String_Constant-1>=<value-1>,
<String_Constant-2>=<value-2>,
………………………
};
Example:
enum colors {RED=10, BLUE=20, GREEN=30 };
Files
Function Purpose
fopen() Used to open create a new file (or) open an existing file
in particular mode
fclose() Used to close a file
getc() Used to read a character from file
putc( Used to write a character into file
fprintf() Used to write any type of data in file
fscanf() Used to read ay type of data from file
rewind() Used to move the file pointer to BOF (Beginning of file)
fseek() Used to move the file pointer to specific position
For random accessing, we use it
ftell() Used to know the file pointer position
fread() Used to read data from binary file
fwrite() Used to write the data into binary file
Opening a File:
fopen():
• “fopen()” function is used to create a new file or open an existing
file in particular mode.
• This function returns address of the file. This address is “FILE” type
address.
Syntax:
<file_pointer> = fopen(<file_name>,<mode>);
Example:
fp = fopen(“demo.txt”,“w”);
fp = fopen(“d:\\nareshit\\student.txt”, “a”);
fp = fopen(“demo.txt”,“r”);
Closing a file:
fclose():
“fclose()” function is used to close an opened file. After performing file
input output operations, we must close the opened file. Otherwise, we
may loss the data.
Syntax:
fclose(<file_pointer>);
Example:
fclose(fp);
putc():
Syntax:
putc(<char>,<file_pointer>);
Example:
putc(ch,fp);
getc():
Syntax:
<char> = getc(<file_pointer>);
Example:
ch = getc(fp);
fprintf():
• This function is used to write the data into file.
• Using this function, we can write any type of data into file like int,
float & char ...etc.
Syntax:
fprintf(<file_pointer>,<format_string>,<argument_list>);
Example:
“rno” and “name” data will be written in “fp” file with above
code.
fscanf():
• This function is used to read the data from file.
• Using this function, we can read any type of data from file like int,
float & char ...etc.
Syntax:
fscanff(<file_pointer>,<format_string>,<argument_list>);
Example:
“rno” and “name” data will be read from “fp” file with above
code.
ftell():
This function is used to get the position of file pointer.
Syntax:
ftell(<file_pointer>);
Example:
n = ftell(fp);
fseek():
This function is moved to move file pointer to specified number of
bytes from specified position.
Syntax:
fseek(<file_pointer>,<number_of_bytes_to_move>,<from_where>);
>);
String Constant [or] value Meaning
SEEK_SET [or] 0 From Beginning of File
SEEK_CUR [or] 1 From Current Position
SEEK_END [or] 2 From End of File
Example:
fseek(fp,2,SEEK_SET) Moves 2 bytes forward from beginning of file
fseek(fp,3,SEEK_CUR) Moves 2 bytes forward from current position
fseek(fp,4,SEEK_END) Moves 4 bytes backward from end of file
Types of Files:
Text File:
• Text File contains plain text.
• It contains data as we entered data through keyboard.
• Example: .txt files
Binary File:
• Binary file contains data in the form of bits and bytes.
• It contains the data as the data stored in memory.
• Example: .bin files, .exe files., image files, audio files, video files
fwrite():
“fwrite()” function is used to write the binary data into file.
Syntax:
Example:
fwrite(&s1, sizeof(s1), 1, fp);
fread():
“fread()” function is used to read the binary data into file.
Syntax:
Example:
fread(&s1, sizeof(s1), 1, fp);
Graphics
CUI Application:
CUI Application can display text (or) characters only.
GUI Application:
GUI Application can display text, colors, shapes, font styles and images.
Shapes:
initgraph() Function:
This function is used to switch the screen from text mode to graphics
mode.
Syntax:
Example:
int gd,gm;
gd = DETECT; //automatically detects graphic drivers
initgraph(&gd ,&gm, “C:\\TURBOC3\\BGI”);
Above code detects the graphics drivers & output screen will be switched
to graphics mode.
line() :
line() function is used to draw a line.
Syntax:
line(x1, y1, x2, y2);
Example:
line(200,100,300,200);
rectangle() :
rectangle() function is used to draw a box [rectangle (or) square].
Syntax:
rectangle(x1, y1, x2, y2);
Example:
rectangle(200,100,300,200);
circle() :
circle() function is used to draw a circle.
Syntax:
circle(x, y, radius);
Example:
circle(200,200,100);
putpixel() :
putpixel() function is used to draw a pixel [dot].
Syntax:
putpixel(x, y, color);
Example:
circle(200,200,RED);
drawpoy() :
drawpoly() function is used to draw the polygon.
Syntax:
drawpoly(number_of_points, array);
Example:
int x[] = {100,100,200,200,300,100,400,200};
drawpoly(4,x);
ellipse() :
ellipse() function is used to draw an ellipse.
Syntax:
Example:
ellipse(200, 200, 0, 360, 100, 50);
arc():
arc() function is used to draw an arc.
Syntax:
Examples:
arc(200,200,0,90,100); => 0 to 90 degrees arc will be drawn
with 100 radius from the point (200,200).
pieslice() :
pieslice() function is used to a slice [part] of a circle. It is same as arc.
But it is closed one.
Syntax:
Example:
pieslice(200,200,0,90,100);
Above code draws a slice of circle at (200,200) point with 100 radius
from 0 to 90 degrees.
setfillstyle():
This function is used to set fill pattern and fill color.
Syntax:
setfillstyle(pattern_constant/value, color_constant/value);
Example:
setfillstyle(1, 4); // 1 is pattern number. 4 is color number
(or)
setfillstyle(SOLID_FILL, RED);
floodfill():
This function is used to fill the color in shape. It fills from specified
point to till it reaches the specified color border.
Syntax:
floodfill(x, y, color);
Example:
floodfill(200, 200, BLUE);
outtextxy() :
outtextxy() function is used to draw the text at specified point in
specified color.
Syntax:
outtextxy(x, y, color);
Example:
outtextxy(200, 200, “hello”);
settextstyle() :
It is sued to set text style, text direction and text size.
Syntax:
settextstyle(text _style_constant / value,
text_direction_constant / value, text_size);
Example:
settextstyle(4,0,10);
(or)
settextstyle(GOTHIC_FONT, HORIZ_DIR, 10);