C Language Class Room Notes
C Language Class Room Notes
Notes Link:
https://bit.ly/shiwac9am
C Language 9 AM Page 1
Monday, January 31, 2022 10:38 AM
C-Language Basics
Operators
Control Structures
Functions
Arrays
Strings
Pointers
User-defined types [structures, unions, enumerations]
Files
Miscellaneous
C Language 9 AM Page 2
C-Language
Friday, January 21, 2022 9:30 AM
Hardware:
• Is a group of computer peripherals.
• All computer parts are comes under HARDWARE.
Software:
• is a set of programs
• Program => is a set of instructions
ATM Software:
Withdraw
Check Balance
Deposit
SOFTWARE
date
time
md
cd
copy con
C Language 9 AM Page 3
Media Player Software
Play Program
Stop Program
Pause Program
Types of Software:
2 Types:
• System Software
• Application Software
System Software:
• The software which is used run & manage the
functionality of the computer
Examples:
Operating System [OS]
Compiler
Interpreter
Device Driver
Operating System:
• is mediator b/w user & machine
• It allows us to communicate with the machine.
Exs:
Windows OS MS DOS OS LINUX UNIX
Compiler:
High Lebel Languages:
print 'hello'
• Human understandable
languages
11110
Low level languages:
machine understandable languages
C Language 9 AM Page 4
HLL
LLL
print 'hello'
10010110
Compiler /
Interpreter
Compiler:
• is a translator.
• is mediator b/w HLL & LLL
• translates High Level instructions to low level instructions
• translates all instructions at a time and places in particular
file
Interpreter:
• is a translator.
• is mediator b/w HLL & LLL
• translates High Level instructions to low level instructions
• translates line by line & submits it to micro processor
C Language 9 AM Page 5
compile => put together / assemble
…..
……
….
C Language 9 AM Page 6
OS => Printer Drivers => Printer
Hardware Software
2 Types:
System Software =>
OS Compiler Interpreter Device Driver
Application Software
Application Software:
• is the software that is used to perform particular
kind of applications.
C Language 9 AM Page 7
Oracle SQL Server MySQL
C-Language:
• introduced in 1972.
• Dennis Ritchie & his team developed this
language.
• developed at AT & T Lab , USA.
• Dennis Ritchie is founder of C-Language
AT & T Lab got a project to
develop UNIX OS in 1970.
selected B-Language to develop
UNIX
Machine Language:
• in this, we write code in the form 0s and 1s
Disadvantages:
• writing code is difficult
• not portable
Assembly Language:
• we write code in the form of mnemonics
mnemonic Exs: ADD DIV MOV
• Assembler => is the first translator
introduced in the world
• Assembler translates assembly language
code to low level language.
Disadvantages:
• difficult to write the code
• not portable
General Purpose P L:
1 Language => many kinds of applications
Purpose of C-Language:
• Using C-Language we can develop system
software & application software.
Features of C-Language:
• General Purpose P L
• Middle Level P L
• Portability
• Modularity
• Extendibility
• Compiled
• General Purpose P L:
• 1 Language => many kinds of applications
• General Purpose P L:
• 1 Language => many kinds of applications
Application Software:
Google Chrome
System Software:
Mozilla Firefox
Windows OS
Photoshop
UNIX OS
Maya
Advanced programming languages
compilers & interpreters
Winamp
MS Office
Oracle My SQL
HLL:
Middle Level Programming Language: • programmer friendly
• Application Software
Middle Level = HLL features +LLL features • Ex: Java VB python
Computer
Software
Hardware
set of programs
a group of computer set of instructions => program
C Language 9 AM Page 10
Software
Hardware
set of programs
a group of computer set of instructions => program
peripherals
System s/w Appln s/w
Portability:
C-Program developed in one system can run on any other
system even if OS is different.
hello.c
…
…. Source Code [HLL]
…
C-Compiler
hello.exe
…
Machine code /
…
Native Code [OS understandable code]
OS
Output
Machine-1 [Windows ]
C Language 9 AM Page 11
hello.c Machine-2 [Windows]
Case-1:
hello.exe
… Same OS
…
….
…
… Place .exe file
Machine-1 [Windows]
Hello.java
machine-2 [windows]
…
Source Code Hello.class
…
javac
JVM
Hello.class
..
Byte Code
…
java
Hello.exe
.. Machine Code
C Language 9 AM Page 12
hello.cs => csc => IL Code => CLR => .exe
hello.py => pyc => Byte Code => PVM => .exe
Modularity:
• C-Language is modular / procedure-oriented / function-oriented
programming language.
• modular / procedure-oriented => programming approach [style]
• In modular / procedure-oriented style, we write program in the
form of functions.
• C-Program we write in the form of functions. 'C' is a modular /
Procedure-oriented / function-oriented programming language.
In this, we divide large program into small parts. Every part is
called function.
Procedure-Oriented approach:
we write program in the form of functions.
Ex: C-Language
Object-Oriented Approach:
we write program in the form of classes & objects.
Ex: Java
Features of C-Language:
Extendibility:
C-Library
Compiled:
C Language 9 AM Page 14
interpreted programming language.
• To improve the performance C-Language developed as
Compiled Programming Language
Features of C-Language:
Structure of C-Program:
C-Language is a procedure-oriented programming language.
We write program in the form of functions.
//global declaration
//function declaration
//preprocessor directives
function-1()
{
//local declaration Syntax to define a function:
//statements
} <return_type> <function_name>([<argument_list>])
function-2() {
{ //Statements
//statements }
}
.
.
function-n()
{
//statements
}
main()
{
//call other functions
}
C Language 9 AM Page 15
main() :
built-in functions:
pow()
• is a user-defined function.
sqrt()
• is an entry point of the program.
• every c-program execution starts
user-defined function:
from "main" only.
nareshit()
ramu()
#include<stdio.h>
main()
{
printf("hello");
}
1. Text Editor
[Notepad, Wordpad, MS Word]
[Edit plus Notepad++]
2. C-Compiler
[GNU C-Compiler]
[Dell C-Compiler]
[IBM C-Compiler]
[Turbo C-Compiler]
IDEs / SDKs
[Integrated Development Environment]
[Software Development Kit]
C Language 9 AM Page 16
[Software Development Kit]
• Text Editor
• C-Compiler
• Other features
C Language 9 AM Page 17
Wednesday, January 26, 2022 9:22 AM
main():
• is a user-defined function.
• is entry point of the program.
• every program execution starts from main.
printf():
• is a built-in / predefined function.
• defined in "stdio.h" header file.
• used to print the data on console
screen.
#include<stdio.h>:
#include<stdio.h>:
with this line "stdio.h" header file code will be
included into the program. This header file has 300+
lines code is there. This code will be attached in
program. After that program will be compiled.
• Character Constant
• are used to print non-printing characters like
" ' \ new line …etc
these are used in printing statements like
C Language 9 AM Page 18
• these are used in printing statements like
"printf()".
• Escape sequence has a \ and a following
meaningful character.
Data:
is a collection of facts about people or places or
things.
Ex: 25 Ravi A 67.89
int rno=25;
25 => Data
rno==> variable
int => data type
Ex:567 23 89 -678
Data Types in C
int
Primitive / Derived User-defined 56
Predefined / 89
System-defined Array Structure 345
String Union
student
Pointer Enumeration
25 ravi A 56.78
Number Related Character Related
char
Integer Floating Point
Ex: 'A' 'B' 'M'
Variable =>
• is a name of storage location.
• It contains the data.
• It can hold one value only at a time.
Ex:
int age=25;
..
..
age=30;
Declaring variable:
Syntax:
<data_type> <variable1>[,<v2>,<v3>,………];
Ex:
int age;
Assigning value:
Syntax:
<variable> = <constant> / <variable> / <expression>;
C Language 9 AM Page 20
Assigning value:
Syntax:
<variable> = <constant> / <variable> / <expression>;
age=25;
x=50;
y=x;
z = x+y;
Exs:
x y int %d or %i
C Language 9 AM Page 21
Program to add two number:
x y int %d or %i
20 30
z=x+y
20+30 = 50
print z
#include<stdio.h>
main() Output
{
int x,y,z; sum=50
x=20;
y=30;
z = x+y;
printf("sum=%d",z);
}
Assignment-1: Assignment-2:
calculate x+y*z
find area & perimeter
of rectangle
calculate (x+y)*z
a = l*b
p = 2*(l+b)
int %d (or) %i
float %f
char %c
#include<stdio.h>
main() Output:
{
float pi=3.14,r=45.6,a,p; area=….
perimeter=….
a = pi*r*r;
p = 2*pi*r;
printf(" area=%f",a);
C Language 9 AM Page 22
printf(" area=%f",a);
printf("\n perimeter=%f",p);
}
area = l*b
b=15.4
perimeter = 2*(l+b)
l=38.9
h=65.2
b=78.9
area = (b*h)/2
Output:
Section: A #include<stdio.h>
marks: 786 main()
avrg marks: 78.6 {
char sec='A';
int m=786;
float a=78.6;
printf("Section:%c\nMarks:%d\navrg marks:%f",sec,m,a);
}
%d (or) %i int
%f float
%c char
%s string
%o octal
%x (or) %X hexa decimal
String:
• String is a group of characters.
• String constant must be enclosed in double quotes.
char x;
x can hold 1 char only
char x[10]="raju";
x can hold 10 chars
x is string
10 max size
C Language 9 AM Page 23
Program to print a string:
Output
#include<stdio.h> Hi vijay
main()
{
char x[20] = "vijay"; //20 Bytes
printf("Hi %s",x);
}
Output:
empid: 1234
ename: Ravi
salary: 8000.00
job: clerk
gender: M
Number System:
30
oct %o
hex %x (or) %X
dec %d (or) %i
#include<stdio.h>
Output:
main()
dec value=30
{
C Language 9 AM Page 24
program to print decimal, octal & hexa decimal value:
#include<stdio.h>
Output:
main()
dec value=30
{
oct value=36
int x=30;
hex value=1e
hex value=1E
printf("dec value=%d\n",x);
printf("oct value=%o\n",x);
printf("hex value=%x\n",x);
printf("hex value=%X\n",x);
}
printf() =>
used to print the data on console screen
output related function.
scanf():
• is a built-in function.
• input related function.
• included in "stdio.h" header file.
• used to read the data from keyboard.
Reading an integer:
age
int age;
4 Bytes
4567 => &age
printf("Enter age:");
scanf("%d",&age);
float avrg;
printf("Enter average:");
scanf("%f",&avrg);
Reading a character:
char sec;
C Language 9 AM Page 25
Reading a character:
char sec;
printf("Enter section:");
scanf("%c",&sec);
Reading string:
char name[10];
scanf("%s",name);
Output:
Enter x: 6 main()
Enter y: 4 {
sum=10 int x,y,z;
printf("Enter x:");
scanf("%d",&x);
printf("Enter y:");
scanf("%d",&y);
sum= z=x+y;
printf("sum=%d",z);
}
b area = l*b
perimeter = 2*(l+b)
l
main()
{
float l,b,a,p;
a = l*b;
p = 2*(l+b);
C Language 9 AM Page 26
p = 2*(l+b);
printf("area=%f \n perimeter=%f",a,p);
}
Assignment:
main()
{
char sec;
int m;
float a;
printf("Enter section,marks,avrg:");
scanf("%c%d%f",&sec,&m,&a);
Assignment:
C Language 9 AM Page 27
Enter your name: Raju
Hi Raju
#include<stdio.h>
main() declare string
{
char name[20]; read string
4/2 = 2
/ => division operator
In C => 5/2 = 2 =>
it gives quotient value
int/int = int
5.0/2 =2.5
5/2.0 = 2.5
5.0/2.0 = 2.5
average of 3 numbers:
x y z
10 20 31
C Language 9 AM Page 28
(x+y+z)/3 = 20
(x+y+z)/3.0 = 20.333
(x+y+z)/a = ?
int x,y,z,a;
(float)(x+y+z)/a (or)
(x+y+z)/(float)a (or)
(float)(x+y+z)/(float)a
#include<stdio.h>
main()
{
int x,y,z;
float avrg;
printf("Enter 3 numbers:");
scanf("%d%d%d",&x,&y,&z);
printf("average=%f",avrg);
}
x y
20 30
C Language 9 AM Page 29
x y
20 30
x y
20 30
temp
#include<stdio.h>
main()
{
int x,y,temp;
printf("Enter 2 numbers:");
scanf("%d%d",&x,&y);
temp=x;
x=y;
y=temp;
printf("x=%d \t y=%d",x,y);
}
x y
x y
20 30 After swap 30 20
C Language 9 AM Page 30
Integer type:
long int
4 bytes
int 4 bytes
30 => 11110
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0
sign
Data [15 bits]
bit
In 16 bits,
1 bit => sign bit
15 bits => Data
C Language 9 AM Page 31
is the 16 bits min value
0 to 65535
size of operator:
• used to know size of data type or variable
Syntax:
sizeof(data_type / variable)
Example:
sizeof(int) => 4
size of(char) => 1
sizeof(double) => 8
short int x;
sizeof(x) => 2
int size=4
#include<stdio.h>
main()
{
short int x;
printf("int size=%d\n",sizeof(int));
printf("dbl size=%d\n",sizeof(double));
printf("long dbl size=%d\n",sizeof(long double));
printf("char size=%d\n",sizeof(char));
printf("x size=%d",sizeof(x));
}
limits.h
Macro [symbolic constant]
shrt_max = 32767
C Language 9 AM Page 32
shrt_max = 32767
shrt_min = -32768
int_max
int_min
long_max
long_min
long_long_max
long_long_min
ushrt_max
uint_max
ulong_max
ulong_long_max
float.h
MACRO constant
FLT_DIG 6
DBL_DIG 15
LDBL_DIG 18
FLT_MAX
FLT_MIN
DBL_MAX
DBL_MIN
LDBL_MAX
LDBL_MIN
%e (or) %E Scientific
C Language 9 AM Page 33
C-Language Tokens:
C-Token =>
A smallest individual part of the program.
Ex:
int x=40, y=50;
• Identifier
• Keyword
• Constant
• Operator
• Separator
Identifier:
The names of variables, int x,total;
functions, structures, labels or any
user-defined name is called add()
"Identifier". {
Ex: x, total => variable names }
add => function name struct student
student => structure name {
}
Ex:
int float; //invalid
int if; //invalid
int INT; //valid
C Language 9 AM Page 34
Keywords:
• Keywords are the reserved words.
• Every keyword has specific meaning & can perform
particular functionality.
• We cannot use them as identifiers.
• 44 Keywords are available in C-17 version.
Constants:
Constants are the fixed values. We cannot change
them.
Example:
25 567 18 => Integer Constants
Operators:
a+b a>b
- m<40
a*b m>=40
/
Separators:
int x,y;
; => statement separator
float z;
, => variable separator
[] => subscript separator
() => expression separator
{} => block separator
Features of C-Language
Structure of C-Program
main()
printf()
Escape sequences
Data Types
Declaration, Assignment & Initialization
int x=45; //Initialization
int x;
x=30; //Assignment
Format Specifiers
scanf()
Sizes & Ranges
C-Language Tokens
C Language 9 AM Page 35
Operators
Friday, February 4, 2022 9:37 AM
Operator:
• is a symbol that is used to perform operations
like arithmetic or logical operations.
• Ex: Arithmetic => a+b a-b a*b
• Ex: Logical => a>b m>=40 m<40 age<18
• Operand : The variable that is participating in b*b-4*a*c => Expression
operation.
• Ex: a+b a,b are operands *
• Expression = Operators + Operands + Numbers -
• Exs: x+y x+y*z 2*pi*r b*b-4*a*c a,b,c => operands
Types of Operators:
• According to number of operands
• According to operation [purpose]
Unary Operators :
If one operand participates in operation then it is called
"UNARY OPERATOR".
++ -- -
x=5
Ex: x++ -x x-- x++
x=6
x=5
x = -x => -(5)
Binary Operator:
If two operands participate in operation then it is
called "BINARY OPERATOR".
+ * - / >
Ex: a+b a*b a-b a/b a>b
a+b+c
C Language 9 AM Page 36
Ternary Operator:
If 3 operands are participate in operation
then it is called "Ternary Operator".
Ex: ?:
Arithmetic + - * / %
modulus
Relational / < <= > >= == !=
Comparison equals not equals
Logical && || !
And Or Not
Assignment = += -= *= /= %=
Bitwise & | ^ << >> ~
bw bw bw left shift right shift bw not/
and or xor complement
Miscellaneous ++ Increment
-- Decrement
- Unary Minus
?: Ternary / Conditional
sizeof Size of operator
& Address Of
* pointer
. dot [direct member access]
-> arrow [indirect member access]
Arithmetic Operators:
are used to perform Arithmetic Operations like
addition, subtraction.
+ Addition
subtraction
C Language 9 AM Page 37
- subtraction
* multiplication
/ Division
% Modulus
x=5 y=2
x=5.0 y=2
#include<stdio.h>
main()
{
int age;
C Language 9 AM Page 38
int age;
printf("Enter age:");
scanf("%d",&age);
if(age>=18)
printf("eligible");
else
printf("not eligible");
}
if(n%2==0) if(n%2==0)
printf("Even"); printf("Even");
if(n%2!=0) else
printf("Odd"); printf("Odd");
== =
x==50 x=50
C Language 9 AM Page 39
Program to find result of a student
for 1 subject:
maths =>
max marks: 100
min marks: 40 => for pass
if(m>=40)
printf("PASS");
if(m<40)
printf("FAIL");
x > y
50 > 40 if(x>y)
50 is big pf("x is big");
x else
pf("y is big");
Logical Operators:
are used to perform logical operations.
&& And
|| Or
! Not
c1 c2 c1 && c2 c1 || c2
T T T T
T F F T
F T F T
F F F F
C Language 9 AM Page 40
And, Or are used to write multiple conditions
if(age<18 || age>25)
printf("not eligible");
age=16
else
printf("eligible");
&& &
C Language 9 AM Page 41
|| |
Logical OR Bitwise OR
Examples:
job sal
-------- ------
if(job=='CLERK' || job=='MANAGER')
clerk 10000
manager 15000
salesman 8000
manager
manager
clerk
clerk
salesman
analyst
the emp whose salry is b/w 10000 to 20000 => 10% sal
remaining emps => 5%
read gender
if(gender=='M' || gender=='F')
printf("ur gender is %c",gender);
else
printf("invalid char");
C Language 9 AM Page 42
m p c
max marks: 100
min marks: 40 in each sub => pass
Read m,p,c
c1 Not(c1)
T F
F T
read m
main() a) hello
{ b) blank
int x=0; c) error
if(!x)
printf("hello"); //hello
}
if(1)
C Language 9 AM Page 43
printf("hello"); //hello
}
if(1)
printf("hello");
if(0)
printf("hi");
In C/C++,
main()
{
int x=5;
printf("%d\n",x==5); //1
printf("%d",x>5); //0
}
! =>
c=> T !c=> F
c=>F !c=> T
Assignment Operators:
are used to assign the values.
= Simple Assignment
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulus Assignment
C Language 9 AM Page 44
%= Modulus Assignment
x=5
x=x+20 x+=20
Increment Operator:
• Symbol => ++
• unary operator
• It is used to increase 1 value of the variable.
• can be used in 2 ways:
○ Post Increment [x++]
○ Pre Increment [++x]
main() main()
{ {
int x=8; int x=8;
x++; ++x;
printf("%d",x); printf("%d",x);
} }
C Language 9 AM Page 45
In case of Assignment:
main() main()
{ {
int x=6,y; int x=6,y;
y=x++; y=++x;
printf("x=%d\n",x); printf("x=%d\n",x);
printf("y=%d\n",y); printf("y=%d\n",y);
} }
x=7 x=7
y=6 y=7
In case of Printing:
main() main()
{ {
int x=5; int x=5;
printf("%d\n",x++); printf("%d\n",++x);
printf("%d\n",x); printf("%d\n",x);
} }
Decrement Operator:
• Symbol: --
• unary operator
• It is used to decrease 1 value of the variable.
• can be used in 2 ways:
○ Post Decrement (x--)
○ Pre Decrement (--x)
C Language 9 AM Page 46
main() main()
{ {
int x=7; int x=7;
x--; --x;
printf("%d",x); //6 printf("%d",x); //6
} }
It is used to
convert +ve value to -ve value
or
-ve value to +ve value.
size of operator:
• Symbol: sizeof
• It is used to find size of data type
or variable.
Ex:
sizeof(int) => 4
sizeof(double) => 8
sizeof(char) => 1
short int x;
sizeof(x) => 2
C Language 9 AM Page 47
Bitwise Operators:
• used to work with the bits 0s,1s.
• are used for Low Level Programming
like compiler design, OS symbol tables
• implement security techniques like
encryption & decryption.
Encryption =>
Plain Text to Cipher Text
hello zqwwr
Truth Table
1 => TRUE / ON
0 => FLASE / OFF
x y x&y x|y x^y
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
C Language 9 AM Page 48
Binary to Decimal [+ve]:
C Language 9 AM Page 49
0011 1010 0011 1100
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0
x = 12
x>>2 = ?
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0
x ~x
1 0
0 1
C Language 9 AM Page 50
Binary to Decimal [-ve]:
x=20
y=25
Syntax:
x=50 y=40
if(x>y)
x big = x>y ? x : y
else
y
C Language 9 AM Page 51
Program to check whether the given number is
even or odd using ternary operator:
Address of Operator:
• Symbol: &
• is used to access the address of variable
x
int x;
x=50; 4 Bytes 50
int x;
x=50;
Operator Precedence:
• Precedence => Order / Priority
Operator Precedence tells order of performing
C Language 9 AM Page 52
• Operator Precedence tells order of performing
operations when evaluating the expressions.
• It is just like BODMAS rule for C-Language.
Example:
x=1 y=2 z=3
*/ %
x+y*z => EXPRESSION + -
x+y*z = ? => 7
a + b * c - d/e
Associativity:
When multiple operators are having same level
priority then associativity will be used to
evaluate the expressions
C Language 9 AM Page 53
a+b*c-d/e => expression
a + b * c - d/e
a - b / c + d*e
* / % Left to Right
= Right to Left
x = y = z = 100
C Language 9 AM Page 54
Control Structures / Control Statements / Flow
COntrol
Friday, February 4, 2022 10:30 AM
Control Statements:
Sequential Statements:
based on the condition statements
get executed sequentially
get executed
main() main()
{ {
printf("hello\n"); int x=5;
printf("hi\n"); if(x>5)
printf("hello\n");
printf("welcome\n"); if(x<5)
} printf("hi\n");
if(x==5)
Output: printf("welcome\n");
hello }
hi
welcome Output:
welcome
Control Structures:
• are used to control the flow of execution of statements.
• are used to change the sequential execution.
• Normally, C-Program gets executed sequentially. To transfer
the control to our desired location, we use control structures.
Advantages:
• we can change the sequential execution
• provide control on program to the programmer.
• Code optimization [less code].
Conditional if
if else
if else if
nested if
Multi-way Conditional switch
Iterative / Looping while
do while
for
Jumping goto
break
continue
return
• if
if else
C Language 9 AM Page 55
• if else
• if else if
• nested if
if:
Syntax:
if(<condition>) if()
{ {
//Statements //statements
} }
if block
Ex:
read age
if(age>=18)
printf("eligible");
if else:
Ex:
read age
if(age>=18)
printf("eligible");
if(age>=18)
printf("eligible");
else
C Language 9 AM Page 56
if(age>=18)
printf("eligible");
if(age>=18)
printf("eligible");
else
printf("not eligible");
if else if:
Syntax:
if(<Condition-1>)
{
//Statements
}
else if(<Condition-2>)
{
//Statements
}
else if(<Condition-3>)
{
//Statements
}
.
.
else
{
//Statements
}
C Language 9 AM Page 57
given number is +ve or -ve or zero:
if else:
even, odd
pass, fail
if else if:
+ve, -ve, zero
Math Functions:
sqrt()
pow()
sin() math.h
cos()
tan()
abs()
sqrt():
is used to find square root value
Syntax:
double sqrt(double)
Syntax:
pow(number,power)
sin():
C Language 9 AM Page 58
sin():
used to find sine values sin(angle)
cos():
used to cosine values cos(Angle)
tan():
used to find tangent values tan(angle)
abs():
used to get absolute value [non-negative].
abs(5)
abs(-5)
C Language 9 AM Page 59
Program to find result of the student for 3 subjects:
Max Marks: 100
Min Marks: 40 for pass in each subject
calculate average marks
if avrg is greater than or equals to 60 then FIRST
if avrg is b/w 50 to 59 then SECOND
if avrg is b/w 40 to 49 then THIRD
C Language 9 AM Page 60
Program to find biggest in 3 different numbers:
x y z
70 50 60
nested if:
Writing "if" in another "if" is called "nested if".
Syntax:
if(<condition-1>)
{
if(<condition-2>)
{
//Statements
}
}
if(inter == "PASS")
{
if(course=="EEE")
display EEE syllabus
else if(course=='CSE')
display the CSE syllabus
}
x y z
80 50 60
if(x>y)
{
if(x>z)
printf("%d is big",x);
}
if(y>x)
{
if(y>z)
printf("%d is big",y);
}
if(z>x)
{
if(z>y)
printf("%d is big",z);
C Language 9 AM Page 62
printf("%d is big",z);
}
Sorting
Ascending insertion sort
bubble sort
6 2 merge sort
8 3 quick sort
4 4 heap sort
3 6 radix sort
2 8 selection sort
swapping 2 numbers:
if(x>y)
{
if(x>z)
printf("%d is big",x);
else
printf("%d is big",z);
}
else
{
if(y>z)
printf("%d is big",y);
else
printf("%d is big",z);
}
biggest in two:
if(x>y)
x = x>y ? x : y;
else
y
C Language 9 AM Page 63
x y z
big
50 90 70
50
big = x;
if(y>big)
big=y;
if(z>big)
big=z;
switch:
Syntax:
switch(<expression>)
if(c1)
{
{
case <constant-1>:
//statements
//Statements
}
break;
else if(c2)
case <constant-2>:
{
//Statements
//statements
break;
}
.
.
.
.
.
else
default:
{
//Statements
//Statements
}
}
C Language 9 AM Page 64
7 = Saturday
switch(n)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
/printf("Tuesday");
break;
//case 4 to case 7
Assignment:
Program to display month name of 1-Jan
given month number: 2-Feb
.
Enter month number: 3 .
March 12-Dec
other than 1 to 12
Invalid
Rules in switch:
• in every case last statement must be "break".
Otherwise it gives wrong results to us.
If break is not there, it executes next case
statements irrespective of value matching.
C Language 9 AM Page 65
statements irrespective of value matching.
That's why to come out of switch we must
write "break".
• Constant must be integer only. But, character
constant can be accepted. Because, for every
character implicitly ASCII value will be taken.
This ASCII value is integer.
• Constant must be unique.
• Writing default is optional.
• For last case we have no need to write
"break". Because, even if break is there or not
it comes out of the switch.
a
e
i
o
u => vowel
switch(alpha)
{
case 'a':
printf("Vowel");
break;
case 'e':
printf("Vowel");
break;
case 'i':
printf("Vowel");
break;
case 'o':
printf("Vowel");
break;
case 'u':
printf("Vowel");
break;
default:
printf("Consonant");
}
tolower():
• used to convert a character to
lower case.
tolower('Q')
C Language 9 AM Page 66
tolower('Q')
switch(expression) if(c1)
{ {
case c1: //stmts
//stmts }
break; else if(c2)
case c2: {
//stmts //stmts
break; }
. .
. .
default: else
//stmts {
//stmts
} }
Ex: 1.deposit
switch(trans_type) 2.withdraw
{ 3.check balance
case 1: 4.mini statement
//deposit operation
break; Enter ur choice:3
case 2:
//withdraw operation
break;
C Language 9 AM Page 67
break;
.
.
default:
printf("invalid choice");
}
1. Red
2. Blue
3. White
4. Black
Select ur favourite color [1 to 4]: 1
ur fav color is: red
Assignment:
Find area of specific shape based on user's choice:
1. Circle 1. Circle
2. Triangle 2. Triangle
3. Rectangle 3. Rectangle
Enter ur choice: 1 Enter ur choice: 2
Enter radius: 5.6 Enter base and height:
area=….. area=…..
C Language 9 AM Page 68
1. Circle 1. Circle
2. Triangle 2. Triangle
3. Rectangle 3. Rectangle
Enter ur choice: 3 Enter ur choice: 9
Enter length and breadth: 7.8 5.6 Invalid choice
area=…..
switch(ch)
{
case 1:
read radius
print area
case 2:
read base, height
print area
case 3:
read length, breadth
print area
default:
print invalid
}
100 hellos
printf("hello\n");
hello
printf("hello\n");
hello Loop(100 times)
printf("hello\n");
hello {
.
. printf("hello\n");
.
. }
printf("hello\n");
hello
C Language 9 AM Page 69
while loop:
Syntax:
Initialization if(<condition>)
while(<condition>) {
{ //statements
//statements }
//step
}
1 i=1; //initialization
2 while(i<=100) //condition
3 {
. print i;
. i++; //step
100 }
i=1;
i
1 printf("%d\n",i); //1
2 i++; //i=2
3
4 printf("%d\n",i); //2
i++; //i=3
printf("%d\n",i);
i++; //i=4
printf("%d\n",i);
C Language 9 AM Page 70
Program to print numbers from 4 to 1:
i i=4;
4
3 while(i>=1)
2 {
1 printf("%d\n",i); //4 3 2 1
i--; //i=3 2 1 0
}
Assignment:
1
2 3
4 5
6 7
8 9
. .
. .
20 19
10
20
30
40
.
.
100
Enter n: 5 5*1=5
5*1=5
5*2=10
5*3=15 printf("
.
.
5*10=50
Enter n: 5
5*1=5
5*2=10
5*3=15
.
C Language 9 AM Page 71
5*1=5
5*2=10
5*3=15
.
.
5*10=50
Logic:
• Take the number & divide with 10. With this, we
get remainder & quotient.
• Take quotient as number. Again divide with 10.
• Repeat second step till we get number as 0.
• When number is 0. STOP division.
• Now, Count how many times we divided with 10
• This count value is no of digits value.
n=123
count=0
10)123(12
120
---------------
3 => count++ => 1
n=12
10)12(1
10
---------------
2 => count++ => 2
n=1
10)1(0
0
--------------
1 => count++ => 3
n=0 => STOP => PRINT count
Logic:
• sum=0
• Take the number & divide with 10. We get
remainder as last digit.
• Add last digit to sum & store result in sum.
Take quotient as number & Again divide with
C Language 9 AM Page 72
Add last digit to sum & store result in sum.
• Take quotient as number & Again divide with
10. We get another digit. Add this digit to sum
& store result in sum. Repeat this step, till we
get number as 0.
• Finally print sum.
sum=0
10)786(78
780
----------------
6
sum=sum+6 => 0+6 = 6
10)78(7
70
-------------
8
sum = sum+8 => 6+8 = 14
10)7(0
0
-----------------
7
sum=sum+7 => 14+7 = 21
n=0 STOP => PRINT SUM
Armstrong Number
Sum of cubes digits = Number
C Language 9 AM Page 73
Program to find reverse number:
Logic:
• r=0
• Multiply reverse number(r ) with 10. then add
last digit. Store the result in r.
• Again multiply current r with 10 add another
digit.
• Repeat above step till we get reverse number
r=0;
while(n!=0)
{
d=n%10;
r=r*10+d;
n=n/10;
}
print r
Palindrome:
Number = Reverse Number
do while Loop:
Syntax:
C Language 9 AM Page 74
do while(<condition>)
{ {
//Statements //Statements
}while(<condition>); }
i
i=1;
1
2 do
3 {
4 printf("%d\n",i);
i++;
}while(i<=4);
C Language 9 AM Page 75
while do while
Syntax: Syntax:
while(<condition>) do
{ {
//Statements //Statements
} }while(<condition>);
main() main()
{ {
int x=5; int x=5;
while(x>5) do
{ {
printf("hello"); printf("hello");
} }while(x>5);
} }
ATM software:
do
{
display menu while(3 times)
Withdraw {
display menu
do u want another transaction? Withdraw
}while(ch=='y'); }
C Language 9 AM Page 76
for Loop:
Syntax:
i
1 for(i=1;i<=4;i++)
2 printf("%d\n",i);
3
4
for(i=4;i>=1;i--) 4
printf("%d\n",i); 3
2
1
i
2 for(i=2;i<=20;i=i+2)
4 printf("%d\n",i);
6
8
.
.
20
i
1
for(i=1;i<=20;i=i+2)
3
C Language 9 AM Page 77
i
1
for(i=1;i<=20;i=i+2)
3
printf("%d\n",i);
5
7
.
.
19
i
1 is odd
for(i=1;i<=100;i++)
2 is even
{
3 is odd
if(i%2==0)
4 is even
printf("%d is even\n",i);
.
else
.
printf("%d is odd\n",i);
100 is even
}
i
10
for(i=10;i<=100;i=i+10)
20
printf("%d\n",i);
30
40
.
.
100
1
5
9
13
.
.
99
100
200 for(i=100;i<=1000;i=i+100)
300 printf("%d\n",i);
.
.
1000
C Language 9 AM Page 78
1000
4 * 1 =4
Enter n: 4
4*1=4
4*2=8
.
. for(i=1;i<=10;i++)
4*10=40 printf("%d * %d = %d\n",n,i,n*i);
4! =
1*5*9*13
4! => 4*3*2*1
C Language 9 AM Page 79
4! => 4*3*2*1
Factor:
6
If a number is divisible by another
number then another number is
1,2,3,6
called "Factor".
1,2,3,4,5,6
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0) => TRUE means i is factor of n
{
printf("%d\n",i);
count++;
}
}
print count => count is number of factors
n=4
i=> 1,2,3,4
count=0;
C Language 9 AM Page 80
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
printf("%d\n",i);
count++;
}
}
print count
Prime Number:
If a number is divisible by 1 & itself
Prime number:
number of factors =2
Ex:
2
3
5
7
11
13
17
19
Perfect number:
Sum of Factors except number = Number
C Language 9 AM Page 81
2 power 3 => k = pow(2,3) => print k
math.h
pow(---,….)
{
//power logic
}
1+2+3+4
C Language 9 AM Page 82
1+2+3+4
n=3
C Language 9 AM Page 83
Assignment:
0
x=-1
1
y=1
1
2
for(i=1;i<=n;i++)
3
{
5
f = x+y;
8
printf("%d\n",f);
13
x=y;
21
y=f;
34
}
.
.
goto:
• used to transfer the control to specified label.
• can be used in 2 ways:
Jumping Backward
C Language 9 AM Page 84
○ Jumping Backward
○ Jumping Forward
Syntax: Syntax:
//statements //statements
<label>: goto <label>;
//statements //statements
goto <label>; <label>:
//statements //statements
Note:
All programs which we can do using loops
can be also done by "goto"
i
1
i=1;
2
3
nareshit:
4 i <=4
printf("%d\n",i); //1
i++; //i=2
if(i<=4)
goto nareshit;
n=4 4!
1*2*3*4
C Language 9 AM Page 85
Program to restrict the user from entering -ve value:
abs():
abs(--)
{
absolute => non-negative
//logic
}
abs(5) => 5
abs(-5) => 5
main()
{
int n;
Unary Minus ( - ):
multiply with -
break:
• can be used in 2 places only:
○ inside of loop
○ inside of switch
• To come out of switch, in every case last
statement we are writing "break".
• To terminate the loop in the middle of
execution we use "break".
Syntax:
Loop switch
….
case <const>:
….
….
C Language 9 AM Page 86
Loop switch
….
case <const>:
….
….
break;
break;
…
….
…
main()
{
int i; 1
2
for(i=1;i<=10;i++) 3
{ .
printf("%d\n",i); .
} .
} 10
main()
{
int i;
for(i=1;i<=10;i++)
{
printf("%d\n",i); //1 2 3 4 5
if(i==5)
break;
}
}
Array
15 30 25 82 73 66
x[0] x[99]
enter ur HTNO: 25
C Language 9 AM Page 87
Program to check whether the given number is
prime or not:
Prime Number:
Number of Factors = 2
2 => 1,2
3 => 1,3 4 => 1,2,4 1,that number
5 6 => 1,2,3,6
7
11
13
n=6 found=0;
for(i=2;i<n;i++)
i => 2,3,4,5 {
if(n%i==0) //TRUE => 3rd factor
{
found=1;
break;
}
}
continue:
• can be used in one place only. i.e. inside of loop.
• It is used to skip current iteration & continue the
next iteration.
Syntax:
…..
……
continue;
…….
…..
for(i=1;i<=10;i++)
{
if(i==5 || i==7)
continue;
printf("%d\n",i); //1 2 3 4 5 6
}
C Language 9 AM Page 88
return:
• It is used to come out of the function
• It can carry a value out of function
Ex:
int f1()
{
int x=20,y=30;
Nested Loops:
Writing Loop in another Loop is called "Nested Loop".
C Language 9 AM Page 89
{ { {
} } }while(..);
} } }
do do do
{ { {
while(…) for(…) do
{ { {
} } }while(…)
}while(..); }while(..); }while(..);
for()
{
for()
{
for()
{
}
}
}
Nested Loops:
Prime number 2
Number of Factors = 2 3
C Language 9 AM Page 90
Program to print prime numbers b/w 1 to 20:
Prime number 2
Number of Factors = 2 3
5
7
11
n=6 count=0 13
17
i = 1,2,3,4,5,6 19
n=1, 2, 3, 4, 5 …20
for(n=1;n<=20;n++)
2
{
3
count=0;
5
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
printf("%d\n",n);
}
#include<stdio.h>
main()
{
int n,count,i,s,e;
for(n=s;n<=e;n++)
{
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
printf("%d\n",n);
}
}
C Language 9 AM Page 91
}
Perfect Num
Sum of factors except num = number
n=6
i = 1,2,3,4,5 <6
1+2+3 = 6
for(n=1;n<=1000;n++)
{
sum=0;
for(i=1;i<n;i++)
{
if(n%i==0)
sum=sum+i;
}
if(sum==n)
printf("%d\n",n);
}
6*6*6 = 216
Pattern Programs:
C Language 9 AM Page 92
* * * * *
for(i=1;i<=5;i++)
* * * * *
{
* * * * *
for(j=1;j<=5;j++)
* * * * *
printf(" * ");
* * * * *
printf("\n");
}
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
printf(" * ");
printf("\n");
}
for(j=1;j<=1;j++)
printf(" * ");
for(j=1;j<=2;j++)
printf(" * ");
for(j=1;j<=3;j++)
printf(" * ");
C Language 9 AM Page 93
for(j=1;j<=3;j++)
printf(" * ");
for(j=1;j<=4;j++)
printf(" * "); for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++) for(j=1;j<=i;j++)
printf(" * "); printf(" * ");
printf("\n");
}
for(n rows)
{
for(n columns)
{
* ?
space ?
}
}
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i+j=6)
printf(" * ");
}
printf("\n");
}
C Language 9 AM Page 94
1 1 1 1 1 1 2 3 4 5
2 2 2 2 2 1 2 3 4 5
3 3 3 3 3 1 2 3 4 5
4 4 4 4 4 1 2 3 4 5
5 5 5 5 5 1 2 3 4 5
1 1
1 2 2 2
1 23 3 33
1 234 4 444
1 2345 5 5555
C Language 9 AM Page 95
Program to print the following pattern:
if(i==3 || j==3)
print *
else
print space
for(n rows)
{
for(n columns)
{
if(i==p || j==p || (i==1 && j<=p) || (i==n && j>=p)
(j==1 && i>=p) || (j==n && i<=p))
print *
else
print space
}
}
C Language 9 AM Page 96
Functions
Monday, February 28, 2022 9:57 AM
Function:
• Function => Task / Action / Work
• Function is a set of statements that gets
executed on calling.
• Every function is defined to perform particular
task / action.
• Function is a sub-program.
Advantages:
• Function provides Reusability.
• Function reduces length of code.
• Function improves understandability.
• Function provides better maintenance.
Bank Project
withdraw()
{
…………..
}
…………
deposit()
……………
{
…………….
}
…………..
checkbalance()
………….
{
}
bank project
f1()
{
}
2 more functionalities
f2()
{
}
C Language 9 AM Page 97
Types of Functions:
2 Types:
• Built-In Functions
• User-Defined Functions
• Built-In Functions:
• Predefined / Library / System-defined Functions
• These functions already developed by c-language
developers & they placed them in corresponding
header files.
User-Defined Functions:
We can define our own functions. These functions
are called user-defined functions.
Ex:
nareshit() f1() ramu() fact() add()
withdraw() deposit()
C Language 9 AM Page 98
Syntax to define the function:
<return_type> <function_name>([<argument_list>])
{
//STATEMENTS
}
[ ] => optional
< > => any
• Function Definition
• Function Declaration
• Call Of Function
Function Definition:
• Defining a Function is called "Function Definition".
• It contains 2 parts:
○ Function Header
○ Function Body
Ex:
void nareshit() Function Header
{
printf("hi\n");
printf("bye\n"); Function Body
}
FUNCTION
C Language 9 AM Page 99
Function Declaration:
• Declaring a function is called "Function
Declaration"
• Like variable declaration, function must be
declared.
• Function Declaration ends with ;
• It tells information about the function to
compiler
Ex:
void nareshit();
void add(int, int);
Call Of Function:
• Calling a function is called "Call Of Function".
• Every function gets executed on calling.
• A Function call is required for Function execution.
Ex:
nareshit();
printf("hello");
scanf("%d",&x);
pow(2,3);
Argument [Parameter]:
• Argument is a local variable which is declared in
FUNCTION HEADER.
• It is used to bring value into function from out of
function.
• It acts like input for the function.
add(5,2);
}
pow(double x,double y)
Return:
• Return is a jumping control structure.
• can be used in 2 ways:
○ return;
○ return <constant/expression>;
○ return; =>
used to come out of the function in the middle of
function execution.
Ex:
void f1()
{
printf("hi\n");
return;
printf("bye\n");
}
main()
{
f1();
}
int f1()
{
return 5;
}
main()
{
int k;
k=f1();
printf("%d",k);
}
adding 2 numbers:
No Argument, No Return:
This kind of function cannot take any arguments &
cannot return any value.
printf("Enter x,y:");
scanf("%d%d",&x,&y);
printf("sum=%d\n",x+y);
C Language 9 AM Page 103
printf("sum=%d\n",x+y);
}
Argument, No Return:
This kind of function can take arguments. But it
cannot return the value.
void add(int,int);
No Argument, Return:
This kind of function cannot take arguments.
But returns the value.
int add();
int add()
{
int x,y;
printf("Enter x,y:");
scanf("%d%d",&x,&y);
return x+y;
}
Note:
• Function returns value to function call
A Function can return only one value. It cannot return
C Language 9 AM Page 104
• A Function can return only one value. It cannot return
multiple values
Argument, Return:
This kind of function can take arguments & return
the value.
int add(int,int);
int add(int x,int y)
{
return x+y;
}
5*1=5
void mtable(int);
void mtable(int n)
{
int i;
for(i=1;i<=10;i++)
printf("%d * %d = %d\n",n,i,n*i);
}
main()
{
mtable(5);
mtable(15);
}
int fact(int);
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
main()
{
int k;
k=fact(4);
printf("4!=%d\n",k);
printf("5!=%d\n",fact(5));
printf("7!=%d\n",fact(7));
}
printf("Enter x,y:");
scanf("%d%d",&x,&y);
void sub()
{ return (float)x/y;
int x,y; }
printf("Enter x,y:");
scanf("%d%d",&x,&y); void product(int x,int y)
{
printf("diff=%d\n",x-y); printf("product=%d\n",x*y);
} }
int square(int);
int cube(int);
double power8(int);
int square(int n)
{
return n*n;
}
int cube(int n)
{
return n*n*n;
}
double power8(int n)
C Language 9 AM Page 108
double power8(int n)
{
return pow(n,8);
}
main()
{
printf("2 power 2=%d\n",square(2));
printf("3 power 2=%d\n",square(3));
printf("5 power 2=%d\n",square(5));
Assignment:
isprime(int n)
{
int count=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
printf("%d is prime\n",n);
else
printf("%d is not a prime\n",n);
}
main()
{
isprime(5);
isprime(6);
}
math.h nareshit.h
sqrt() power()
sin() fact()
pow() square()
cube()
Tools =>
f1()
{
…..
…..
f1(); //Recursive Call => Recursion
}
main()
{
f1();
}
Recursion:
• If a function is called with in the same function
then it is called "Recursion".
• In this concept, calling function & called
function both are same.
• Recursion is used to execute the function code
repeatedly.
int fact(int n)
4! fact(4)
{
if(n==1)
4*3! 4*fact(3)
return 1;
3*2! 3*fact(2)
else
2*1! 2*fact(1)
return n*fact(n-1);
1 1
}
int fibo(int n)
n
{
0 fibo(0) => 0
if(n==0 || n==1)
1 fibo(1) => 1
return n;
1 fibo(2) => fibo(1)+fibo(0)
else
2 fibo(3) => fibo(2)+fibo(1)
return fibo(n-1)+fibo(n-2);
3 fibo(4) => fibo(3)+fibo(2)
}
5
8
13
main()
.
{
.
fibo(0);
fibo(1);
fibo(2);
fibo(3);
}
Types of Recursion:
According to number of recursive calls,
2 Types:
• Linear Recursion
• Binary Recursion
int power(int n,int p)
Linear Recursion: {
If a function has one recursive call then it called if(p==0)
"Linear Recursion". return 1;
else
Ex: Factorial, Power, Sum of Digits return n*power(n,p-1);
}
Binary Recursion:
C Language 9 AM Page 114
Binary Recursion:
If a function has two recursive calls then it is called
"Binary Recursion".
int fibo(int n)
{
if(n==0 || n==1)
return n;
else
return fibo(n-1)+fibo(n-2);
}
Storage Class:
• Storage class tells the behavior of variables in terms of
scope & lifetime. int x=50;
• Scope => Availability of Usage void f1()
• Lifetime => The span time a variable alive in memory {
auto [local]:
• A variable which is declared inside of function
• is called "Auto Variable".
• "auto" keyword is used to declare the "auto" variable.
• Even if we don't use "auto" keyword, by the place of
variable declaration, every variable in the function will
be treated as "auto variable" by default.
• Ex:
void f1()
{
int x; // x => auto variable
auto int y; // y => auto variable
}
• "Auto variable" can be also called as "Local Variable /
Internal Variable / Automatic Variable".
• Scope => Function
• Lifetime => Function
extern:
• A variable which is declared outside of all
functions is called "extern variable". EX:
• "extern" keyword is used to declare the int x; //extern variable
"extern variable". extern int a; //extern variable
• Even if don't use keyword, by the place of f1()
its declaration, that variable will be treated {
as "extern variable" by default. printf("%d\n",x);
• "extern variable" can be also called as }
"external variable" (or) "global variable". f2()
• Scope => Program {
• Lifetime => Program printf("%d",x);
}
• default value: 0 main()
{
f1();
f2();
printf("%d",x);
}
Local VS Global:
int x=100; int x=100;
void f1() void f1()
{ {
int x=100;
void f1()
{
int x=80;
printf("x=%d\n",x); //80 80 100 100
printf("x=%d\n",x); Note:
} If local variable is there, it gives
main() priority for local
{ If local variable is not there, it
f1(); takes global.
printf("x=%d\n",x);
printf("x=%d\n",x);
}
static:
• A variable which is declared
using "static" keyword is called static int e; //static global var
"static variable". f1()
• Static variable can be used in 2 {
ways: static int a; //static local var
○ static local variable }
○ static global variable
register:
RAM
• A variable which is declared using "register" main()
keyword is called "register variable". { a
• It is just like 'auto variable'. int a;
• It can be declared inside of function only. register int r;
• It cannot be declared outside of all functions. }
• Scope => Function
Micro Processor
• For register variable, memory will be allocated in
register
CPU[Micro Processor] registers.
r
• It is a request to the compiler. But not command.
• Compiler may ignore this request.
• We cannot guarantee that always register
variable will be stored in Microprocessor
registers. Sometimes it may be stored in RAM
also.
• Default value is: Garbage value
Array:
• is a set of elements of same data type.
• value => elements
10 10.56 'r'
'A'
80 23.32 'a'
567
-15 67.89 'j'
56.7
56 -45.67 'u'
21 12.34 Not an Array
Char
Integer
Float Array
Array
Array
Advantages:
1 student marks of 1 sub
• It decreases number of variables.
m=78
• It can group same type elements
& all elements name is same.
100 students => 100 students
• We can access array elements
marks of 1 sub
randomly
m1=56
• Ex: To access
m2=81
▪ 3rd element => x[2]
m3=54
▪ 25th element => x[24]
.
.
• Code optimization will be there.
m100=89
[Less Code]
Disadvantages:
• we must specify array size. e=100
• Array size is fixed. We cannot increase or p=2 60
decrease array size at run time.
50
• Memory wastage or shortage will be
80
there.
• Poor performance will be there in case of 70
insertion & deletion. 30
Types of Arrays:
2 Types:
• Single Dimensional
• Multi-Dimensional
Ex:
40
40 90 20
90
ROW
20
Column
Multi-Dimensional Array:
It can represent both rows & columns.
Ex:
50 70 40
35 42 61
x[0] = 50
for(i=0;i<5;i++)
x[1] = ..
printf("x[%d] = %d\n",i,x[i]);
.
.
x[4] = ..
Note:
• We must specify array size.
• At the time of initialization [in this one case
only] we have no need to specify size.
int x[10],y[10];
n=3 => n => number of elements x y
50
10 x[0] 10 y[0]
20 x[1] 20 y[1]
30 x[2] 30 y[2] y = x;
y[0] = x[0]
y[1] = x[1]
y[2] = x[2]
x[10], y[10] , n= 3
10 x[0] y[0]
20 x[1] y[1]
30 x[2] y[2]
for(i=0;i<n;i++)
{
z[i] = x[i];
z[n+i] = y[i];
}
10 z[0]
10 x[0] 11 y[0] 11 z[1]
20 x[1] 22 y[1] 20 z[2]
30 x[2] 33 y[2] 22 z[3]
30 z[4]
33 z[5]
Searching Techniques:
are used to search for particular element in the
Array.
Ex:
70 90 50 30 80
x[0] x[1] x[2] x[3] x[4]
2 Searching Techniques:
• Linear Search
• Binary Search
70 90 50 30 80
x[0] x[1] x[2] x[3] x[4]
e found=0;
90 if(e==x[0])
{
found=1;
break;
}
if(e==x[1])
{
found=1;
break;
}
if(e==x[2])
{
found=1;
break;
}
if(e==x[3])
{
found=1;
break;
}
if(e==x[4])
{
found=1;
break;
}
n=9
l=0, h=8 (n-1)
10 x[0] mid = (l+h)/2 => 8/2 = 4 found=0;
20 x[1] l=0;
30 x[2] case-1: h=n-1;
40 x[3] searching element==mid index element while(l<=h)
50 x[4] e=50 {
found=1; mid = (l+h)/2;
60 x[5]
break;
70 x[6]
if(e==x[mid])
80 x[7] case-2: {
90 x[8] searching element>mid index element found=1;
e=70 break;
l=mid+1; }
else if(e>x[mid])
case-3: l=mid+1;
searching element<mid index element else if(e<x[mid])
20 h=mid-1;
h=mid-1; }
Sorting Techniques:
are used to arrange the elements in
Ascending or Descending Order.
50 20 90
90 40 70
40 50 50
70 70 40
20 90 20
Ascending Descending
Bubble Sort:
• Compare First element with
30
second. If first element > second
20
then swap.
• Compare 2nd element with 3rd.
If 2nd > 3rd then swap. 20
Follow above step till we get 30
elements in Ascending Order.
• After one pass highest element
will come at bottom of the array.
3 3 7
8
9
5 3
x[0]>x[1]
IV-PASS 3 5
7
8
9
10 20 30
x[0] x[1] x[2]
0+10+20+30
for(i=0;i<n;i++)
sum=sum+x[i];
print sum
big=x[0];
20 x[0]
10 x[1] if(x[1]>big)
big=x[1];
30 x[2]
if(x[2]>big)
big=x[2];
max element=30
min element=10
MODIFY
INSERT
DELETE
x[10]
Read elements
10
n=5
20
x[2] = 100;
10 x[0]
p=2 20 x[1] x[2] => 3rd position element
e=100 x[4] => 5th position element
30 x[2]
40 x[3]
p=3 => index 2
50 x[4]
p=5 => index 4
10 x[0]
p=3
20 x[1] e=500
30 x[2]
40 x[3]
50 x[4]
#include<stdio.h>
main()
{
int x[10],n,i,p,e;
x[p-1]=e;
for(i=0;i<n;i++)
printf("%d\n",x[i]);
}
10 x[0]
20 x[1]
30 x[2]
40 x[3]
50 x[4]
x[5]
10
20
30
40
50
Types of Arrays:
2 types:
• Single Dimensional =>
10 20 30 10
20
30
• Multi-Dimensional:
can represent both rows & columns.
Sub types:
○ 2D-Array => collection of 1D-Arrays
10 20 30
○ 3D-Array => collection of 2D-Arrays
40 50 60
○ 4D-Array => collection of 3D-Arrays
○.
○. 2 rows
○ nD-Array => collection of n-1D-Arrays 3 columns
10 20 30
x[0] x[1] x[2]
1000 1004 1008
10 20 30
40 50 60
Declaring 2D-Array:
Syntax:
data_type array[row_size][<col_size];
Ex:
5000 5004 5008 5012 5016 5020
int x[2][3]; //6 elements => 24 Bytes
row-0
row-1
Initializing 2D-Array:
i<2 for(i=0;i<2;i++)
2 => no of rows { for(j=0;j<3;j++)
for(j=0;j<3;j++) printf("%d\t",x[0][j]);
j<3 printf("%d\t",x[i][j]); printf("\n");
3 => no of cols printf("\n");
} for(j=0;j<3;j++)
printf("%d\t",x[1][j]);
printf("\n");
Reading 2D-Array:
printf("x-array elements:");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&x[i][j]);
Square Matrix:
no of rows = no of cols
Ex:
2X2 3X3 4X4
Rectangle Matrix:
no of rows != no of cols
Ex:
2X3 4X2 6X5
10 20 10 20 y[0][0] = x[0][0]
for(j=0;j<2;j++)
X= 30 40 Y= 30 y[0][1] = x[0][1]
y[0][j] = x[0][j]; for(i=0;i<m;i++)
{
2X2
for(j=0;j<n;j++)
y[1][0] = x[1][0]
for(j=0;j<2;j++) y[i][j] = x[i][j];
y[1][1] = x[1][1]
y[1][j] = x[1][j]; }
20 20 y=x;
Transpose Matrix:
Interchanging rows & columns
10 20 30 10 40
x= y=
40 50 60 20 50
30 60
y[0][0] = x[0][0]
for(j=0;j<3;j++)
y[1][0] = x[0][1]
y[j][0] = x[0][j];
y[2][0] = x[0][2]
for(i=0;i<2;i++)
y[0][1] = x[1][0] for(j=j=0;j<3;j++)
for(j=0;j<3;j++)
y[1][1] = x[1][1] y[j][i] = x[i][j];
y[j][1] = x[1][j];
y[2][1] = x[1][2]
10 20
10 + 20 + 30 + 40
30 40
for(i=0;i<n;i++)
10 20 30
for(j=0;j<n;j++)
40 50 60
if(i==j)
70 80 90 sum=sum+x[i][j];
10+50+90 = 150
10 20 30
40 50 60
70 80 90
10+20+30+40+50+70 = 220
Rule:
first matrix size = second matrix size
10 20 1 2
y=
X= 30 40 3 4
z[1][0] = x[1][0]+y[1][0]
z[1][1] = x[1][1]+y[1][1]
Matrix Multiplication:
Rule:
No of Columns in 1st Matrix = No of Rows in 2nd Matrix
1 2 3 7 8
X= 4 5 6 Y= 9 10
2X3 11 12
3X2
for(2 rows)
{
1*7 + 2*9 + 3*11 1*8 + 2*10 +3*12 for(2 columns)
Z
4*7 + 5*9 + 6*11 4*8 + 5*10 + 6*12 Addition
}
Types of Arrays:
• Single Dimensional => either a row or a column
10 20 30
40 50 60
11 22 33
44 55 66
3D-Array
Declaring 3D-Array:
Syntax:
data_type array[size1][size2][size3];
Ex:
int x[2][2][3]; //12 elements => 48 Bytes
2 2D-Arrays each can have 2 rows 3 columns
Initializing 3D-Array:
Printing 3D-Array:
for(i=0;i<2;i++)
for(i=0;i<2;i++)
10 20 30 {
x[0] 40 50 60 for(j=0;j<2;j++)
{
for(k=0;k<3;k++)
11 22 33 printf("%d\t",x[i][j][k]);
x[1] 44 55 66 printf("\n");
}
printf("=====================\n");
printf("\n");
}
Reading 3D-Array:
4D-Array:
collection of 3D-Arrays
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24
24*4 = 96
void PrintArray(int[][3],int,int);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d\t",x[i][j]);
printf("\n");
Array:
• is a set of elements of same
type.
Advantages:
• group same type elements
• decreases number of variables
• random accessing is possible
Types of Arrays:
• 1D-Array => a row or a column
• Multi-D Array => both rows &
columns
○ 2D-Array => colln of 1D-Arrays
○ 3D-Array => colln of 2D-Arrays
int m=45;
45 67 80
88 55 71
.. .. ..
int x[6][100][3];
45 67 80
88 55 71
.. .. ..
45 67 80
88 55 71
.. .. ..
.
.
45 67 80
88 55 71
.. .. ..
String:
• is a collection of characters. char x[10];
• In C-Language, String constant
must be enclosed in double 'r' x[0]
quotes.
'a' x[1]
• Ex: "raju" "nareshit" "india"
'j' x[2]
• String is a single dimensional
array of character type. 'u' x[3]
• C-Compiler passes '\0' at end of '\0' x[4]
the string. To identify end of the
string C-Compiler passes it.
int x[10];
• '\0' is null character. Its ASCII
value is 0.
• String name holds first element's
address.
Declaring String:
char x[10]; // 10 Bytes
Initializing String:
char x[10] = "Ravi";
(or)
char x[10] = {'r','a','v','i'};
(or)
char x[] = "Ravi";
Assigning String:
Assigning integer
char x[10];
x = "Ravi"; //Invalid - ERROR
int x[10];
x=60; //invalid - ERROR
x is array. Array name holds
address. we cannot assign value.
x[0]=60; //valid
char x[10];
x[0] = 'r'; x[1]='a'; x[2]='v'
x[3]='i';
strcpy(x,"ravi"); //Assigning
String
Printing a string:
C Language 9 AM Page 145
Printing a string:
printf("%s",x);
(or) 'r' 'a' 'v' 'i' '\0'
printf(x); printf("hello"); x[0] x[1] x[2] x[3] x[4]
(or)
puts(x);
(or)
for(i=0;x[i]!=0;i++)
printf("%c",x[i]);
(or)
for(i=0;x[i]!='\0';i++)
printf("%c",x[i]);
Reading String:
int x;
char x[10];
scanf("%d",&x);
scanf("%s",x);
(or)
gets(x);
Note:
to read string don't use &.
String name itself is address.
main()
{
char x[20]="Ravi"; R a v I \0
x[0] 1 2 3 4
printf("%c\n",x[2]); //v
puts(x); //Ravi
printf("\n");
#include<stdio.h>
main()
{
char x[10];
printf("Enter ur name:");
scanf("%s",x);
printf("%s",x);
}
main()
{
char x[10];
gets(x);
puts(x);
}
String Functions:
string.h
strlen()
strcpy()
strrev()
strcat()
strcmp()
strlwr()
strupr()
C Language 9 AM Page 147
strcat()
strcmp()
strlwr()
strupr()
Syntax:
strlen(string)
Ex:
strlen("raju") => returns 4
strlen("sai") => returns 3
#include<string.h>
#include<stdio.h>
main()
{
char x[20];
int n;
printf("Enter a String:");
scanf("%s",x);
n = strlen(x);
printf("No of chars=%d",n);
}
char x[10]
count=0;
's' x[0]
'a' x[1] while(x[count]!='\0')
{
'i' x[2]
count++;
'\0' x[3]
}
C Language 9 AM Page 148
'a' x[1]
{
'i' x[2]
count++;
'\0' x[3]
}
print count
while(a[count]!='\0')
count++;
return count;
}
strcpy():
used to copy one string to another.
Syntax:
strcpy(string1,string2)
Ex:
char x[10];
#include<string.h>
#include<stdio.h>
main()
{
char x[10],y[10];
strcpy(y,x);
printf("x=%s \t y=%s",x,y);
}
y[3] = '\0';
strrev():
used to find reverse string.
Syntax:
strrev(string)
Ex:
char x[10] = "sai";
strrev(x);
print x => ias
for(i=0;x[i]!='\0';i++)
y[n-i-1] = x[i];
Syntax:
strcat(str1,str2)
char x[10]="raj",y[10]="kumar";
strcat(x,y);
print x => rajkumar
Read 2 strings
strcat
print first string
n=strlen(x) = 3
strcmp():
used to compare 2 strings. It is mainly used to check
whether both strings are equal or not.
Syntax:
strcmp(str1,str2)
Ex:
strcmp('sai','teja') => 2nd greater => returns -1
strcmp('teja','sai') => 1st greater => returns 1
strcmp('sai','sai') => equal => returns 0
x y
ramu ramu
Palindrome:
C Language 9 AM Page 152
Palindrome:
string = reverse string
strcpy(y,x);
strrev(y);
if(strcmp(x,y)==0)
printf("palindrome");
else
printf("not a palindrome");
strlwr():
used to convert the string to lower case
Syntax:
strlwr(string)
Ex:
char x[10] = "RAMU";
strlwr(x)
print x => ramu
strupr():
used to convert the string to upper case
Syntax:
strupr(string)
Ex:
char x[10] = "ramu";
strupr(x)
print x => RAMU
putchar():
printf():
• output related function.
• output related function
• included in "stdio.h" header file.
• used to print the data on console
• used to print a char on screen.
screen
• we can print any type of data
Syntax:
putchar(char);
C Language 9 AM Page 153
putchar(char);
Ex:
char x='A';
putchar(x); //A
getchar(): scanf():
• input related function • input related function
• used to read a char from • used to read the data from
screen. console screen
• included in "stdio.h" • We can read any type of data
Ex:
char ch;
ch=getchar();
#include<stdio.h>
main()
{
char x[10];
printf("Enter ur name:");
scanf("%[A-Z]",x); //accepts only A to Z chars
printf("%s",x);
}
#include<stdio.h>
main()
{
char x[10];
printf("Enter text:");
scanf("%[^A-Z]",x); //other than capital letters accepted
printf("%s",x);
}
2D Char Array:
2D Char Array => a set of 1D Char Arrays
char x[10][20];
printf("%s\n",x[0]); //raj
for(i=0;i<4;i++)
printf("%s\n",x[1]); //sai
printf("%s\n",x[i]);
printf("%s\n",x[2]); //kiran
printf("%s\n",x[3]); //naresh
printf("%c",x[0][2]); // j printf("%c",x[2][3]);
Assignment:
l=0
h=n-1
found=0;
while(l<=h)
{
mid = (l+h)/2
if(strcmp(e,x[mid])==0)
{
found=1;
break;
}
else if(strcmp(e,x[mid])>0)
l=mid+1;
else if(strcmp(e,x[mid])<0)
h=mid-1;
}
Types of Variables:
2 Types:
• Data Variable
• Pointer Variable
x p
main()
{
int x,*p;
x=25;
p=&x;
printf("%d\n",x); //25
printf("%d\n",&x); //5000
printf("%d\n",*&x); //25
}
int *p;
p=&x;
printf("%d",*p);
Advantages:
• Pointers are used for Faster Accessing.
• Pointer provide Call By Reference.
• Pointer provides Dynamic Memory
Allocation.
C Language 9 AM Page 158
Allocation.
Disadvantages:
• Security Problems may occur due to
pointer arithmetic.
• Programmers does not show interest to
write programs using pointers
1234 Ravi 500000
5000 5004 5014
Pointer Arithmetic:
int x,y;
• Using operators on pointers is called
"Pointer Arithmetic".
x+y
• We can use 4 operators on pointers.
x-y
They are:
x*y
○ ++
x/y
○+
x<<y
○ --
x&y
○-
main()
{
int x[] = {10,20,30,40,50}, *p; 10 x[0]
20 x[1]
p=&x[0]; 30 x[2]
40 x[3]
printf("%d\n",*p); //10 50 x[4]
p++;
5000
printf("%d\n",*p); //20
p=p+2; p
printf("%d\n",*p); //40
p++;
printf("%d\n",*p); //50
p=p-3; In case of values In case of addresses
next value will be taken next memory block address
printf("%d\n",*p); //20 x=100 will be taken
p--; x++ => x=101
x=5000 [int address]
printf("%d\n",*p); //10 x++ => x=5004
}
x=5000 [double address]
x++ => x=5008
5000
main()
{
int x[] = {10,20,30,40,50}, *p;
p = &x[0];
printf("%d\n",*p++); //10
for(i=0;i<5;i++)
printf("%d\n",*p++);
printf("%d\n",*p++); //20
printf("%d\n",*p++); //30
printf("%d\n",*p++); //40
printf("%d\n",*p++); //50
}
printf("%d",*p);
= printf("%d",*p++);
p++;
main()
{
int x[2][3] = { {10,20,30},{40,50,60} },*p;
p = &x[0][0];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d\t",*p++);
printf("\n");
}
}
main()
{
int x[2][3] = { {10,20,30},{40,50,60} },*p;
int i,j;
p = &x[0][0];
Output:
first element address=6487552
first row address=6487552
2nd row address=6487564
first row first ele address=6487552
first row 2nd ele address=6487556
first row first ele=10
first row 2nd ele=20
x[i] = *(x+i)
x[i][j] = *(*(x+i)+j)
x[i] *(x+i)
x[i][j] *(*(x+i)+j)
x[i][j][k] *(*(*(x+i)+j)+k)
*(x+i)
*(*(x+i)+j)
*(*(*(x+i)+j)+k)
*(*(*(*(x+i)+j)+k)+l)
*(*(*(*(*(x+i)+j)+k)+l)+m)
Call By Value:
• Calling the function by passing the value.
• In this, values are passed as arguments.
• If we make any changes in called function
variables, it will not be affected in calling function
variables. Because, called function works with
copy.
void swap(int,int);
void swap(int x,int y) x y
{
int temp; 20 30
temp=x;
x=y;
y=temp;
}
main() temp
{
int a=20,b=30;
x => a's copy
swap(a,b); //call by value
y => b's copy
printf("a=%d\tb=%d",a,b);
copies of a,b are swapped.
}
means, x,y swapped
Note:
A function return one value only.
void swap(int*,int*);
void swap(int *x,int *y)
{
int temp;
temp=*x;
Pointer to Pointer:
• Pointer to pointer is a variable that is used to
hold address of pointer variable.
main()
{
int x=25,*p1,**p2,***p3;
p1=&x;
p2=&p1;
p3=&p2;
printf("%d\n",x); //25
printf("%d\n",*p1); //25
printf("%d\n",**p2); //25
printf("%d\n",***p3); //25
}
○ free()
(int*)5000 (int)5.6
RAM
main()
{
int x,*p; //static mem alloc
p = (int*)malloc(50);
free(p);
}
main()
{
int x;
x=(int)7.8; //x=7
}
realloc() [REALLOCate]:
• is included in "stdlib.h" & "alloc.h".
• used to expand the memory which is
allocated using malloc() or calloc().
• It returns void type address.
p = (int*)malloc(100);
p = (int*)realloc(p,200);
calloc(no_of_Elements, size);
malloc(100)
calloc(5,100)
calloc(3,50)
Note:
Programmer is responsible to destroy the memory
if memory allocated dynamically. Automatic
memory management is not available in C/C++.
int x,y[10],*a,*b[10]
x data variable
y array data array [set of values]
a pointer variable
b pointer array [ a set of addresses]
Structure:
• Structure is a user-defined data type. 10 20 30
• Structure is a collection of elements of
different types. 10.5 35.6 23.9
• It can hold homogeneous [same type]&
heterogeneous [different] elements. 'r' 'a' 'j'
• "struct" keyword is used to define the
structure.
'A' 678 67.8
Defining Structure:
Syntax:
struct struct_name
{
data_type1 var1,v2,……;
data_type2 var1,v2,……;
};
struct student
{
int sid;
char sname[10];
float avrg;
};
Note:
When we define the members in structure, memory
will not be allocated.
When we declare variable for structure, memory will
be allocated.
struct student
{
int sid;
sid sname
struct student s1={101,'Sai',56.78};
printf("%d\n",s1.sid)//101
printf("%s\n",s1.sname); //Sai avrg
printf("%f",s1.avrg); //56.78
scanf("%d",&s1.sid);
scanf("%s",s1.sname);
scanf("%f",&s1.avrg);
s1
struct student
{ 1234 sai 56.78
int sid; sid sname avrg
char sname[10];
C Language 9 AM Page 169
struct student
{ 1234 sai 56.78
int sid; sid sname avrg
char sname[10];
float avrg;
};
main()
{
struct student s1={1234,"sai",56.78};
printf("%d\t%s\t%f",s1.sid,s1.sname,s1.avrg);
}
#include<stdio.h>
struct student
{
int sid;
char sname[10];
float avrg;
};
main()
{
struct student s1;
printf("Enter name,sid,avrg:");
scanf("%s%d%f",s1.sname,&s1.sid,&s1.avrg);
printf("%d\t%s\t%.2f\n",s1.sid,s1.sname,s1.avrg);
}
Syntax:
#include<stdio.h>
main()
{
ramu x=20;
krishna y=30;
printf("sum=%d",x+y);
}
Define date data type. create 2 date values & print them.
struct date
d
m
y
struct date
{
25/12/2000
int d,m,y;
};
main()
{
struct date d1={25,12,2000};
printf("%d/ %d / %d\n",d1.d,d1.m,d1.y);
}
Structure as Argument:
return s1;
//for ex, if s1 has id, name & avrg, all 3 values will be returned
getchar() putchar()
getstd() putstd()
Array of Structure:
• Array of Structure means STRUCTURE ARRAY.
int x; std s;
int x[10]; std s[10]; //Array of Structure
printf("Enter no of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter id,name:");
scanf("%d%s",
&s[i].id,s[i].name);
}
for(i=0;i<n;i++)
printf("%d\t%s
\n",s[i].id,s[i].name);
}
Structure of Arrays:
Declaring Array as a member in structure is
called "Structure Of Array".
sid
sname
m[10]
printf("Enter no of subs:");
scanf("%d",&ns);
for(j=0;j<n;j++)
{
printf("Enter sid,sname and %d
subs marks:",ns);
scanf("%d%s",
&s[j].sid,s[j].sname);
for(i=0;i<ns;i++)
scanf("%d",&s[j].m[i]);
}
for(j=0;j<n;j++)
{
printf("%d\t%s Add total, avrg & result
\t",s[j].sid,s[j].sname); members to structure.
for(i=0;i<ns;i++) Claculate total, avrg
printf("%d\t",s[j].m[i]); & result of every student.
printf("\n");
}
}
struct student
{
int m[10]; //Structure of Array
};
Structure in Structure:
struct person
id
name
struct student
struct employee
person p
person p
sec
job
marks
sal
printf("%d\t%s\t%c\t%d
\n",s1.p.id,s1.p.name,s1.sec,s1.m
arks);
printf("%d\t%s\t%s\t%
lf",e1.p.id,e1.p.name,e1.job,e1.sa
l);
}
Pointer to Structure:
Declaring pointer variable of structure is called
"Pointer to Structure".
int x=50,*p;
p=&x;
p = &s1;
printf("%d\t%.2f\n",s1.sid,s1.avrg);
printf("%d\t%d\n",&s1.sid,&s1.avrg);
printf("%d\t%.2f\n",*&s1.sid,*&s1.avrg);
student.txt
File:
101 Ramu 456
• is a collection of related data.
102 Sai 786
ORACLE Tables
Files Concept: SQL SERVER
MY SQL emp
Goal: Storing data permanently in file empno ename job sal
1234 Sai clerk 6000
• C-Language supports to File Management System
[FMS].
• File Management System is a way of maintaining first name: ..
of the files. last name: ..
• FMS allows us to perform file operations like: mobile: ..
○ Writing data into file country: ..
○ Reading data from file .
○ Copying one file data to another .
○ Renaming the file SUBMIT
○ Removing the file
fopen()
fclose()
getc()
putc()
fprintf()
fscanf()
fread()
fwrite()
fseek()
ftell()
rewind()
rename()
remove()
fopen():
• This function is create new file or open
existing file in particular mode.
Syntax:
fopen(<file_name>,<file_mode>)
Mode Purpose
w write
r read
demo.txt
fopen("demo.txt","w"); computer is
=> a new file will be created an e……
with the name "demo.txt" in the ………………
current directory. It will be
opened in write mode.
fopen("d:\nareshit\xyz.txt","w");
demo.txt
fopen("demo.txt","w")
FILE: 5000
• FILE is a data type defined in
"stdio.h" .
• It is used work with files.
FILE *fp;
demo.txt
fp = fopen("demo.txt","w");
5000
Syntax:
fclose(file_pointer)
Ex:
fclose(fp)
demo.txt
xyz.txt
S
FILE *fp;
char ch='S';
fp=fopen("xyz.txt","w");
putc(ch,fp);
fclose(fp);
creates new file & opens in write mode creates new file & opens in append mode
opens existing file without data opens existing file with contents
safe
EOF:
• End Of File
• It is a macro defined by c-language developer.
• This macro included in "stdio.h" header file.
• EOF = -1
• Press F6 or Ctrl+Z = EOF
fp=fopen("xyz.txt","r"); hello …
…
getc(): getchar():
function is used read a char from reads char from
file console screen
Syntax: getchar()
getc(file_pointer)
getc(fp)
xyz.txt
FILE *fp1,fp2; hello every ..
…
fp1=fopen("xyz.txt","r"); …
C Language 9 AM Page 181
xyz.txt
FILE *fp1,fp2; hello every ..
…
fp1=fopen("xyz.txt","r"); …
fp2=fopen("abc.txt","w");
ch=getc(fp1);
putc(ch,fp2); abc.txt
student.txt
int sid;
cha sname[10];
20 Ravi
FILE fp;
30 Sai
40 Kiran
fp=fopen("student.txt","w");
printf("Enter sid,sname:");
scanf("%d%s",&sid,sname);
fprintf(fp,"%d\t%s\n",sid,sname);
fclose(fp);
#include<stdio.h>
main()
{
int sid,n,i;
char sname[10];
FILE *fp;
fp=fopen("student.txt","w");
printf("Enter no of students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter sid,sname:");
scanf("%d%s",&sid,sname);
fprintf(fp,"%d\t%s
\n",sid,sname);
printf("record saved in file..!
\n");
}
fclose(fp);
}
#include<stdio.h>
main()
{
int sid,i;
char sname[10],ch;
FILE *fp;
fp=fopen("student.txt","w");
do
{
printf("Enter sid,sname:");
scanf("%d%s",&sid,sname);
fprintf(fp,"%d\t%s
\n",sid,sname);
printf("record saved in file..!
\n");
}while(ch=='y' || ch=='Y');
fclose(fp);
}
fscanf(fp,"%d%s",&sid,sname);
#include<stdio.h>
main()
{
int sid;
char sname[20];
FILE *fp;
fp=fopen("student.txt","r");
while((fscanf(fp,"%d%s",
C Language 9 AM Page 183
while((fscanf(fp,"%d%s",
&sid,sname)!=EOF)
{
printf("%d\t%s\n",sid,sname);
}
fclose(fp);
}
2 types of files:
• Text File => contains text
Ex: .txt files
• fwrite()
• fread()
fwrite():
used to write the data into file.
Syntax:
fwrite(&structure,size_of_structure,no_of_Records,file_pointer)
student s1;
5000
4 to
fwrite(&s1,sizeof(s1),1,fp);
20 5023
-------
24
fread():
used to read the data from file.
Syntax:
fread(&structure,size_of_structure,no_of_Records,file_pointer)
Ex:
fread(&s,sizeof(s),1,fp);
wb write binary
rb read binary
r+b read write binary
student.bin
fp=fopen("stddemo.bin","wb");
printf("Enter sid,avrg:");
scanf("%d%f",&s1.sid,&s1.avrg);
fwrite(&s1,sizeof(s1),1,fp);
fclose(fp);
#include<stdio.h>
typedef struct student
{
int sid;
float avrg;
}std;
main()
{
FILE *fp;
std s1,s;
char ch;
fp=fopen("stddemo.bin","a+b");
do
{
printf("Enter sid,avrg:");
scanf("%d%f",&s1.sid,
&s1.avrg);
fwrite(&s1,sizeof(s1),1,fp);
fflush(stdin);
rewind(fp);
printf("\n\nsid\taverage\n");
printf("======================
===========\n");
while(fread(&s,sizeof(s),1,fp))
{
printf("%d\t%.2f
\n",s.sid,s.avrg);
}
fclose(fp);
Random Accessing:
fseek()
ftell()
demo.txt
computer
getc(fp)
Random Accessing:
fseek()
ftell()
fseek():
used to go to specified number of bytes from
specified position.
Syntax:
fseek(file_pointer,no_of_Bytes,from_where)
demo.txt
demo.txt
fseek(fp,2,0); computer
c o m p u t e r
ftell():
used to know position of file
pointer
renaming file:
rename():
used to rename the file
Syntax:
rename(old_file_name, new_file_name)
Syntax:
remove(filename)
Ex:
remove("aaa.txt")
Turbo C++:
• supports to Graphics
• provides graphics.h, conio.h
console applications
initgraph(): enter x: 10
• enter y: 20
sum=30
GUI Applns
enter x 5
enter y
4
sum
sum=9
initgraph():
used to switch from text mode to graphics mode.
int gd,gm;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
line():
used to draw the line.
line(x1,y1,x2,y2)
circle():
function is used to draw the circle
circle(x,y,radius)
setfillstyle(pattern_style,color)
rectangle():
used to draw the rectangle
ellise(x,y,starting_Angle,ending_angle,x-radius,y-radius)
ellipse(200,200,0,360,100,50)
outtext(x,y,string);
stetextstyle(font_Style,direction,font_size);
settextstyle(4,0,10);
outtextxy(100,100,"hello");
0 horizontal direction
1 vertical direction
Unions:
• user-defined data type.
• "union" keyword is used to define the union
• size of union variable = max size among the members
struct demo
{
union demo
int x;
{
double y;
int x;
};
double y;
Structure Union
Enumeration:
• Enumeration is a user-defined data type
• "enum" keyword is used to define enumeration.
• used to define string constants with integer
equivalent values
enum colors
{
BLACK,
BLUE,
GREEN,
CYAN,
RED,
.
.
WHITE
};
}
MS DOS command line
#include<stdio.h>
main(int argc,char *argv[])
{
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
}