C Language Material
C Language Material
Contents
S Topi Page
No c Num
01 Introduction to C 02
02 Programming Elements 04
03 C Application Structure 05
04 Variables in C 06
05 Functions and calling 08
06 Local and Global Variables 11
07 Data types in C 14
08 Operators in C 20
09 Control Statements in C 31
10 Loop statements in C 44
11 Menu Driven Programs 62
12 Nested Loops in C 65
13 Range based programs 67
14 Pattern programs in C 72
15 Functions in C 81
16 Arrays in C 87
17 String Handling in C 106
18 Structures in C 116
19 Unions in C 124
20 Pointers in C 127
21 Dynamic Memory Allocation 142
22 File Handling in C 148
23 Enumeration in C 156
24 Typedef in C 158
25 Storage Classes in C 160
26 Command Line Arguments in C 167
27 Pre-Processor in C 170
Introduction to C
History:
C is a Programming language developed by Dennis Ritchie in 1972.
It is mainly used in development of Operating Systems, Embedded
software, Device drivers, application software etc.
Programming language:
Programming languages are used to develop applications.
Computer applications Store data and perform operations on data.
Platform Dependency:
Platform means “Operating System”
C and C++ Compilers convert the source program into specific Operating
system understandable code. Hence the compiled code is compatible to
same Operating system on which it has compiled.
2. Web application:
Application runs from multiple machines connected in a network.
Web application installed in server.
Data connection is required to run the application.
Examples: gmail.com, icici.com, irctc.in etc.
Note: We use technologies to develop Web applications which are platform independent
C-software:
C is a standalone software.
We have different types of C-software to develop and run C Programs.
For example, Turbo-C, C-Free, Code Blocks etc.
Download and install any C IDE to write and run programs easily.
1. Identity:
o Identity of a program is unique.
o Programs, Classes, Variables and Methods having identities
o Identities are used to access these members.
2. Variable:
o Variable is an identity given to memory location.
or
o Named Memory Location
o Variables are used to store information of program(class/object)
Syntax Exampl
es
int age = 23;
datatype identity = double salary =
value; 35000.00;
char gender =
‘M’; char* name =
“Amar”;
3. Function:
Function is a block of instructions with an identity
Function performs operations on data(variables)
Function takes input data, perform operations on data and returns results.
Synta Exampl
x e
returntype identity(arguments) int add(int a, int b)
{ {
body; int c =
} a+b;
return c;
}
C Application Structure
Program:
C program consists variables and functions.
Program execution starts with main() function automatically.
Main.c
#include<stdio.
h> void main()
{
printf("Hello");
}
Application:
C application contains more than one program.
We connect these programs by calling one program functions from another
program.
We connect these programs using #include.
Only one program contain main() function from which application execution starts.
Main.c Arithmetic.c
#include<stdio.
#include<arithmeti h> void add()
c.c> void main() {
{ printf("Add");
// invoking }
functions add(); void subtract()
subtract();
{
}
printf("Subtract");
}
#include:
A pre-processor directive is used to connect the programs in C application.
Library:
Library is a collection of pre-define programs called Header-files.
Header-file contains Variables and Methods.
Library is used to develop C application quickly.
Some of the header file names as follows:
Syntax:
datatype identifier = value;
Examples:
char name[] =
“amar” int age =
23
char* mail =
“[email protected]” char
gender = ‘M’;
double salary = 35000;
Assignment:
Assigning a value to the variable which is already declared.
For example,
o int a ; // declaration
o a=10 ; // assignment
Modify:
Increase or decrease the value of a variable
For example,
o int a ; // declaration
o a=10 ; // assignment
o a=a+20; //modify
Initialization:
Defining a variable along with value
For example,
o int a = 10 ; // initialization
o a = a+20 ; // modify
Rules to create variable:
Variable contains alphabets(A-Z , a-z) or Digits (0-9) and only one symbol( _ ).
Variable should not starts with digit
o int 5a = 10; (error)
o int a5 = 10;
o int 1stRank; (error)
Note: We will discuss briefly about Local and Global variables after Functions concept
Functions and Calling
Main()
function:
Main() function must be defined in every C program
C program execution starts from main() function.
Main() function automatically invoke by Operating system.
User function:
Defining other functions along with main() function.
We must declare(prototype) of user function.
We can invoke the function any number of times once it has defined.
Local variables:
A variable inside the function or block.
Local variable cannot access outside of that block.
int main()
{
int a ; -> local variable
}
Format specifiers:
Formatting the result is very important before display to user.
We use following format specifiers to read and print different types of data values.
Data Format
type specifier
int %d
char %c
float %f
string %s
Global Variables:
Defining a variable outside to all functions.
Global variables can be accessed from all the functions.
#include<stdio.
h> void test();
int a=10;
int main
(){
printf("a value in main : %d \
n", a); test();
return 0;
}
void test(){
printf("a value in test :%d \n", a);
}
Data Types in C
Data type:
We need to specify the data type in variable declaration.
Data type specifies, the type of data is allowed to store.
Following table describes the data type with size, format specifier and limits:
Character data type: Char type is used to store alphabets, symbols and digits.
We represents character with single quotes.
#include
<stdio.h> int
main(){
char v1 =
'a'; char v2
= '5'; char
v3 = '$';
printf("v1 value is : %c \
n", v1); printf("v2 value
is : %c \n", v2); printf("v3
value is : %c \n", v3);
return 0;
}
#include
<stdio.h> int
main(){
char v1 =
'a'; char v2
= '5'; char
v3 = '$';
printf("%c ascii value is : %d \n",
v1, v1); printf("%c ascii value is :
%d \n", v2, v2); printf("%c ascii
value is : %d \n", v3, v3); return 0;
}
Output:
a ascii value is :
97 5 ascii value
is : 53
$ ascii value is : 36
limits.h: It is a header file providing constant variables assigned with limits of each data
type..
What happens when we try to store the value beyond the limits of datatype?
Every variable can store the value within the limits only.
When limit exceeded, it counts the value in the specified limit and store
some other value.
#include<stdio.
h> int main(){
char ch = 130;
printf("ch val : %d \n", ch); //
prints -126 return 0;
}
#include<stdio.
h> int main(){
char c1=256,
c2=1024; printf("c1
: %d \n", c1);
printf("c2 : %d \n",
c2); return 0;
}
Output:
c1 : 0
c2 : 0
#include<stdio.
h> int main()
{
short s = 32769;
printf("s val : %d \
n", s); return 0;
}
#include<stdio.
h> int main()
{
short s = -32744;
printf("s val : %d \
n", s); return 0;
}
sizeof(): a pre-defined function used to find the size of Variable, value, Datatype etc.
#include
<stdio.h> int
main(){
char
c;
short
s;
printf("char + short : %d \n",
sizeof(c+s)); return 0;
}
Address operator:
We need to specify the location (memory address) using variable to read the data.
‘&’ is called Address operator in C.
#include
<stdio.h> int
main()
{
int a;
printf("Enter a value
: "); scanf("%d", &a);
printf("a value is : %d \
n", a); return 0;
}
Operators in C
Operator: It is a symbol that performs operation on data.
#include<stdio.
h> int main()
{
printf("5>3 : %d \n", 5>3);
printf("5<3 : %d \n",
5<3); printf("5==3 :
%d \n", 5==3); printf("5!
=3 : %d \n", 5!=3);
return 0;
}
Note: All relational operators having same priority. Hence these operators
execute from left to right
#include<stdio. Explanation:
h> int main()
{
int a=25, b=15, c=5,
d, e; d = a>b>c;
e = b<a>c;
printf("%d, %d \n", d,
e); return 0;
}
Modify
Operators
Increment Operators Decrements Operators
Pre-Increment Post-Decrement Pre-Decrement Pos-Decrement
Example: Example: Example: Example:
int a = 5; int a = 5; int a = 5; int a = 5;
print(++a); print(a++); print(--a); // print(a--); //
// 6 // 5 4 5
print(a); //6 print(a); //6 print(a); //4 print(a); //4
Logical Operators:
These operators return true (1) or false (0) by evaluating more than one
expression.
Operators are,
o Logical-AND (&&)
o Logical-OR (||)
o Logical-NOT (!)
Following truth table represents the results of Logical operators’ evaluation
A B A&& A|| !A !B
B B
T T T T F F
T F F T F T
F T F T T F
F F F F T T
#include
<stdio.h> int
main(){
printf("5>3 && 5!=3 = %d \n", 5>3 && 5!=3);
printf("5>3 && 5==3 = %d \n", 5>3 && 5==3);
printf("5>3 || 5==3 = %d \n", 5>3 || 5==3);
printf("5<3 || 5==3 = %d \n", 5<3 || 5==3);
return 0;
}
Compound assignment Operators:
Compound assignment operators reduce the size of modify expression.
Operators are +=, -=, *=, &&=, >>=
Bitwise operators:
These operators convert the input into binary data and perform operations.
Operators are,
a. Bitwise AND (&)
b. Bitwise OR (|)
c. Bitwise XOR (^)
The following table explains the how Bitwise operations returns the results.
Truth table:
A B A&B A| A^B
B
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
Note: After performing bitwise operations, results will be displayed in Decimal format
only.
Bitwise – AND operator:
#include 12 = 00001100 (In Binary)
<stdio.h> int 25 = 00011001 (In Binary)
main()
{ 00001100
int a = 12, b = 25;
&
printf("Output = %d", a
& b); return 0; 00011001
} ----------
00001000 = 8 (In decimal)
Bitwise – OR operator:
#include 12 = 00001100 (In Binary)
<stdio.h> int 25 = 00011001 (In Binary)
main()
{ 00001100
int a = 12, b = 25; | 00011001
printf("Output = %d", a
----------
| b); return 0;
} 00011101 = 29 (In decimal)
Bitwise – XOR operator:
#include 12 = 00001100 (In Binary)
<stdio.h> int 25 = 00011001 (In Binary)
main()
{ 00001100
int a = 12, b = 25; ^
printf("Output = %d", a
00011001
^ b); return 0;
} -----------
00010101 = 21 (In decimal)
2's Complement:
The 2's complement of a number is equal to the complement of that number plus
1.
Bitwise Complement of Any Number N is -(N+1).
Theoretical formulas:
For Right Shift: n/2s
For Left Shift: n*2s
o Where ‘n’ is the data and ‘s’ is the number of bits to shift
#include<stdio.
h> int main(){
int a, b,
c; a =
10;
b = a;
c = a*b;
printf("c value : %d \
n", c); return 0;
}
if(condition)
{
statements;
}
Program to give 15% discount to Customer if the bill amount is >= 5000
#include<stdio.
h> int main(){
float bill=0, discount=0;
printf("Enter Bill amount
: "); scanf("%f", &bill);
if(bill>=5000)
{
discount =
0.15*bill; bill =
bill-discount;
}
printf("Final bill to pay : %f \n", bill);
printf("Your discount is : %f \n",
discount); return 0;
}
Output: Enter Bill amount : 6000.0 Final bill to pay : 5100.0 Your discount is : 900.0
Program to give 20% bonus to Employees having more than 5 years’ experience
#include<stdio.
h> int main(){
int exp=0;
float salary=0, bonus=0;
printf("Enter Employee
salary : "); scanf("%f",
&salary); printf("Enter
Expierience : "); scanf("%d",
&exp);
if(exp>5)
{
bonus = 0.20 *
salary; salary =
salary + bonus;
}
printf("Your salary : %f \n",
salary); printf("Bonus : %f \
n", bonus); return 0;
}
Output: Enter Employee salary : 25000 Enter Expierience : 6
Your salary : 30000.000000 Bonus : 5000.000000
if - else block: Else block can be used to execute an optional logic if the given
condition has failed.
Synta Flow
x Chart
if (condition){
If – Stats;
}
else{
Else – Stats;
}
return 0;
}
Program to check profit or loss:
#include<stdio.
h> int main()
{
int originalCost,
sellingPrice; printf("Enter
Original Cost : ");
scanf("%d",
&originalCost);
printf("Enter Selling
Price : "); scanf("%d",
&sellingPrice);
if(originalCost <
sellingPrice)
printf("Profit\n");
else if(originalCost >
sellingPrice)
printf("Loss\n");
else
printf("No Loss No Profit \n");
return 0;
}
#include<stdio.
h> int main()
{
int
units;
float
bill;
printf("Enter units
consumed : "); scanf("%d",
&units);
if(units>0 &&
units<=100) bill
= units*0.8;
else if(units>100 && units<=200)
bill = (100*0.8) + (units-
100)*1.0; else if(units>200 &&
units<=300)
bill = (100*0.8) + (100*1.0) + (units-200)*1.2;
else
bill = (100*0.8) + (100*1.0) + (100*1.2) + (units-300)*1.5;
printf("Bill to pay : %f \n" ,
bill); return 0;
}
Nested if block: Defining a block inside another block. Inner if block condition
evaluates only if the outer condition is valid. It is not recommended to write many
levels to avoid complexity.
#include<stdio.
h> int main(){
int m1, m2, m3;
printf("Enter 3 marks
: ");
scanf("%d%d%d", &m1, &m2,
&m3); if(m1>=35 && m2>=35
&& m3>=35)
{
int avg =
(m1+m2+m3)/3;
if(avg>=60)
printf("Grade-A\
n"); else if(avg>=50)
printf("Grade-B\n");
els
e printf("Grade-C\n");
}
els
e
printf("Student failed\
n"); return 0;
}
#include<stdio.
h> int main()
{
int a, b, c;
printf("Enter angles of
triangle : "); scanf("%d%d
%d", &a, &b, &c);
if(a+b+c==180)
{
if(a==b && b==c)
printf("Equilateral triangle \n");
else if(a==b || b==c || a==c)
printf("Isosceles triangle
\n");
els
e printf("Scalene triangle \n");
}
els
e
printf("Invalid angles
given \n"); return 0;
}
#include<stdio.
h> int main()
{
int month;
printf("Enter month : ");
scanf("%d", &month);
if(month>=1 &&
month<=12)
{
if(month==2)
printf("28 days \n");
else if(month==4 || month==6 || month==9 ||
month==11) printf("30 days \n");
els
e printf("31 days \n");
}
els
e
printf("Invalid month
given \n"); return 0;
}
Introduction to Loops
Note: Block executes only once whereas Loop executes until condition become False
For Loop: We use for loop only when we know the number of repetitions. For example,
Print 1 to 10 numbers
Print Array elements
Print Multiplication table
Print String character by character in reverse order
While loop: We use while loop when we don’t know the number of repetitions.
Display contents of File
Display records of Database table
Do while Loop: Execute a block at least once and repeat based on the condition.
ATM transaction: When we swipe the ATM card, it starts the first
transaction. Once the first transaction has been completed, it asks the
customer to continue with another transaction and quit.
For Loop
for loop: Execute a block of instructions repeatedly as long as the condition
is valid. We use for loop only when we know the number of iterations to do.
Synta Flow
x Chart
for(init ; condition ; modify)
{
statements;
}
C Program to Print 1 to N:
int main(){
int n, i;
printf("Enter n
value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
printf("%d \n", i);
}
return 0;
}
C Program to display A to Z
#include<stdio.
h> int main(){
char ch;
for(ch='A' ; ch<='Z' ;
ch++){
printf("%c", ch);
}
return 0;
}
Fibonacci series: The series in which sum of 2 consecutive numbers will be the next
number
Series: 0, 1, 1, 2, 3, 5, 8, 13, 21,…
int main(){
int i, n, a=0, b=1,
c; printf("Enter
limit : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i+
+){
printf("%d ",
a); c = a+b ;
a=b
;b=
c;
}
return 0;
}
While Loop
While loop: Execute a block of instructions repeatedly until the condition
is false. We use while loop only when don’t know the number of iterations
to do.
Synta Flow
x Chart
while(condition)
{
statements;
}
C Program to Find the Sum of First and Last digits of given number:
int main(){
int n, first, last;
printf("Enter
num : ");
scanf("%d", &n);
first = n
%10;
n=n/10;
while(n>=1
0){
n = n/10;
}
last = n%10;
printf("Sum of First and Last digits : %d \n",
first+last); return 0;
}
printf("Reverse number is : %d \
n", rev); return 0;
}
Palindrome Number Program in C:
The number become same when we reverse is called Palindrome number(121,
1001, 123321) int main(){
int n, rev=0, r,
temp;
printf("Enter
num : ");
scanf("%d", &n);
temp=n;
while(n>0){
r = n%10;
rev = rev*10
+ r; n = n/10;
}
if(temp==rev)
printf("Palindrome Number \n");
else
printf("Not a palindrome number \n");
return 0;
}
int main(){
int n, r, sum=0,
temp;
printf("Enter num :
"); scanf("%d",
&n); temp=n;
while(n>0){
r = n%10;
sum = sum +
r*r*r; n = n/10;
}
if(temp==sum)
printf("Armstrong number \n");
else
printf("Not an Armstrong number \n");
return 0;
}
#include<stdio.
h>
#include<math
.h> int main (){
int num, temp, r1, r2, sq, rev1 = 0, rev2 = 0;
printf("Enter a number
: "); scanf("%d",
&num);
rev1); sq = sqrt(rev1);
printf("Sqrt num : %d \n", sq);
return 0;
}
Continue: A branching statement that terminates the current iteration of loop execution.
#include<stdio.h>
int main()
{
int i;
for(i=1 ; i<=10 ; i++)
{
if(i==5)
continue;
printf("i val : %d \
n", i);
}
return 0;
}
Switch case
Switch: It is a conditional statement that executes specific set of
statements(case) based on given choice. Default case executes if the user
entered invalid choice. Case should terminate with break statement.
Synta FlowCha
x rt
switch(choice)
{
case 1 : Statements ;
break
case 2 : Statements ;
break
......
case n : Statements ;
break
default: Statements ;
}
#include<stdio.
h> int main(){
char ch;
printf("Enter character(r, g,
b) : "); scanf("%c", &ch);
switch(ch)
{
case 'r' : printf("Red \
n"); break;
case 'g' : printf("Green \n");
break;
case 'b' : printf("Blue \
n"); break;
default : printf("Unknown \n");
}
return 0;
}
switch(ch)
{
case 1: c=a+b;
printf("Add result : %d\
n", c); break;
case 2: c=a-b;
printf("Subtract result : %d\
n", c); break;
case 3: c=a*b;
printf("Multiply result : %d\
n", c); break;
case 4: c=a/b;
printf("Division result : %d\
n", c); break;
Do-While Loop
do-while: Executes a block at least once and continue iteration until
condition is false.
Synta Flow
x Chart
do
{
statements;
} while(condition);
if(n%2==0)
printf("%d is even \n", n);
else
printf("%d is odd \n", n);
}while(ch!
='n'); return
0;
}
getch():
getch() is a pre-defined method belongs to conio.h header file.
It is used to read character from the console while program is running.
goto: A branching statement used to send the control from one place to another
place in the program by defining labels.
Program to display 1 to 10 numbers without loop:
#include<stdio.
h> int main(){
int
a=1;
top:
printf("a value : %d \n", a);
++a;
if(a<=10)
goto top;
return 0;
}
if(ch==1){
printf("Enter 2
numbers : \n"); scanf("%d
%d", &a, &b);
printf("Add result : %d\n", a+b);
}
else if(ch==2){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Subtract result : %d\n",
a-b);
}
else if(ch==3){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Multiply result : %d\n",
a*b);
}
else if(ch==4){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Division result : %d\n",
a/b);
}
else if(ch==5){
printf("End \
n"); exit(1);
} }
els
e
}
printf("Invalid
choice \n");
Program to perform Arithmetic operations using (while and switch):
int main()
{
int a, b, c, ch;
while(1){
printf("Arithmetic
Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");
printf("Enter your choice
: "); scanf("%d",&ch);
if(ch>=1 && ch<=4){
printf("Enter 2
numbers : \n"); scanf("%d
%d", &a, &b);
}
switch(ch){
case 1: c=a+b;
printf("Add result : %d\
n", c); break;
case 2: c=a-b;
printf("Subtract result : %d\
n", c); break;
case 3: c=a*b;
printf("Multiply result : %d\
n", c); break;
case 4: c=a/b;
printf("Division result : %d\
n", c); break;
case 5: printf("End\
n"); exit(1);
default: printf("Invalid choice\n");
}
}
}
Nested While loop: Defining a while loop inside another while loop. Loop
execution terminates only when outer loop condition fails.
#include<stdio.
h> int main(){
int x=1;
while(x<=
5)
{
printf("x : %d ->
", x); int y=1;
while(y <= 5)
{
printf("y : %d \t ", y);
++y;
}
printf("\n");
++x;
}
return 0;
}
Output:
x : 1 -> y : y : y : y : y : 5
1 2 3 4
x : 2 -> y : 1 y : y : y : y : 5
2 3 4
x : 3 -> y : 1 y : y : y : y : 5
2 3 4
x : 4 -> y : 1 y : y : y : y : 5
2 3 4
x : 5 -> y : 1 y : y : y : y : 5
2 3 4
Nested for loop:
Defining for loop inside another for loop.
Nested loops are mainly used to process two-dimensional data (Rows & Columns)
Outer loop represents number of rows
Inner loop represents number of columns.
Following program prints the combinations of outer loop and inner loop variable
values:
#include<stdio.
h> int main()
{
int i, j;
for(i=1 ; i<=5 ; i++)
{
for(j=1 ; j<=5 ; j++)
{
printf("(%d,%d)\t", i, j);
}
printf("\n");
}
return 0;
}
Output:
(1,1 (1,2 (1,3 (1,4 (1,5
) ) ) ) )
(2,1 (2,2 (2,3 (2,4 (2,5
) ) ) ) )
(3,1 (3,2 (3,3 (3,4 (3,5
) ) ) ) )
(4,1 (4,2 (4,3 (4,4 (4,5
) ) ) ) )
(5,1 (5,2 (5,3 (5,4 (5,5
) ) ) ) )
Range based programs
C Program to print Even number in given Range:
int main (){
int limit, n;
printf("*****Even Numbers in the Given
Range*****\n"); printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ;
n++){
if(n%2==0)
printf("%d \t", n);
}
return 0;
}
Pattern Programs in C
Basic
Patterns:
int main (){
int i, j;
11111
for (i=1 ; i<=5 ; i++){ 22222
for (j=1 ; j<=5 ; j++){ 33333
printf("%d", i); 44444
} 55555
printf("\n");
}
return 0;
}
int main (){
int i, j;
12345
for (i=1 ; i<=5 ; i++){ 12345
for (j=1 ; j<=5 ; j++){ 12345
printf("%d", j); 12345
} 12345
printf("\n");
}
return 0;
}
int main (){
int i, j;
11111
for (i=1 ; i<=5 ; i++){ 00000
for (j=1 ; j<=5 ; j++){ 11111
printf("%d", i%2); 00000
} 11111
printf("\n");
}
return 0;
}
int main (){
int i, j;
10101
for (i=1 ; i<=5 ; i++){ 10101
for (j=1 ; j<=5 ; j++){ 10101
printf("%d", j%2); 10101
} 10101
printf("\n");
}
return 0;
}
int main (){
int i, j;
55555
for (i=5 ; i>=1 ; i--){ 44444
for (j=5 ; j>=1 ; j--){ 33333
printf("%d", i); 22222
} 11111
printf("\n");
}
return 0;
}
int main (){
int i, j;
54321
for (i=5 ; i>=1 ; i--){ 54321
for (j=5 ; j>=1 ; j--){ 54321
printf("%d", j); 54321
} 54321
printf("\n");
}
return 0;
}
int main (){
char x, y;
AAAA
for (x='A' ; x<='E' ; x++){ A
for (y='A' ; y<='E' ; y++){ BBBB
printf("%c", x); B
} CCCC
printf("\n"); C
DDDD
}
D
return 0; EEEE
} E
#include<stdio.
h> int main (){
char x, y; ABCD
E
for (x='A' ; x<='E' ; x++){
ABCD
for (y='A' ; y<='E' ; y++){ E
printf("%c", y); ABCD
} E
printf("\n"); ABCD
} E
ABCD
return 0;
E
}
#include<stdio.
h> int main (){
int i, j; *****
*****
for (i=1 ; i<=5 ; i++){
*****
for (j=1 ; j<=5 ; j++){
*****
printf("*"); *****
}
printf("\n");
}
return 0;
}
#include<stdio.
h> int main (){
int i, j;
for (i=1 ; i<=5 ; i++){
for (j=1 ; j<=5 ; j++){ ****
*
if(i%2==0)
####
printf("*"); #
else ****
printf("#"); *
} ####
printf("\n"); #
*****
}
return 0;
}
#include<stdio.
h> int main (){
int i, j;
for (i=1 ; i<=5 ; i++){ #*#*
for (j=1 ; j<=5 ; j++){ #
#*#*
if(j%2==0)
#
printf("*"); #*#*
else #
printf("#"); #*#*
} #
printf("\n"); #*#*
#
}
return 0;
}
#include<stdio.
h> int main ()
{ 1
23
int i, j, k=1;
456
for (i=1 ; i<=5 ; i++){ 7891
for (j=1; j<=i ; j++){ 23456
printf("%d", k+
+); if(k>9)
k=1;
}
printf("\n");
}
return 0;
}
#include<stdio.
h> int main ()
{ 12345
int i, j, k=1; 6789
123
for (int i=5 ; i>=1 ; i--){
45
for (j=1; j<=i ; j++){ 6
printf("%d", k+
+); if(k>9)
k=1;
}
printf("\n");
}
return 0;
}
int main ()
{
A
char i, j;
AB
for (i='A' ; i<='E' ; i++) ABC
{ ABCD
for (j='A' ; j<=i ; j++) ABCDE
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Functions in C
Variable: Stores data.
Function: Performs operation on data.
Built in Functions:
C library is a set of header files
Header file is a collection of pre-defined functions.
stdio. conio. string.h graphics.h
h h
printf getch( strlen line()
() ) () circle()
scanf clrscr() strrev bar()
() cetche () …
feof() () strcat
… …. ()
…..
With arguments and No return values (Print ASCII value of given character):
#include<stdio.h>
void
ascii_value(char);
int main(void){
char sym ;
printf("Enter
symbol : ");
scanf("%c", &sym);
asciiValue(sym);
return 0;
}
void asciiValue(char sym)
{
printf("ASCII value is : %d \n", sym);
}
switch(choice){
case 1 : c = add(a,b);
printf("Result : %f\n\
n",c); break ;
case 2 : c = subtract(a,b);
printf("Result : %f\n\
n",c); break ;
case 3 : c = multiply(a,b);
printf("Result : %f\n\
n",c); break ;
case 4 : c = divide(a,b);
printf("Result : %f\n\
n",c); break ;
case 5 : exit(1);
default : printf("Invalid choice \n\n");
}
}
return 0;
}
float add(float x, float y){
return x+y ;
}
float subtract(float x,
float y){ return x-y
;
}
float multiply(float x,
float y){ return
x*y ;
}
float divide(float x,
float y){ return
x/y ;
}
Recursion:
Function calling itself
or
Calling a function from the definition of same function.
#include<stdio.
h> void
recur(void);
void main(){
recur();
}
void recur(){
printf("Starts \
n"); recur();
printf("Ends \
n");
}
Arrays in C
Primitive
type:
Variables are used to store data.
Primitive variable can store only one value at a time.
For example,
int main(){
int
a=5;
a=10;
a=20;
printf("a val : %d \n", a); // prints - 20
return 0;
}
Array:
Array is used to store more than one value but of same type.
For example, storing 100 students’ average marks.
Array creation:
In array variable declaration, we need to specify the size
Array variable stores base address of memory block.
Array elements store in consecutive memory location.
Length of array:
sizeof() function returns the total size of array.
We can find the length of array by dividing total size with single element size.
int main()
{
float arr[5];
printf("Total size of array : %d \n", sizeof(arr));
printf("Array element size : %d \n",
sizeof(arr[0])); printf("Length of Array : %d \n",
sizeof(arr)/sizeof(arr[0])); return 0;
}
C Program to Check First and Last elements Sum equals to 10 or not in Array:
int main (){
int arr[] = {4, 3, 9, 2, 6};
int first =
arr[0]; int last
= arr[4];
if(first+last==
10)
printf("Equals to 10 \n");
else
printf("Not equals to 10 \n");
return 0;
}
C Program to replace the First and Last elements of array with 10:
int main ()
{
int arr[] = {4, 3, 9, 2, 6}, i;
arr[0] = 10;
arr[4] = 10;
printf("Array elements are :
\n"); for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}
void
display(int[]);
int main(){
int a[5] = {10, 20, 30, 40, 50};
display(
a);
return 0;
}
void display(int
x[]){ int i;
printf("Array is :\
n"); for(i=0 ;
i<5 ; i++){
printf("%d\n", x[i]);
}
}
#include<stdio.h>
void reverse(int[],
int); int main(){
int a[5] = {10,20,30,40,50}, i;
printf("Before
reverse : \n"); for(i=0 ;
i<5 ; i++){
printf("%d \n", a[i]);
}
reverse(a,
5); return
0;
}
void reverse(int a[],
int n){ int
i,j,temp;
i=0;
j=n-1;
while(i<j
){
temp=a[
i];
a[i]=a[j];
a[j]=tem
p; i++;
j--;
}
printf("After
reverse : \n"); for(i=0 ;
i<5 ; i++){
printf("%d \n", a[i]);
}
}
printf("Elements are :\
n"); for(i=0 ; i<n ; i+
+){
printf("arr[%d] : %d \t addr : %u\n", i, arr[i], &arr[i]);
}
return 0;
}
printf("Enter size of B
: "); scanf("%d", &n);
printf("Enter %d elements into B : \
n", n); for(i=0 ; i<n ; i++)
scanf("%d", &b[i]);
Linear Search:
Linear Search is used to search for an element in the array.
Linear Search can be applied on Sorted array / Unsorted array.
In linear search, index element starts with key element. If element found
return index else display Error message.
int main(){
int a[30], m, key, i, n,
found=0; printf("Enter
size of array : ");
scanf("%d",&m);
printf("Enter Elements in
array : \n"); for(i=0; i<m; i++)
{
scanf("%d",&a[i]);
}
int main(){
int a[30], b[10], m, n, i;
printf("Enter size of
A : "); scanf("%d",
&m);
printf("Enter %d elements into A : \
n", m); for(i=0 ; i<m ; i++)
scanf("%d", &a[i]);
printf("Enter size of B
: "); scanf("%d", &n);
printf("Enter %d elements into B : \
n", n); for(i=0 ; i<n ; i++)
scanf("%d", &b[i]);
for(i=0 ; i<n ; i++)
a[m+i] = b[i];
Binary Search:
Binary search can be applied to only sorted array.
In binary search, we find the mid location and compare with searching element.
If the searching element less than mid location element, search goes to left side.
If the searching element greater than mid location, search goes to right side.
int main(){
int a[10],m,i,n,k,low,high;
printf("Enter the size of
array : "); scanf("%d",&n);
printf("Enter %d elements \
n",n); for(i=0;i<n;i++)
scanf("%d",&a[i]);
low=0;
high=n-
1;
printf("Enter the key
value : "); scanf("%d",&k);
while(low<=high){
m=(low+high)/2;
if(k<a[m])
high=m-
1; else
if(k>a[m]){
low=m+
1; else
if(k==a[m]){
printf("Element found @ loc : %d\
n",m); break;
}
}
return 0;
}
Bubble Sort:
Simple sorting technique to arrange elements either in Ascending order or
Descending order.
In Bubble sort, the index element compares with the next element and
swapping them if required.
For each pass(inner loop completion) highest element bubbled to last location.
This process continuous until the complete array get sorted.
#include<stdio.
h> int main(){
int arr[7] = {7, 3, 9, 4, 2, 5, 1}, i, j, n=7, t;
for(i=0 ; i<n-1 ; i++){
for(j=0 ; j<n-1-i ; j++){
if(arr[j]>arr[j+1]){
t = arr[j];
arr[j] =
arr[j+1];
arr[j+1] = t;
}
}
}
printf("Sorted
array : "); for(i=0 ;
i<n ; i++){
printf("%d ", arr[i]);
}
return 0;
}
#include<stdio.
h> int main(){
int a[2][2], b[2][2], c[2][2], i, j;
printf("Enter elements of A :
\n"); for(i=0 ; i<2 ; i++)
for(j=0 ; j<2 ; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of B :
\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("Added matrix
is : \n"); for(i=0 ; i<2 ; i+
+){
for(j=0 ; j<2 ; j++){
printf("%d \t", c[i][j]);
}
printf("\n");
}
return 0;
}
#include<stdio.
h> int main(){
int arr[3][3]={{10,20,30},{40,50,60},{70,80,90}} ,I ,j ,temp;
printf("Matrix is: \
n"); for(i=0 ; i<3 ;
i++){
for(j=0 ; j<3 ; j++){
printf("%d\t", arr[i][j]);
}
printf("\n");
}
printf("Transpose of matrix:
\n"); for(i=0 ; i<3 ; i++){
for(j=0 ; j<3 ; j++){
printf("%d\t", arr[i][j]);
}
printf("\n");
}
return 0;
}
#include<stdio.
h> int main()
{
int a[2][2],b[2][2],c[2][2],i,j,k;
printf("Enter array A \
n"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter array B \
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]=0;
for(k=0;k<2;k
++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("Multiplication
array \n"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
return 0;
}
String Handling in C
String:
String is a one-dimensional character array.
String is a collection symbols (alphabets, digits and special symbols).
Strings must be represented with double quotes.
Syntax: Example:
char identity[size]; char name[20];
Memory representation:
We can store only 'n-1' characters into an array of size 'n'.
Last character of every string is '\0'
ASCII value of '\0' character is 0.
int main(){
char name[20];
printf("Enter multi word
name : "); gets(name);
printf("Hello %s \n", name);
}
string.h functions
strlen() :
strlen() returns length of string excluding null character.
Return type is size_t (positive integer)
Prototype is size_t strlen(char s[]);
#include<string.
h> int main(){
char
str[20];
size_t len;
printf("Enter
string : ");
gets(str);
len = strlen(str);
printf("Length is : %u \n",
len); return 0;
}
Program to convert Upper case characters into Lower case without Library
function:
#include<stdio.
h>
#include<string
.h> int main(){
char
src[20];
int i=0;
printf("Enter Upper string
: "); gets(src);
while(src[i] != '\0')
{
if(src[i]>='A' && src[i]<='Z')
{
src[i] = src[i]+32;
}
i+
+;
}
printf("Lower string : %s \n", src);
}
printf("Enter
string : ");
gets(src);
i=0;
j=strlen(src)
-1; while(i<j)
{
temp =
src[i]; src[i]
= src[j];
src[j] =
temp; i++;
j--;
}
printf("Reverse string : %s \n", src);
}
strcmp(): Compare strings are return 0 if equal else return the ASCII
difference between mismatching characters.
#include<string.
h> int main()
{
char s1[20] =
"hello"; char
s2[20] = "Hello";
if(strcmp(s1,s2)==0)
printf("Strings are equal \n");
els
e printf("String are not equal \n");
if(stricmp(s1,s2)==0)
printf("Strings are equal \n");
els
e printf("String are not equal \n");
#include<stdio.h>
int
stringCompare(char[],char[
]); int main()
{
char str1[100],
str2[100]; int
compare;
printf("Enter first
string: "); gets(str1);
printf("Enter second
string: "); gets(str2);
compare =
stringCompare(str1,str2);
if(compare == 1)
printf("Both strings are equal.\n");
else
printf("Both strings are not equal\n");
return 0;
}
int stringCompare(char str1[],char str2[])
{
int i=0,flag=0;
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i]){
flag=
1;
break
;
}
i+
+;
}
if (flag==0 && str1[i]=='\0' &&
str2[i]=='\0') return 1;
els
e return str1[i]-str2[i];
Array variable: stores more than one value but of same type.
Structure variable: stores more than one value of different data types. We
define structures using struct keyword.
struct Employee
{
int id;
char
name[20];
float salary;
};
struct Employee e = {101, "Amar",
35000};
Memory representation:
Note: Structure is a data type and memory allocate to structure only when we create
variable
Structure (Data type) Memory allocation (create
variable)
struct Employee
{
int id; struct Employee e;
char
name[20];
float salary;
};
Program to find the size (memory allocated to structure): sizeof() functions
returns the total number bytes allocated to structure.
#include<stdio.
h> struct Emp{
int id;
char
name[20];
float salary;
};
int main(){
struct Emp x;
printf("size of Emp : %d \n", sizeof(x));
printf("size of Emp : %d \n", sizeof(struct
Emp)); return 0;
}
Accessor (dot operator): We must access the locations of structure through dot(.)
operator
#include<stdio.
h> struct
Employee {
int id;
char
name[20];
};
int main(){
struct Employee e = {101, "amar",
35000}; printf("Employee id : %d \
n", e.id); printf("Employee name :
%s \n", e.name); printf("Employee
salary : %f \n", e.salary); return 0;
}
#include<stdio.
h> struct
Employee {
int id;
char
name[20];
float salary;
};
void display(struct
Employee); int main(){
struct Employee x = {101, "Amar", 35000};
display(
x);
return 0;
}
void display(struct Employee y){
printf("Emp id : %d \n", y.id);
printf("Emp name : %s \n",
y.name); printf("Emp salary :
%f \n", y.salary);
}
Program to define a function that returns structure:
#include<stdio.
h> struct Emp{
int id;
char
name[20];
float salary;
};
struct Emp
collect(); int
main(){
struct Emp
y; y =
collect();
printf("Emp id : %d \n", y.id);
printf("Emp name : %s \n",
y.name); printf("Emp salary :
%f \n", y.salary); return 0;
}
struct Emp collect(){
struct Emp x = {101, "Amar",
35000}; return x;
}
Array of Structures: by creating array type variable to structure data type, we can store
multiple records like Employee details, Customer details, Student details, Account details
etc.
struct struct Emp e; -> store 1 record
Emp{ struct Emp e1, e2, e3; -> store 3
.... records struct Emp arr[100]; ->
store 100 records
}
;
int main()
{
struct Student
s; int i;
printf("Enter Student id and
name : \n"); scanf("%d%s", &s.id,
s.name);
printf("Enter student marks of 5
subjects : \n"); for(i=0 ; i<5 ; i++)
{
scanf("%d", &s.marks[i]);
}
printf("Student details are :
\n"); printf("%d, %s, ", s.id,
s.name); for(i=0 ; i<5 ; i+
+)
{
printf("%d ,", s.marks[i]);
}
return 0;
Store more than one student records including their marks:
#include<stdio.
h> struct
student
{
int id;
char
name[20];
int marks[5];
};
int main()
{
struct student
a[3]; int i,j;
printf("Enter student
details\n"); for(i=0;i<3;i+
+) {
printf("Enter student id and
name\n"); scanf("%d
%s",&a[i].id,a[i].name);
printf("Enter marks of student\
n"); for(j=0;j<5;j++)
scanf("%d",&a[i].marks[j]);
}
printf("Student details
are \n"); for(i=0 ; i<3 ; i+
+) {
printf("%d \t %s \t
",a[i].id,a[i].name);
for(j=0;j<5;j++)
printf("%d\
t",a[i].marks[j]); printf("\n");
}
Nested structures: Defining a structure inside another structure. We access
the elements of nested structure using outer structure reference variable.
#include<stdio.
h> struct Emp
{
int num;
float
salary;
};
struct Employee
{
struct Emp
e; char
name[20];
};
int main()
{
struct Employee x;
printf("Emp name is : %d \
n",x.e.num); printf("Emp name
is : %s \n",x.name); printf("Emp
name is : %f \n",x.e.salary);
return 0;
}
Unions in C
Introduction:
Union is a user defined data type.
Unions were used when memory at premium.
A union basically allows a variable to have more than one type; but only
one of these types can be used.
Syntax: Example:
union identity union Test
{ {
Members; char
}; c;
short
s;
};
STRUCTU UNIO
RE N
Define with struct keyword. Define with union keyword
The size of the structure is equal to the The size of the union is equal to the size
sum of of the
the sizes of its members. largest member.
Each member within a structure is Memory allocated is shared by individual
assigned a members of the union.
unique storage area.
Individual members can be accessed at a Only one member can be accessed at a
time. time.
Altering the value of a member will not Altering the value of any of the member
affect will
other members of the structure. alter other member values.
Program to display size of union: The sum of all sizes of variables defined in
structures is the size of total structure.
#include<stdio.
h> struct st{
char
a;
short
b;
float
c;
};
union un{
char
a;
short
b;
float
c;
};
int main(){
struct st s
; union un
u;
printf("Size of structure : %d \n",
sizeof(s)); printf("Size of union : %d \
n", sizeof(u)); return 0;
}
Accessing members of union: We use dot(.) operator to access the members of union.
Note: We can define any number of variables inside the union, but we cannot
use multiple variables at a time. We will get odd results like follows.
#include<stdio.
h> union un{
int a, b;
};
int main(){
union un u ;
u.a = 10;
printf("b value is : %d \n", u.b);
u.b = 20;
printf("a value is : %d \n",
u.a); return 0;
}
#include<stdio.
h> union un
{
char
a[2]; int
b;
};
int main()
{
union un u
; u.a[0] =
2;
u.a[1] = 3 ;
2. Un-typed: Can points to any type of data. It is also called Generic pointer.
void* -> can points to any data.
Note: Call by reference is preferred when we have to return more than one
variable, like in C programming where we can only return one variable at a time.
Call by reference can be achieved via pointers.
Call By Reference: In this example, the output shows the correct result. This
happens because we have sent the exact address of the variable.
Size of Pointer:
Pointer variable stores address(integer) hence the size of pointer equals to integer
size.
sizeof() function can be used to display the size of each pointer type.
#include<stdio.
h> int main(){
char* a;
short* b;
float* c;
double*
d;
printf("char* size : %d \n",
sizeof(a)); printf("short* size :
%d \n", sizeof(b)); printf("float*
size : %d \n", sizeof(c));
printf("double* size : %d \n",
sizeof(d)); return 0;
}
#include<stdio.
h> int main(){
char x = 'a';
float y = 2.3;
double z =
4.5; char* p1
= &x; float*
p2 = &y;
double* p3 = &z;
printf("p1 value is : %u \n", p1);
printf("++p1 value is : %u \n", +
+p1); printf("p2 value is : %u \
n", p2); printf("++p2 value is :
%u \n", ++p2); printf("p3 value
is : %u \n", p3); printf("++p3
value is : %u \n", ++p3); return
0;
}
Where: “fptr” is a pointer that points to a function which is taking 2 integers and
#include<stdio.
h> void main(){
int i =
100; int*
ip; char*
cp; ip =
&i;
cp = (char*)ip;
printf("i value : %d\n",
*ip); printf("i value :
%d\n", *cp);
}
Pointer to Pointer:
It is also called “double pointer”
A “Pointer to Pointer” variable holds the address of another “Pointer variable”
#include<stdio.
h> int main()
{
int x = 10;
int* px =
&x;
int** ppx = &px;
#include<stdio.
h> int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++)
printf("%d\n", arr[i]);
#include<stdio.
h> void main(){
int a[5] = {10,20,30,40,50}, i;
int *p =
a; p=a;
for(i=0; i<5; i++){
printf("%d\t",a[i]);
printf("%d\t",p[i]);
printf("%d\t",*(p+i));
printf("%d\t",*(i+p));
printf("%d\n",i[p]);
}
}
#include<stdio.
h> int main(){
int arr[5] = {10,20,30,40,50};
int *p = arr;
printf("%d \n", *+
+p);
printf("%d \n",
*(p+2)); printf("%d \
n", *++p+3); return
0;
}
#include<stdio.
h> int main(){
int arr[5] = {10,20,30,40,50};
int *ptr = arr;
printf("%d \n", *(+
+ptr+1)); return 0;
}
#include<stdio.
h> int main(){
int arr[5] = {10,20,30,40,50},i;
int* ptr;
ptr =
arr;
printf("%u\n", *++ptr +
3); printf("%u\n", *(ptr-- +
2) + 5);
printf("%u\n", *(ptr+3)-
10); return 0;
}
#include<stdio.
h> int main(){
int arr[5] = {8, 3, 4, 9, 2},i;
int* ptr;
ptr =
arr;
printf("%u\n", *(--ptr+2) + 3);
printf("%u\n", *(++ptr + 2) - 4);
printf("%u\n", *(ptr-- +1 ) + 2);
return 0;
}
#include<stdio.
h> int main(){
int arr[5] = {5, 2, 7, 3, 6},i;
int* ptr;
ptr =
arr;
printf("%d\n", *(ptr++ + 1) - 2);
printf("%d\n", *(ptr-- + 3) - 10);
printf("%d\n", *(--ptr + 2 )
+ 5); return 0;
}
Pointer to String:
A char* can points to a single character or a String.
Char* holds the base address.
We can process the strings using %s
To process character by character, we use %c
#include<stdio.
h> void main(){
char* s =
"Harsha" ;
printf("%s \n", s);
printf("%c \n", s);
printf("%c \n", *s);
printf("%c \n",
*(s+3));
printf("%c \n",
*s+3);
}
void main(){
char* s = "Sathya" ;
printf("%c \n", *+
+s+2); printf("%c \
n", *++s);
printf("%c \n",
*(s+2));
printf("%c \n", *s--);
printf("%c \n", *--s);
}
#include<stdio.
h> void main(){
char* str =
"learnown";
printf("%c\n", *str++
+ 3); printf("%s\n", +
+str+2);
}
#include<stdio.
h> void main(){
char* str = "learnown";
printf("%c\n" , *(str++ +
2)+3); printf("%c\n" , *+
+str+2); printf("%s\n" , --
str-1);
}
#include<stdio.
h> void main(){
char* str = "learnown";
printf("%c\n",*((str--
+2)+1)-3);
printf("%c\n", *(--str + 3)-
32); printf("%c\n",*(+
+str+2)+4);
}
#include<stdio.
h> void main(){
char sport[ ]=
"cricket"; int x=1 ,
y;
y=x++ + ++x;
printf(“%c”,sport[++y]);
}
Array of Pointers: If the array is Pointer type, it can store multiple references
called Array of Pointers.
#include<stdio.
h> int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
int* ptr[5];
for(i=0 ; i<5 ; i++){
ptr[i] = &arr[i];
}
printf("Array elements are :
\n"); for(i=0 ; i<5 ; i++){
printf("%d \n", *ptr[i]);
}
return 0;
}
Array of Strings:
We can declare an array variable that stores list of pointers(strings base address).
We can process all the strings using array variable.
#include<stdio.
h> int main()
{
char* list[5] = {"C", "Java", "Python",
"Android", "IOS"}; int i;
printf("List is : \
n"); for(i=0 ;
i<5 ; i++)
{
printf("%s \n", list[i]);
}
return 0;
}
#include<stdio.
h> int main()
{
char* list[5] = {"C", "Java", "Python",
"Android", "IOS"}; int i;
printf("List is : \
n"); for(i=0 ;
i<5 ; i++)
{
/* printf("%c \n", list[i]); */
printf("%c \n", *list[i]);
}
return 0;
}
#include<stdio.
h> void main()
{
char *s[ ] = {"black", "white", "pink",
"violet"}; char **ptr[ ] = {s+3, s+2,
s+1, s};
char
***p; p
= ptr;
++p;
printf("%s\n", (*(*p+1)+1)+2);
}
A function returning address:
A function can return address of aggregate data type variable or user
defined data type variable to access the data.
#include<stdio.
h> int*
add(int,int);
void main(){
int a, b, *c;
printf("enter two numbers
: "); scanf("%d
%d",&a,&b);
c = add(a,b);
printf("sum : %d\
n",*c);
}
int* add(int x, int
y) { int z;
z=x+y;
return
&z;
}
Dangling pointer:
In the above code, add function returns the address of local variable.
Local variables will be deleted once the function execution completes.
As we return the address of location, the value of that location may change
by another function before processing the data.
Hence Dangling pointers will not provide accurate results(values).
#include<stdio.
h> int *fun()
{
int x =
5; return
&x;
}
int main()
{
int *p = fun();
fflush(stdin);
printf("%d",
*p); return 0;
}
Where:
() : This operator behaves as function operator.
[] : This operator behaves as array subscription operator.
* : This operator behaves as pointer operator.
Identifier : it is name of pointer variable.
Data type : Data types also includes modifier (like signed int, long double etc.)
How to read following pointer?
char (* ptr)[3]
Step 1: () and [] enjoys equal precedence. So rule of associative will decide the
priority. Its associative is left to right So first priority goes to ().
Step 2: Inside the bracket * and ptr enjoy equal precedence. From rule of
associative (right to left) first priority goes to ptr and second priority goes to *.
Step3: Assign third priority to [].
Step4: Since data type enjoys least priority so assign fourth priority to char.
Dynamic Memory Allocation
Using pointers, we can create variables which are ready to hold addresses of
memory blocks. The size of memory block specified at runtime through Dynamic
memory allocation.
#include<stdio.
h> int main(){
int
x=10;
int* p1;
char*
p2;
p1 = &x;
printf("x value is : %d \n", *p1);
p2 = (char*)p1;
printf("x value is : %d \n",
*p2); return 0;
}
#include<stdio.
h>
#include<stdlib.
h> struct Emp
{
int num;
char
name[20];
float salary;
};
int main()
{
struct Emp* p;
p = (struct Emp*)malloc(sizeof(struct
Emp)); if(p==NULL)
printf("Memory allocation failed \n");
else
printf("Memory allocation success \n");
return 0;
}
#include<stdio.
h>
#include<stdlib.
h> struct Emp{
int num;
char
name[20];
float salary;
};
int main(){
struct Emp* p;
p = (struct Emp*)malloc(sizeof(struct
Emp)); if(p==NULL){
printf("Memory allocation failed \n");
}
else
{ printf("Enter Emp details :\n");
scanf("%d%s%f", &p->num, p->name, &p-
>salary); printf("Name is : %s \n", p->name);
}
return 0;
}
printf("Enter size of
array : "); scanf("%d",
&n);
arr = (int*)calloc(n,
sizeof(int)); if(arr==NULL)
{
printf("Failed in memory allocation \n");
}
else
{ printf("Array elements are : \n");
for(i=0 ; i<n ; i++)
{
printf("%d \n", *(arr+i));
}
}
return 0;
}
printf("Enter size of
array : "); scanf("%d",
&n);
arr = (int*)calloc(n,
sizeof(int)); if(arr==NULL)
{
printf("Failed in memory allocation \n");
}
else
{ printf("Enter array elements : \
n"); for(i=0 ; i<n ; i++)
scanf("%d",
arr+i); for(i=0 ; i<n ;
i++)
sum = sum +
*(arr+i); printf("Sum is :
}
%d \n", sum);
return 0;
}
realloc() :
It is used to increase/decrease the size of array which is created by calloc()
Using calloc(), we can create the size with fixed size
Dynamic memory : Size varies depends on requirement
We can modify the size of array using realloc()
function void* realloc(void* ptr, size_t
size);
#include<stdlib.
h> void main(){
int *p1, *p2, m, n;
printf(“enter size of
array : “);
scanf(“%d”,&m);
p1 =
(int*)calloc(m,sizeof(int));
if(p1 == NULL){
printf(“calloc failed\
n”); exit(1);
}
else
printf(“memory allocated..\n”);
p2=(int*)realloc(p1 ,
n*sizeof(int)); if(p2 == NULL)
{
printf(“realloc failed\
n”); exit(1);
}
else
printf(“memory re-aquired..\n”);
free(p1);
free(p2);
}
free() :
The memory which has allocated dynamically must be released
explicitly using free function.
Function prototype is:
o void free(void* ptr);
Using free() 147unction , we can de-allocate the memory of any type of pointer.
File Handling in C
FILE* pointer:
FILE is a pre-defined structure type variable.
FILE* can points to any type of file.
Once we make the pointer pointing to a file, then we can perform all FILE
operations such as reading, writing, appending and so on.
Modes of Files:
Read mode(“r”):
Opens file in Read mode.
If file is present, it opens and returns pointer to that file.
If file is not present, it returns NULL pointer.
Write mode(“w”):
Opens file in Write mode.
If file is present, it opens and removes the existing contents of File.
If file is not present, it creates the new file with specified name.
Append mode(“a”):
Opens file in append mode.
If file is present, it opens and places the cursor at the end of existing data to
add the new contents.
If file is not present, it creates the new file with specified name.
Opening a File:
fopen() is a pre-defined function that opens a file in specified mode.
On success, it opens and returns the pointer to file.
On failure, it returns NULL pointer.
FILE* fopen(char* path, char* mode);
#include<stdio.
h> int main(){
FILE* p;
p=
fopen("c:/users/srinivas/desktop/code.c",
"r"); if(p==NULL)
printf("No such file to open \n");
else
printf("File opened in read mode \n");
return 0;
}
Reading File character by character:
fgetc() is a pre-defined function belongs to stdio.h
fgetc() function read the input file character by character.
On success, it reads the character and returns ASCII value of that character
On Failure, it returns -1(EOF)
int fgetc(FILE* stream);
#include<stdio.
h> int main(){
FILE* p;
int ch;
p = fopen("code.c",
"r"); if(p==NULL)
{
printf("No such file to open \n");
}
els
e
printf("File contents : \
{
n");
while((ch=fgetc(p)) !=
-1)
{
printf("%c", ch);
}
}
return 0;
}
#include<stdio.
h> int main(){
printf("EOF value is : %d \n",
EOF); printf("EOF character is :
%c \n", EOF); return 0;
}
Closing the File: fclose() is used to close the file after use.
It is recommended to release every resource(file) after use.
On success, it returns 0.
On Failure, it returns -1.
int fclose(FILE* stream);
We must release Resource (File, Database) after use. Improper shutdown causes
#include<stdio.
h> int main(){
FILE* p;
int r1, r2;
p = fopen("code.c",
"r"); if(p != NULL){
r1 = fclose(p);
printf("On success : %d \
n", r1); r2 = fclose(p);
printf("On failure : %d \n", r2);
}
return 0;
}
#include<stdio.
h> int main(){
FILE *src,
*dest; int ch;
src = fopen("code.c", "r");
dest = fopen("output.txt",
"w"); if(src != NULL){
while((ch = fgetc(src)) !=
EOF){ fputc(ch,
dest);
}
printf("Data copied...\
n"); fclose(dest);
fclose(src);
}
return 0;
}
fseek(): It is used to move the cursor position in the opened file, to perform
read and write operations.
int fseek(FILE* steam, long offset, int origin);
Parameters:
“offset” is a long type variable that represents the number of bytes to move.
o Positive offset moves the cursor in forward direction
o Negative offset moves the cursor in backward direction.
Origin comes with
o SEEK_SET : Start of the file
o SEEK_CURR : Current cursor position
o SEEK_END : End of the file
On success, if specified location is present, it moves the cursor and returns 0
On failure, it returns -1.
#include<stdio.
h> int main(){
FILE* p;
int ch;
p = fopen("code.c",
"r"); if(p==NULL){
printf("No such file to open \n");
}
else{
fseek(p, 100, SEEK_SET);
while((ch=fgetc(p)) !=
-1){ printf("%c",
ch);
}
fclose(p);
}
return 0;
}
#include<stdio.
h> int main(){
FILE* p;
int ch;
p = fopen("code.c",
"r"); if(p==NULL){
printf("No such file to open \n");
}
els
e{ fseek(p, -50, SEEK_END);
while((ch=fgetc(p)) !=
-1){ printf("%c",
ch);
}
rewind(p);
while((ch=fgetc(p)) !=
-1){
printf("%c", ch);
}
fclose(p);
}
return 0;
}
It reads “size” bytes from specified “stream” and stores into “str”.
On Success, it returns the pointer to string that has read.
On failure, it returns NULL pointer.
It reads only size-1 characters into String every time. Last character of
every string is null(\0) by default.
#include<stdio.
h> int main(){
FILE* p;
char str[10];
p = fopen("code.c",
"r"); if(p==NULL){
printf("No such file to open \n");
}
else
{ fgets(str, 10, p);
printf("The string is : %s \n",
str); fclose(p);
}
return 0;
}
Reading the complete file using fgets():
#include<stdio.h>
int main(){
FILE* p;
char str[10];
p = fopen("code.c",
"r"); if(p==NULL){
printf("No such file to open \n");
}
else{
while(fgets(str, 10, p)){
printf("%s \t", str);
}
fclose(p);
}
return 0;
}
#include<stdio.
h> int main(){
FILE *src,
*dest; char
str[10];
src = fopen("code.c",
"r"); if(src==NULL){
printf("No such file to open \n");
}
else{
dest = fopen("data.txt",
"w"); while(fgets(str, 10,
src)){
fputs(str, dest);
}
printf("Contents
copied...\n"); fclose(src);
fclose(dest);
}
return 0;
}
feof():
It used to test whether End of File has reached or not
It returns -1 when End of File has reached else returns 0
int feof(FILE* stream)
#include<stdio.
h> int main(){
char old[20] = "data.txt";
char new[20] = "modified_data.txt";
if(rename(old, new)==0)
printf("successfully renamed...\n");
else
printf("Failed in renaming the file...\n");
return 0;
}
#include<stdio.
h> int main()
{
char target[20] = "data.txt";
if(remove(target)==0)
printf("successfully removed...\n");
else
printf("Failed in removing the file...\n");
return 0;
}
Enumeration in C
Introduction:
An enumeration consists of a set of named integer constants.
Each enumeration-constant in an enumeration-list names a value of the
enumeration set.
Syntax:
enum identifier
{
enumerator-list
};
Introduction:
typedef is a user-defined data type specifier.
Using typedef we can define identifiers (synonyms) for data types.
We can use synonyms instead of original data types.
Advantage: Synonyms to data types become more readable than complex identities
#include<stdio. #include<stdio.
h> typedef h> struct Emp{
struct Emp{ int eno;
int eno; char*
char* ename;
ename; float esal;
float esal; };
} int main()
Employee
{
; int
typedef struct Emp
main()
Employee; Employee e;
{
}
Employee e;
}
Introduction:
We need to specify the storage class along with datatype in variable declaration.
Storage class describes
o Memory location of variable
o Default value of variable
o Scope of variable
o Lifetime of variable
Storage classes classified into
o Automatic Storage classes
o Register Storage classes
o Static Storage classes
o External Storage classes
Syntax:
storage_class datatype name ;
Example:
auto int a
; static int
b;
Block scope of a variable:
Defining a variable inside the block.
We can access that variable from the same block only.
We cannot access from outside of the block or from other block.
#include<stdio.
h> int main()
{
{
int a=10;
printf("a val : %d \n", a);
}
{
int b=20;
printf("b val : %d \n", b);
printf("a val : %d \n", a); // Error :
}
return 0;
}
Function scope of a variable:
Defining a variable inside the function.
We can have number of blocks inside the function.
Function scope variable can access throughout the function and from all
block belongs to that function.
#include<stdio.
h> int main()
{
int a=10; /* function scope */
{
int a=20; /* block scope */
printf("Inside First block, a val : %d \n", a);
}
{
printf("Inside Second block, a val : %d \n", a);
}
Note: If we don’t provide any value to local variable, by default the value is
“Garbage value” #include<stdio.h>
int main()
{
int
a;
{ int a=10;
printf("a val : %d \n", a);
return 0;
}
Program scope:
Defining a variable outside to all function
We can also call it as Global variable
We can access the global variable throughout the program.
#include<stdio.
h> void
test(void);
int a=10; /*program
scope*/ int main(){
int a=20; /*function scope */
{
int a=30; /*block scope
*/ printf("In block : %d \
n", a);
}
printf("In main : %d \
n", a); test();
return 0;
}
void test(){
printf("In test : %d \n", a);
}
Note: auto variables must be local. If we don’t give storage class to local variable,
it is auto default.
#include<stdio.
h> int main(){
auto int a=10;
{
auto int a;
printf("In block : %d \n", a);
}
printf("In main : %d \
n", a); return 0;
}
Note: Repeated variables in the logic must be defined as register variables. For example
“Loop counters”
#include<stdio.
h>
register int
a=30; int
main()
{
auto int a=10;
printf("In main : %d \
n", a); return 0;
}
#include<stdio.
h> static int
x=10; void
test();
int main(){
static int y;
printf("y val : %d \
n", y); test();
return 0;
}
void test()
{
printf("x val : %d \n", x);
}
Note: External variables always global variables. These variables get memory
only when we initialize with any value.
The declaration statement will not consider, memory allocates only when we
assign value:
#include<stdio.
h> extern int
a; extern int a;
extern int a;
extern int
a=10; int
main()
{
printf("a value is : %d \
n", a); return 0;
}
Command Line Arguments in C
Accepting Command Line arguments:
Every C application runs by Computer Operating System. OS runs the
program from its environment. Every OS consists CUI and GUI mode. To read
command line arguments, we need to run the C program from CUI OS mode.
Code
program:
#include<stdio.
h> int main(){
printf("Hello...\
n"); return 0;
}
Note: save into "turboc" folder with name Program.c
Execution:
C:/turboc>Program.exe
-> Generate output.
main() prototype: Regular main() function prototype is slightly different from the
main() function taking command line arguments. We must define main() function
as follows
int main(int argc , char* argv[ ])
wher
e: ‘argc’ = argument count ( Number of arguments passed at command line
name including file ‘argv’ = argument vector(list) (List of arguments - default type is
)
String)
cmd/> Program
Output : Count
is : 1
cmd/> Program 10 20 30
40 50 Output : Count is : 6
int x =
atoi(s1); int
y = atoi(s2);
} printf("Sum is : %d \n" , x+y);
return 0;
}
cmd/> Program
Output : Insufficient input values
cmd/> Program 10
20 Output : Sum is
: 30
Pre-Processor in C
Introduction:
Pre-processor program that modifies the text of a C program before it is compiled.
Pre-processing includes
o Inclusion of other files
o Definition of symbolic constants and macros
o Conditional compilation of program code
o Conditional execution of preprocessor directives
and a main program called ‘program.c’ that uses the header file, like this,
#include
"header.h" int
main (void)
{
x=biggest(10,2
0); printf(“big :
%d”,x); return
0;
}
Macros(#define):
We use #define to create Macro constants.
Constants recommended to define in Upper case.
At the time or pre-processing all Macros replaced with their values.
Syntax:
#define identifier replacement-text
Example:
#define PI 3.14159
Function-like Macros
You can also define macros looks like a function call.
For example,
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
Would cause
area = CIRCLE_AREA( 4 );
To become
area = ( 3.14159 * ( 4 ) * ( 4 ) );
#if directive:
It is conditional compilation directive. If the condition is valid then the
code defined inside the block gets compiled.
Syntax:
#if <Constant_expression>
#endif
}
#end
if
#include<stdio.
h> int main()
{
int var =
5; #if var
printf("%d",var);
#else
printf("%d",var);
#end
if
return 0;
}
Compile time Error: Directive #if will not think expression constant var as
integer variable and also it will not throw an error. Then what is var for directive
#if?
if
return 0;
}
Program to display System date using pre-defined Macro constant:
#include<stdio.h>
int main(){
#ifdef DATE
printf("%s", DATE );
#else
printf("First define the DATE ");
#endif
return 0;
}
Output: It will print current system date.
Explanation: DATE is global identifier. It has already defined in the header file
stdio.h and it keeps the current system date.
#end
if
return 0;
}
Output: It will print current system time.
Explanation: TIME is global identifier. It has been defined in the header file
stdio.h. Compiler doesn’t compile the c codes which are inside the any
conditional preprocessor directive if its condition is false. So we can write
anything inside it.