0% found this document useful (0 votes)
98 views

C Language Class Room Notes

By Naresh It, Shiva Chaitanya Sir

Uploaded by

gelay98882
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

C Language Class Room Notes

By Naresh It, Shiva Chaitanya Sir

Uploaded by

gelay98882
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 196

Notes Link

Friday, January 21, 2022 8:37 PM

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 & Software:

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

Program-1 [Arithmetic] Prog-3 [Power] Prog-n


Prog-2 [Sqrt]
a=20 ….
b=5 ….
….
….
….
print a+b …..

print a-b
print a*b ………..
print a/b

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

compile => put together / assemble

C Language 9 AM Page 5
compile => put together / assemble

…..
……
….

Device Driver Software:

Printer => Printer Drivers


Speaker => Sound Drivers

Device driver s/w is mediator b/w


device & OS

C Language 9 AM Page 6
OS => Printer Drivers => Printer

Hardware Software

All Computer parts is a set of programs

System s/w Application s/w

used to run the computer

OS => mediator b/w user & machine


Compiler => mediator b/w HLL & LLL [at once]
Interpreter => mediator b/w HLL & LLL [line by line]
Device Driver => mediator b/w OS & the device

Hardware => all computer parts


Software => a set of programs
program => is a set of instructions

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.

Ex: Android => System s/w


Photoshop
Acrobat Reader phone pe => Appln s/w
whatsapp
Media player

Oracle SQL Server MySQL

C Language 9 AM Page 7
Oracle SQL Server MySQL

C C++ Java Python

Bank Management Software


Restaurant Management Software
Shopping mall management Software

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

Computer => Charles Babbage => 1800s

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

• Machine Language & Assembly language


are low level programming languages.
• low level programming languages are
machine friendly.

Drawbacks of Low Level Programming


Languages:
• difficult to write the code
• not portable

These drawbacks are avoided by High Level


programming Languages
C Language 9 AM Page 8
programming Languages

High Level Languages introduced in 1950s


These are Programmer-friendly.

FORTRAN => used to scientific applications

COBOL => used to business applications

Specific Purpose Programming Languages:


1 Language => 1kind of application

Exs: FORTRAN => Scientific


COBOL => Business
MATLAB => Mathematical
GRAPHIC => Graphical

General Purpose P L:
1 Language => many kinds of applications

C-Language => General Purpose P L


we can develop many kinds of applications like
business, scientific, mathematical & graphical
applications.
We can develop system software also
Ex: UNIX

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

Stand-alone [Desktop] Applications =>


the appln developed to run in one computer
Ex: Media player

Web Applications =>


C Language 9 AM Page 9
Web Applications =>
the appln will be placed in web server & it can be
accessed by many users through the browser
Ex: gmail.com facebook.com nareshit.com

Mobile Applications =>


the applns developed to run in small devices like
smart phones, tabs, remote controls ..etc
Ex: phone pe gpay

• 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

Using C-Language: LLL:


Appln s/w + System s/w • machine friendly
• System s/w
• Ex: machine assembly

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

used to run the computer used to


perform applications
Ex: OS Compiler Interpreter
Device Driver Ex:
Photoshop
media player

Portability:
C-Program developed in one system can run on any other
system even if OS is different.

Execution process of a C-Program:

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

C-Compiler Machine-3 [LINUX]


Case-2:
Different OS
hello.exe Place .c file

C-Language is Platform Dependent Programming Language.

Java, Python, C# are Platform Independent Programming


Languages.

Platform = OS + Micro Processor

Every OS has its own language


Every Microprocessor has its own language

In Platform dependent programming languages


after compilation .exe file will be created.
Ex:
hell.c => C-Compiler => hello.exe

In platform independent programming languages, after


compilation it creates intermediate code file.
Ex:
Hello.java Source code] => Java Compiler => Hello.class
[Byte Code] => JVM => Hello.exe [machine code]

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.

Sequential Programming approach:


we write the code sequentially.
Ex: Assembly Language
earlier versions of COBOL, FORTRAN

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

Disadvantages of Sequential Programming approach:


• less understandability.
• increases length of code.
• no reusability.

Advantages of Procedure-oriented approach:


• improves understandability.
• decreases length of code.
• provides reusability.

Disadvantages of Procedure-Oriented Approach:


• less reusability.
• less security.

Advantages Object-oriented Approach:


C Language 9 AM Page 13
Advantages Object-oriented Approach:
• Provides Reusability [Inheritance]
• provides security [ Class]

Features of C-Language:

General Purpose => 1 Lang => many kinds of applns

Middle Level => HLL Features + LLL Featrures

Portability => C-Program developed in one machine


can run on any other machine

Modularity => we write program in the functions


Advantages:
decreases length of code
provides reusability
improves understandability.

Extendibility:

C-Library => is a collection of header files


Header File => is a collection of built-in functions [predefined functions]

C-Library

math.h stdio.h string.h bank.h nareshit.h

pow() printf() strlen() withdraw() read()


sqrt() scanf() strrev() deposit() print()
sin() getc() strcpy() checkbalance() batch()
cos() putc() strcmp() .
tan() .

We can add our own header files to C-Library. It is


called "Extendibility".

Compiled:

• C-Language is the compiled programming language.


• Before C-Language, we were using B-Language. It was
interpreted programming language.

C Language 9 AM Page 14
interpreted programming language.
• To improve the performance C-Language developed as
Compiled Programming Language

Features of C-Language:

• General Purpose => 1 Lang => many kinds of applns

• Middle Level => HLL Features + LLL Features


Appln s/w + System s/w

• Portability => C-Program in 1 system can run on any other

• Modularity => we write program in the form of functions


• Advantages:
○ decreases length of code.
○ provides reusability.
○ improves the understandability.

• Extendibility => we can add our own header files to c-library

• Compiled => Compiler is faster than interpreter.

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()

printf(): [print format]


• is a built-in function.
• defined in "stdio.h" header file.
• stdio => standard input output
• It is output related function.
• used to print the data on console
screen [output screen].

Program to print "hello" on output screen:

#include<stdio.h>
main()
{
printf("hello");
}

What are required to develop a c-program:

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

Ex: Dev C++ Turbo C++ Code Blocks Eclipse


MS Visual C++

Downloading & installing Dev-C++:

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.

Program to print hello on output stdio.h == 300+ lines


screen:
printf()
#include<stdio.h> //300+ lines {
main() //code
{ }
printf("hello"); .
} .

In C-Language, every statement


ends with ;
; => statement separator

#include<stdio.h>:

#include<stdio.h> => preprocessor directive


# => preprocessor
with # symbol compiler understands that before going
to compile the program that has to do something

include => directive [Command / Program]


when include program runs, it attaches code of
specified header file into the program.

<> => searches in C-Library

stdio.h => header file

#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.

Escape Sequences [Backslash Characters]:

printf(" hello ");

printf(" hi "); printf(" "hello" ");

printf(" "hello "); //ERROR

'' => is non-printing character


we cannot print " directly

• 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.

Escape Sequence Meaning printf("\a\a\ahello


\n new line \t");
\t tab [5 spaces] printf("hi");
\a alert beep O/p screen
\b backspace
hello hi
\" "
\' '
\\ \

Data Types in C-Language:

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

• Data type tells the type of data which a


variable can hold.
• It also tells how much memory has to be
allocated.

Integer => number without decimal places

Ex:567 23 89 -678

Floating Point / Real => Numbers with decimal places


Ex: 56.78 45.7 5.8 -567.4532

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'

short int float


int double
long int long double
long long int
C Language 9 AM Page 19
short int float
int double
long int long double
long long int

Ex: 456 64 -34 Ex: 34.5678 123.89

Primitive Data type Memory


short int 2 Bytes
int 4 Bytes
long int 4 Bytes
long long int 8 Bytes
float 4 Bytes
double 8 Bytes
long double 16 Bytes
char 1 Byte

Declaring variables & Assigning values:


< > => Any
[ ] => Optional

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;

int => data type


age => variable

Assigning value:

Syntax:
<variable> = <constant> / <variable> / <expression>;

C Language 9 AM Page 20
Assigning value:

Syntax:
<variable> = <constant> / <variable> / <expression>;

left one is always variable. u cannot take constant


or expression

age=25;

x=50;
y=x;

z = x+y;

x+y = 50; //ERROR

Exs:

student avrg marks: 67.89

float avrg; //declaring variable

avrg=67.89; //assigning value

student section is: A

char section; //declaring variable

section='A'; //assigning value

Format Specifiers [Conversion Characters]:


• are used to print (or) read the data

data type size format specifier


int 4 bytes %d or %i
float 4 bytes %f
char 1 byte %c

Program to add two number:

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:

x=10 y=5 z=6


b=45
calculate x+y-z l=60

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

Program to find area & perimeter of the circle:

pi=3.14 area = pi*r*r


r=45.6
r=45.6 perimeter = 2*pi*r

#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);
}

Program to find area & perimeter of rectangle:

area = l*b
b=15.4
perimeter = 2*(l+b)

l=38.9

Program to find area of triangle

h=65.2

b=78.9
area = (b*h)/2

Program to print student details:

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.

Ex: "raju" "Hyd" "ameerpet" "india"

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);
}

Program to print employee details:

Output:

empid: 1234
ename: Ravi
salary: 8000.00
job: clerk
gender: M

Number System:

• Binary => 2 digits => 0,1


• Octal => 8 digits => 0 to 7
• Decimal => 10 digits => 0 to 9
• Hexa Decimal => 16 digits => 0 to 9 A B C D E F

30 => dec to bin

30

30 => dec to oct 30 => dec to hex

oct %o
hex %x (or) %X
dec %d (or) %i

program to print decimal, octal & hexa decimal value:

#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);
}

Reading data from keyboard:

Enter x:5 Enter x:100 Enter x:50


Enter y:4 Enter y:400 Enter y:60
sum=9 sum=500 sum=110

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);

Reading float value:

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);

string name holds address.


string name itself is address. no need to write &.

Program to add 2 numbers. Read 2 integers


from keyboard:

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);
}

Program to find area & perimeter of rectangle.


Read length & breadth from keyboard:

b area = l*b
perimeter = 2*(l+b)
l

main()
{
float l,b,a,p;

printf("Enter length and breadth:");


scanf("%f%f",&l,&b);

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:

• Program to find area & perimeter of circle. read


radius from keyboard.
• Program to find area & perimeter of triangle. read
base & height value from keyboard.
• Program to find volume of the box. read length,
breadth & height values from keyboard.
volume = l*b*h

Program to read student section, marks and


avrg marks & print them:

Enter section,marks, avrg:


A 567 56.7
section: A
marks: 567
avrg: 56.7

main()
{
char sec;
int m;
float a;

printf("Enter section,marks,avrg:");
scanf("%c%d%f",&sec,&m,&a);

printf("section:%c \n marks:%d \n avrg:%f",sec,m,a);

Assignment:

Program to read employee gender [M/F], empid


[1234/1235], sal [8000.00 / 12000.00] and print them.

Reading int, float & char

Program to read & print a string:

C Language 9 AM Page 27
Enter your name: Raju
Hi Raju

#include<stdio.h>
main() declare string
{
char name[20]; read string

printf("Enter ur name:"); print string


scanf("%s",name);

printf("Hi %s",name); Hi sai


}

Program to find average of 3 numbers:

4/2 = 2
/ => division operator
In C => 5/2 = 2 =>
it gives quotient value
int/int = int

float/int (or) int/float (or) float/float = float

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

avrg = sum of observations/ number of observations

C Language 9 AM Page 28
(x+y+z)/3 = 20

(x+y+z)/3.0 = 20.333

(x+y+z)/a = ?

type conversion [ type casting]:


converting one data type value to another is called
"type conversion / type casting".

3 [int to float]: => (float)3

int x,y,z,a;
(float)(x+y+z)/a (or)
(x+y+z)/(float)a (or)
(float)(x+y+z)/(float)a

Program to find average of 3 numbers:


x y z
10 20 31

avrg = (float)(x+y+z)/3 => 20.333

avrg = (x+y+z)/3 => 20

#include<stdio.h>
main()
{
int x,y,z;
float avrg;

printf("Enter 3 numbers:");
scanf("%d%d%d",&x,&y,&z);

avrg = (float)(x+y+z)/3; //type conversion

printf("average=%f",avrg);
}

// => single line comment

/* */ => multi line comment

Program to swap 2 numbers:


swap => interchange

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);
}

Swapping two numbers without taking 3rd variable:

x y
x y
20 30 After swap 30 20

x = x+y; => 20+30 = 50


y=x-y; => 50-30 = 20
x=x-y; => 50-20 = 30

short int 2 Bytes


int 4 bytes
long int 4 bytes
long long int 8 bytes

C Language 9 AM Page 30
Integer type:

short int signed [default] => +ve


2 bytes -ve
unsigned => +ve only
int
4 bytes

long int
4 bytes

long long int


8 bytes

short int 2 bytes -32768 to 32767


[16 bits]
unsigned short int 2 bytes 0 to 65535

int 4 bytes

unsigned int 4 bytes

long int 4 bytes

unsigned long int 4 bytes

long long int 8 bytes

unsigned long long 8 bytes


int

short int x=30; // 2bytes = 16 bits

30 => 11110

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0

sign
Data [15 bits]
bit

0 =>+ve 32767 => 15 bits


1 => -ve 32768 => 16 bits

In 16 bits,
1 bit => sign bit
15 bits => Data

short int => -32768 to 32767

why upto 32767 only?


why not it is accepting >32767?

32767=> 111 1111 1111 1111 => 15 bits


is the 15 bits max value

32768 => 1000 0000 0000 0000 => 16 bits


is the 16 bits min value

C Language 9 AM Page 31
is the 16 bits min value

unsigned short int x; // 2bytes = 16 bits

0 to 65535

Data [16 bits]

65535 => 1111 1111 1111 1111 [16 bits]


is the max value in 16 bits

65536 => 1 0000 0000 0000 0000 [17 bits]

Note: In C-Language, size may vary from compiler to compiler

16-bit compiler [Turbo C] 32-bit compiler [Dev-C++]

int 2 bytes int 4 bytes

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));
}

short int => -32768 to 32767

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

sizes => sizeof()


ranges => MACROs => limits.h

Floating Point types:

Floating Point => number with decimal places

Ex: 3.14 78.34 -234.56789

floating point size format precision [max


type specifier no of decimal
places]
float 4 bytes %f 6
double 8 bytes %lf 15
long double 16 bytes %Lf 18

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

to represent float value in scientific


notation, we use %e (or) %E

float max value =>

float min value =>

C Language 9 AM Page 33
C-Language Tokens:

C-Token =>
A smallest individual part of the program.

Ex:
int x=40, y=50;

C-Language tokens are:

• 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 {
}

Rules for naming an Identifier:


Ex:

• Identifier is made up of with


int total marks; //invalid
letters [a to z or A to Z],
digits [0 to 9],
int c@nareshit; //invalid
symbols [ _ $]
• Other than above chars are not
int total_marks; //valid
accepted
• An Identifier should not be
float $alary; //valid
started with digit.
• It can be started with letter or _
int _x; //valid
or $.
• It can be of any length.
int sub1 marks; //invalid
• It is case sensitive.
Ex: int x=20, X=30;
int sub1_mark$; //valid
int rno, RNO, rNO;
• keywords cannot be used as
int 1sub_marks; //invalid
identifier.
• Ex: int float short signed
if for while

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

Octal Constant => prefix octal value with 0


Ex: 036
Hexa Decimal Constant => prefix hex value with 0x
Ex: 0x1E
Binary Constant => prefix bin value with 0b
Ex: 0b11110

56.78 34.5 => Floating point Constants


'A' 'M' 'F' => Character Constants
"raju" "srinu" => String Constants

Operators:

Operator => is a symbol


it is used to perform operations like arithmetic or
logical operations

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]

According to number of operands:

can be divided into 3 types:


• Unary Operators
• Binary Operators
• Ternary Operators

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=1 b=2 c=3

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: ?:

According to the operation [purpose]:

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+y 5+2 7 int+int = int


x-y 5-2 3 int-int = int
x*y 5*2 10 int*int = int
x/y 5/2 2 int/int = int
x%y 5%2 1 int%int = int

x=5.0 y=2

5.0 + 2 7.0 float + int = float


5.0-2 3.0 float-int = float
5.0*2 10.0 float * int = float
5.0/2 2.5 float/int = float
5.0%2 ERROR float%int = ERROR

% can be applied b/w 2 integer operands.


it cannot be used on float

Relational / Comparison Operators:


These operators are used to compare 2 values.

< less than


<= less than or equals to
> greater than
>= greater than or equals to
== equals to
!= not equals to

Program to check whether the person is


eligible to vote or not:

#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");
}

Program to check whether the given number is


even or odd:

Even => 2,4,6,8,…….. => divide with 2

Odd => 1,3,5,7,…….. => divide with 2

if(n%2==0) if(n%2==0)
printf("Even"); printf("Even");
if(n%2!=0) else
printf("Odd"); printf("Odd");

== =

equals operator assignment operator

x==50 x=50

50 value will be assigned to x

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

read maths marks => m

if(m>=40)
printf("PASS");
if(m<40)
printf("FAIL");

Program to find biggest in 2 different numbers:

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.

C-Language provides following Logical Operators:

&& 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

And [&&] => All conditions should be satisfied


Or [ || ] => At least one condition should be satisfied

And, Or are used to write multiple conditions

C Language 9 AM Page 40
And, Or are used to write multiple conditions

Program check whether the person is eligible


to write Army Exam or Not. Age must be b/w
18 to 25:

In case of &&, if first condition is FALSE it will not


check remaining conditions.
In case of ||, if first condition is TRUE it will not
check remaining conditions.

Read age age = 23

if(age>=18 && age<=25)


printf("eligible"); age<18
else
printf("not eligible");

if(age<18 || age>25)
printf("not eligible");
age=16
else
printf("eligible");

&& &

Logical AND Bitwise AND

If first condn FALSE, it Even if first condition is FALSE,


will not check remaining it will check all remaining condns.
conditions

More performance Less Performance

C Language 9 AM Page 41
|| |

Logical OR Bitwise OR

If first condn is TRUE,it Even If first condn is TRUE,it


will not check remaining will check all remaining
conditions. conditions.

More performance Less Performance

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%

if(sal>=10000 && sal<=20000)


printf("increase 10%sal);
else
printf("increase 5% sal");

read gender

if(gender=='M' || gender=='F')
printf("ur gender is %c",gender);
else
printf("invalid char");

Program to find result of a student for 3 subjects:

C Language 9 AM Page 42
m p c
max marks: 100
min marks: 40 in each sub => pass

Read m,p,c

if(m>=40 && p>=40 && c>=40)


printf("PASS");

if(m<40 || p<40 || c<40)


printf("FAIL");

Not Truth Table:

c1 Not(c1)
T F
F T

Program to find result of a student


in one subject:
max marks: 100
min marks: 40 for pass

read m

m>=40 => T => PASS


if(!(m>=40))
printf("FAIL");
else
printf("PASS"); !(m>=40) => FAIL

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++,

TRUE => 1 / Non-Zero


FALSE => 0

main()
{
int x=5;

printf("%d\n",x==5); //1
printf("%d",x>5); //0
}

Expression = operators + operands + numbers

&& => All condns should be satisfied

|| => At least one condn should be satisfied

! =>

c=> T !c=> F
c=>F !c=> T

TRUE => 1 / Non-Zero


FALSE => 0

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=15 => 15 will be assigned to x

x+=20 => x=x+20 => 15+20 = 35


x-=10 => x=x-10 => 35-10 = 25
x*=4 => x=x*4 => 25*4 = 100
x/=20 => x=x/20 => 100/20 = 5
x%=3 => x=x%3 => 5%3 = 2

x=5

x=x+20 x+=20

x+=20 gets executed faster than x=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]

Post Increment Pre Increment

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:

Post Increment Pre Increment

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

First assigns x value to y. First increases x value. Then


Then x value will be x will be assigned to y
increased

In case of Printing:

Post Increment Pre Increment

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
} }

Unary Minus Operator (-x):


• Symbol: -
• Unary Operator. Because, one operand
participates in operation.
• it can be understand as: multiplying operand
with - .
• Ex:
X=5
X=-X => -(5) => -5
X=-X => -(-5) => 5

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.

& Bitwise And


| Bitwise Or
^ Bitwise Xor
<< Left shift operator
>> Right shift operator
~ Bitwise Not / Complement

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

short int x=12,y=13; // 2Bytes

x=12 => 0000 0000 0000 1100


y=13 => 0000 0000 0000 1101

x&y => 0000 0000 0000 1100 => 12


x|y => 0000 0000 0000 1101 => 13
x^y => 0000 0000 0000 0001 => 1

C Language 9 AM Page 48
Binary to Decimal [+ve]:

0000 0000 0000 1100

Take the weights of 1s and add them

0000 0000 0000 1101

Left shift Operator:


• Symbol : <<
• used to move specified no of positions to left side
• Stntax: var << no_of_poisitions

x<<5 => every bit will be moved 5 positions to left side

0011 1010 0011 1100

Right Shift Operator:


• Symbol: >>
• used to move specified number of positions to right side
• Syntax: var >> number_of_positions

x>>5 => every bit will be moved 5 positions to right side

0011 1010 0011 1100

C Language 9 AM Page 49
0011 1010 0011 1100

x=12 => 0000 0000 0000 1100


x<<2 =>

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

Bitwise Not Operator / Complement Operator:


• Symbol: ~

x ~x
1 0
0 1

x=12 => 0000 0000 0000 1100


~x => 1111 1111 1111 0011

C Language 9 AM Page 50
Binary to Decimal [-ve]:

1111 1111 1111 0011

• Take the weights of 0s with - sign & add


them
• add -1

x=20
y=25

x&y, x|y, x^y, x<<4, x>>4, ~x

Ternary Operator [Conditional Operator]:

Syntax:

Expression1 ? Expression2 : Expression3

Expression1 => Condition


Expression2 => TRUE Expression
Expression3 => FALSE Expression

Finding biggest in 2 different numbers using


ternary operator:

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:

Even => 2,4,6,8,… => divide with 2 => remainder 0


Odd => 1,3,5,7,… => divide with 2 -> remainder 1

n%2==0 ? printf("Even") : printf("Odd");

Address of Operator:
• Symbol: &
• is used to access the address of variable

x
int x;
x=50; 4 Bytes 50

5000 => &x

allocates 4 bytes memory


gives name as x for that memory location

The value in memory location can be


accessed in 2 ways:
• Using name
• Using the address

int x;
x=50;

printf("value of x=%d\n",x); //50

printf("address of x=%d\n",&x); // 5000

printf("%d",*&x); // *5000 => value at 5000 => 50

Pointing to an address gives value


at that address.

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

x=1 y=2 z=3


()
(x+y)*z => ? *
+

*/% Left to Right


+ - Left to Right

a+b*c-d/e => expression

a=1 b=2 c=3 d=4 e=2

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=1 b=2 c=3 d=4 e=2

a + b * c - d/e

a - b / c + d*e

Associativity is in two forms:


• Left to Right
• Right to Left

* / % Left to Right
= Right to Left

x = y = z = 100

OPERATOR tells order of performing operations


PRECEDENCE
ASSOCIATIVITY when multiple operators are having
same level priority then
associativity will be used

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].

C-Language provides following control structures:

Conditional if
if else
if else if
nested if
Multi-way Conditional switch
Iterative / Looping while
do while
for
Jumping goto
break
continue
return

Conditional Control Structures:


execute the statements based on condition.

• 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

The statements in "if" block get


executed when the condition is
TRUE.
It will not execute the statements
when the condition is FALSE.

Ex:
read age

if(age>=18)
printf("eligible");

If one statement is there in "if" , we have no need


to write curly braces. If multiple statements are
there in "if" we must write curly braces.

if else:

Syntax: The statements in "if" block


get executed when the condition
if(<condition>) is TRUE.
{ The statements in "else" block
//Statements get executed when the condition
} is FALSE.
else
{
//Statements
}

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 we want to perform a task based


on condition then use "if".
If we want to perform any one of the
2 tasks then use "if else".

if else if:

Syntax:
if(<Condition-1>)
{
//Statements
}
else if(<Condition-2>)
{
//Statements
}
else if(<Condition-3>)
{
//Statements
}
.
.
else
{
//Statements
}

• The statements in "if else if" get executed


when corresponding condition is true.
• When all conditions are false, it executes
else block statements.
• Writing else block is optional.
• It is used to execute the statements based
on multiple conditions.

Program to check whether the


given number is +ve or -ve or zero:

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

Program to find roots of quadratic equation:

Math Functions:

sqrt()
pow()
sin() math.h
cos()
tan()
abs()

sqrt():
is used to find square root value

Syntax:
double sqrt(double)

sqrt(100) => 10.0 [double value]

pow(): double pow(double,double)


is used to find power values

Syntax:
pow(number,power)

pow(2,3) => 8.0 [double value]

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)

Note: Angle must be specified in the form of radians

degrees to radians => multiply degrees value with pi/180


pi = 3.14

sin 90 => sin(90*3.14/180) = 1

cos(0) => cos(0*3.14/180) = 1

tan(45) => tan(45*3.14/180) = 1

abs():
used to get absolute value [non-negative].

abs(5)

abs(-5)

Program to find roots of quadratic equation:

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

Read 3 subs marks


m p c

calculate avrg = (m+p+c)/3

if(m<40 || p<40 || c<40)


printf("FAIL");
else if(avrg>=60)
printf("FIRST");
else if(avrg>=50)
printf("SECOND");
else
printf("THIRD");

Program to find biggest in 3 different numbers:

C Language 9 AM Page 60
Program to find biggest in 3 different numbers:

x y z
70 50 60

if first num is > remaining numbers => first num is greater

nested if:
Writing "if" in another "if" is called "nested if".

Syntax:

if(<condition-1>)
{
if(<condition-2>)
{
//Statements
}
}

In "if" block we can write any


number of ifs, if elses, if else ifs.
In "else" block also we can write
"if" block.

Program to find result of the student using


nested if:
Max Marks: 100
Min Marks: 40 in each sub for pass
if avrg is 60 or greater => FIRST
if avrg is b/w 50 to 59 => SECOND
if avrg is b/w 40 to 49 => THIRD

Read 3 subs marks

if(m>=40 && p>=40 && c>=40)


{
avrg = (m+p+c)/3;
if(avrg>=60)
printf("FIRST");
else if(avrg>=50)
printf("SECOND");
C Language 9 AM Page 61
printf("SECOND");
else
printf("THIRD");
}
else
printf("FAIL");

to perform one task based on condition => if

to perform any one of the 2 tasks based on


condition => if else

to perform any one of more than 2 tasks based


on multiple conditions => if else if

when outer condition is true then only inner


condition should be checked => nested if

if(inter == "PASS")
{
if(course=="EEE")
display EEE syllabus
else if(course=='CSE')
display the CSE syllabus
}

Program to find biggest in 3 different


numbers using nested if:

x y z
80 50 60

first number is > remaining nums => first num is big


80>50 80>60 => 80 is big
x>y && x>z => x is big

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:

using 3rd variable


without 3rd variable

read 3 numbers => x,y,z

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);
}

Program to find biggest in 3 different numbers using


ternary [conditional operator]:

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;

Multi-way Conditional Control Structure:

executes the statements based on value


matching.

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
}
}

Program to display weekday name of given


week day number:

Enter week day number: 15 1 = Sunday


Sunday 2 = Monday
3 = Tuesday
.
.
7 = Saturday

C Language 9 AM Page 64
7 = Saturday

Read week day number => n

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

Program to check whether the given number is even


or odd using switch:

Even: 2,4,6,8, …… => divide with 2 => remainder 0


Odd : 1,3,5,7, …. => divide with 2 => remainder 1

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.

Program to check whether the given alphabet is vowel


or consonant:

a
e
i
o
u => vowel

Read alphabet => alpha

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 & if else if both are acting as same. then what


is the difference b/w switch & if else if:

switch(expression) if(c1)
{ {
case c1: //stmts
//stmts }
break; else if(c2)
case c2: {
//stmts //stmts
break; }
. .
. .
default: else
//stmts {
//stmts
} }

• "switch" can check equality condition only.


"if else if" can check any type of condition
like x>0 x<0

• "if else if" gets executed faster than "switch"

• to provide readability for the program, we use "switch"

• "switch" is suitable for choice-based programming /


menu-driven programming.

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");
}

Program to demonstrate choice based


programming:

1. Red
2. Blue
3. White
4. Black
Select ur favourite color [1 to 4]: 1
ur fav color is: red

Program to perform arithmetic operations using switch:

Enter an operator( + - * /): + Enter an operator( + - * /): *


enter 2 nums: 10 5 enter 2 nums: 10 5
sum=15 product=50

Enter an operator( + - * /): - Enter an operator( + - * /): /


enter 2 nums: 10 5 enter 2 nums: 10 5
diff=5 quotient=2

Enter an operator( + - * /): >


Invalid choice

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
}

Looping [Iterative] Control Structures:

100 hellos

printf("hello\n");
hello
printf("hello\n");
hello Loop(100 times)
printf("hello\n");
hello {
.
. printf("hello\n");
.
. }
printf("hello\n");
hello

• Looping Control Structures are used to execute the


statements repeatedly.
• If our requirement is executing same code
repeatedly, then write repetitive code in the loop.
• Loop provides code optimization [less code].

C-Language provides 3 looping control structures:


• while
• do while
• for

C Language 9 AM Page 69
while loop:

Syntax:

Initialization if(<condition>)
while(<condition>) {
{ //statements
//statements }
//step
}

For any looping control structure 3 things are


required. They are:
• Initialization => starting value
• Condition => ending value
• Step => increase or decrease the value

1 i=1; //initialization
2 while(i<=100) //condition
3 {
. print i;
. i++; //step
100 }

Program to print numbers from 1 to 4:

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

Program to print multiplication table of


given number:

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

Program to find number of digits in


given number:

Enter n:456 Enter n:67890


no of digits=3 no of digits=5

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

Program to find sum of digits of given number:

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

Program to check whether the given number is


Armstrong Number or not:

Armstrong Number
Sum of cubes digits = Number

Ex: 1 153 370 371 407

C Language 9 AM Page 73
Program to find reverse number:

Enter n: 123 Enter n: 567


Reverse Number 321 Reverse Number 765

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

Program to check whether the given number


is palindrome or not:

Palindrome:
Number = Reverse Number

Ex: 232 2332 121

do while Loop:

Syntax:

C Language 9 AM Page 74
do while(<condition>)
{ {
//Statements //Statements
}while(<condition>); }

The statements in "while"


The statements in "do while"
loop get executed as long as
loop get executed as long as
the condition is TRUE.
the condition is TRUE except
first time.

Program to print numbers from 1 to 4:

i
i=1;
1
2 do
3 {
4 printf("%d\n",i);
i++;
}while(i<=4);

Differences b/w while & do while:

C Language 9 AM Page 75
while do while

Syntax: Syntax:
while(<condition>) do
{ {
//Statements //Statements
} }while(<condition>);

Entry-Controlled Loop Exit-Controlled Loop

It first checks the First executes the statements.


condition. Then executes Then checks the condition
the statements.

The statements in while The statements in do while loop


loop get executed as long get executed as long as the
as the condition is TRUE condition is TRUE except first
time.

Minimum number of Minimum number of


execution times for execution times for
while loop is ZERO do while loop is ONE

main() main()
{ {
int x=5; int x=5;

while(x>5) do
{ {
printf("hello"); printf("hello");
} }while(x>5);
} }

When we know When we don't know


exact number of exact number of
iterations then go for iterations then go for
"while" loop "do while" loop.

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:

for(<Initialization> ; <condition> ; <step>)


{
//Statements
}

Program to print numbers from 1 to 4:

i
1 for(i=1;i<=4;i++)
2 printf("%d\n",i);
3
4

Program to print numbers from 4 to 1:

for(i=4;i>=1;i--) 4
printf("%d\n",i); 3
2
1

Program to print even numbers b/w 2 to 20:

i
2 for(i=2;i<=20;i=i+2)
4 printf("%d\n",i);
6
8
.
.
20

Program to print odd numbers b/w 1 to 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
}

Program to print rounded values in


10s:

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

Program to print multiplication table


Program to find factorial of given number
Program to print factors & number of factors
Program to check whether the given number is prime or not
Program to check whether the given number is perfect or not

Program to print multiplication table of given


number:

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);

Program to find factorial of a number:

4! =

1*5*9*13

4! => 4*3*2*1

C Language 9 AM Page 79
4! => 4*3*2*1

Program to print factors & number of factors of


given number:

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

Program to check whether the given number is


prime or not:

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

Program to check whether the given number is


perfect or not:

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
}

Program to find power value using for loop:

Program to find sum of first n numbers


without using formula:

Enter n: 4 => 1+2+3+4


sum=10

n(n+1)/2 => 4*5/2 = 10

1+2+3+4

C Language 9 AM Page 82
1+2+3+4

Program to find sum of squares of first n numbers:

n(n+1) (2n+1)/6 => 3(4)(7)/6 =


3*4*7/6 =
84 /6 = 14

n=3

Program to find sum of the following series:

C Language 9 AM Page 83
Assignment:

Program to print Fibonacci Series:

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
}
.
.

Jumping Control Structures:

C-Language provides 4 Jumping Control Structures:


• goto
• break
• continue
• return

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

Jumping Backward Jumping Forward

Syntax: Syntax:

//statements //statements
<label>: goto <label>;
//statements //statements
goto <label>; <label>:
//statements //statements

acts like loop

Note:
All programs which we can do using loops
can be also done by "goto"

Program to print numbers from 1 to 4 using goto:

i
1
i=1;
2
3
nareshit:
4 i <=4
printf("%d\n",i); //1
i++; //i=2
if(i<=4)
goto nareshit;

Program to find factorial of a number using goto:

n=4 4!

1*2*3*4

• Printing multiplication table


• find sum of series 1+2+3+…..+n

C Language 9 AM Page 85
Program to restrict the user from entering -ve value:

Enter ur age: -15


Enter ur age: -40
Enter ur age: -35
Enter ur age: -23
Enter ur age: 25
ur age is: 25

abs():
abs(--)
{
absolute => non-negative
//logic
}
abs(5) => 5
abs(-5) => 5

Program to get absolute value [Jumping Forward]:

main()
{
int n;

printf("Enter a +ve num:");


scanf("%d",&n);
if(n>0)
goto xyz;
n=-n;
xyz:
printf("%d",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

Generally, when loop condition is false loop will be


terminated. Irrespective of loop condition we want to
terminate the loop in the middle of execution. For this
use "break" in the loop.

main()
{
int i;

for(i=1;i<=10;i++)
{
printf("%d\n",i); //1 2 3 4 5
if(i==5)
break;
}
}

Array

passed students HTNOs

200 students => 100 are passed

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

Assume that number has already 2 factors.


1 & that number.
If number has 3rd factor then it is not prime
number. otherwise it is prime number

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;
…….
…..

Program to print numbers from 1 to 10


except 5 and 7:

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

to come out of switch or loop => we use break

to come out of function => we use return

return can be used for 2 purposes.


1. to come out of function in the middle of execution
Ex:
main()
{
printf("hi\n");
return;
printf("bye");
}

2. to send the result out of the function

Ex:
int f1()
{
int x=20,y=30;

return x+y; //20+30 = 50


}
main()
{
int k;
k=f1();
printf("sum=%d",k);
}

Nested Loops:
Writing Loop in another Loop is called "Nested Loop".

while(….) while(….) while(….)


{ { {
while(…) for(…) do
{ { {
} } }while(..);
} } }

for(….) for(….) for(….)


{ { {
while(…) for(…) do
{ { {
} } }while(..);
} } }

C Language 9 AM Page 89
{ { {
} } }while(..);
} } }

do do do
{ { {
while(…) for(…) do
{ { {
} } }while(…)
}while(..); }while(..); }while(..);

Loop => executes statements repeatedly


Nested Loop => executes the loop repeatedly

hello hello hello hello hello


hello hello hello hello hello
for(i=1;i<=10;i++)
hello hello hello hello hello
{
hello hello hello hello hello
for(j=1;j<=5;j++)
hello hello hello hello hello
printf("hello ");
hello hello hello hello hello
printf("\n");
hello hello hello hello hello
}
hello hello hello hello hello
hello hello hello hello hello
hello hello hello hello hello

for()
{
for()
{
for()
{
}
}
}

Nested Loops:

Loop => used to execute the statements repeatedly

Nested Loop => used to execute the Loop repeatedly.

Program to print prime numbers b/w 1 to 20:

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);
}

//program to print prime numbers


b/w given range

#include<stdio.h>
main()
{
int n,count,i,s,e;

printf("Enter staring and ending


value:");
scanf("%d%d",&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
}

Program to print perfect numbers b/w 1 to 1000:

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);
}

Program to print Armstrong numbers b/w 1 to 1000:

6*6*6 = 216

Pattern Programs:

Program to print following pattern:

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");
}

Program to print following pattern:

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");
}

Program to print following pattern:

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:

n=5 p = (n/2)+1 => 5/2 = 2+1 = 3

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.

math.h stdio.h string.h


sqrt() printf() strlen()
pow() scanf() strupr()
sin() getc() strlwr()
putc() strrev()

User-Defined Functions:
We can define our own functions. These functions
are called user-defined functions.

Ex:
nareshit() f1() ramu() fact() add()
withdraw() deposit()

Syntax to define the function:

C Language 9 AM Page 98
Syntax to define the function:

<return_type> <function_name>([<argument_list>])
{
//STATEMENTS
}

[ ] => optional
< > => any

What are required to make a function useful?

3 things are required to use a function:

• 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

FUNCTION = FUNCTION HEADER + FUNCTION BODY

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);

Different ways of Writing a Function:

A function can be written in 4 ways: They are:


• No Argument, No Return
Argument, No Return
C Language 9 AM Page 100
• Argument, No Return
• No Argument, Return
• Argument, Return

Argument / Parameter => Input value

Return => Result [output] value

int add(int x,int y)


{
return x+y;
}

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.

int add(int x,int y) //x, y are formal arguments


{
return x+y;
}
main()
{
int a=5,b=4;
add(a,b); //a,b are actual arguments

add(5,2);
}

C Language 9 AM Page 101


arguments
pow(2,3)

pow(double x,double y)

There are 2 types of arguments. They are:


• Formal Arguments =>
The arguments which are declared in function header
• Actual Arguments =>
The arguments in function call

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();
}

C Language 9 AM Page 102


○ return <constant/expression>;

To return a value [result] out of the function, we use


"return".

int f1()
{
return 5;
}
main()
{
int k;
k=f1();
printf("%d",k);
}

ARGUMENT used to bring value into function


RETURN send result out of function

adding 2 numbers:

No Argument, No Return:
This kind of function cannot take any arguments &
cannot return any value.

void add() () => no arg


{ (void)
int x,y;

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);

void add(int x,int y)


{
printf("sum=%d\n",x+y);
}
main()
{
add(5,4);
}

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;
}

Define a function to find average of 3 numbers:

float average(int x,int y,int z)


{
return (float)(x+y+z)/3;
}

Define a function to print student details:

void showstd(char s,int m,float a)


{
printf("section:%c \n marks:%d \n avrg marks:%f",s,m,a);
}
main()
C Language 9 AM Page 105
main()
{
showstd('A',567,56.7);
showstd('B',786,78.6);
} section: A
marks: 567
avrg marks: 56.7

Define a function to print multiplication table:

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 power(int n,int p)


{
int i,r=1;
for(i=1;i<=p;i++)
r=r*n;
return r;
}
main()
{

C Language 9 AM Page 106


{
int k;
k=power(2,3);
printf(2 power 3=%d\n",k);

printf("5 power 3=%d",power(5,3));


}

Define a function to find factorial of a number:

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));
}

Can we define multiple functions in a C-Program?


Yes

Defining multiple functions:

Define the functions to perform arithmetic operations:


add(), sub(), product(), div()

C Language 9 AM Page 107


Define the functions to perform arithmetic operations:
add(), sub(), product(), div()

int add(int x,int y)


float div()
{
{
return x+y;
int x,y;
}

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));

printf("2 power 3=%d\n",cube(2));


printf("3 power 3=%d\n",cube(3));
printf("5 power 3=%d\n",cube(5));

printf("2 power 8=%lf\n",power8(2));


printf("3 power 8=%lf\n",power8(3));
}

can a function return multiple values?


No

Every function must be called directly or indirectly


from "main". Because, main is entry point.

Assignment:

• Define a function to find sum of digits of a


number.
• Define a function to find number of digits of a
number.
Define a function to print reverse number
C Language 9 AM Page 109
• Define a function to print reverse number
• Define a function to check whether number is
armstrong or not.
• Define a function to check whether a number is
perfect or not.
• Define a function to check whether a number is
palindrome or not
• Define a function to check whether a number is
even or odd.
• define a function to swap 2 numbers
• define a function to find sum of first n numbers:
1+2+3+….+n

Program to check whether the number is prime or not:

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);
}

C Language 9 AM Page 110


Defining our own header file:

math.h nareshit.h

sqrt() power()
sin() fact()
pow() square()
cube()

Creating header file:

• Open a new file.


• Define multiple functions.
○ Ex: fact() power() square() cube()
• Save it with the name "nareshit.h" in the folder
"cbatch9am" which is in "d:" drive.

Using header file in the program:


• Open a new file
• call the functions of "nareshit.h" header file.
• Above of all, write #include"nareshit.h"

#include"nareshit.h" => searches in current directory


#include"d:\cpp5\nareshit.h" => searches in d: drive cpp5 folder
#include<nareshit.h> => searches in C-Library

Tools =>

C Language 9 AM Page 111


Tools =>

Screen clipping taken: 3/7/2022 10:10 AM

C Language 9 AM Page 112


Recursion
Monday, March 7, 2022 10:19 AM

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.

Program to find factorial of a number using RECURSION:

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
}

Program to find power value using RECURSION:

C Language 9 AM Page 113


int power(int n,int p)
power(2,3)
{
if(p==0)
2*power(2,2)
return 1;
2*power(2,1)
else
2*power(2,0)
return n*power(n,p-1);
1
}

Program to find sum of digits of a number


using RECURSION:

sum(123) int sum(int n)


n%10 +sum(n/10) {
123%10 + sum(123/10) if(n==0)
3 + sum(12) return 0;
2 + sum(1) else
1 + sum(0) return n%10 + sum(n/10);
}

Program to print fibonacci series using RECURSION:

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".

Ex: Fibonacci Series

int fibo(int n)
{
if(n==0 || n==1)
return n;
else
return fibo(n-1)+fibo(n-2);
}

Iteration [Loops] VS Recursion:

• Iteration is used execute the statements in the


loop repeatedly. Whereas Recursion executes
the statements in Function repeatedly.
• Iteration works faster than Recursion.
• Just to provide readability for some problems,
we use RECURSION.

C Language 9 AM Page 115


Storage Classes
Wednesday, March 9, 2022 9:40 AM

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 {

There are 4 storage classes in C-Language: printf("%d\n",x);


• auto [local] }
• extern [global] main()
• static {
• register f1();
}

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

• Default value : 0 {In older => default value: garbage}

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()
{ {

C Language 9 AM Page 116


Local VS Global:
int x=100; int x=100;
void f1() void f1()
{ {
int a=80; int x=80;
printf("%d\n",a); printf("%d\n",x);
printf("%d\n",x); printf("%d\n",x);
} } 80
main() main() 80
{ { 70
int b=70; int x=70; 70
f1(); 80 f1();
printf("%d\n",b); 100 printf("%d\n",x);
printf("%d\n",x); 70 printf("%d\n",x);
} 100 }

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

static local variable: auto


• A static variable which is declared inside of function extern
• Scope => Function
• Lifetime => Program

static global variable:


• A static variable which is declared outside of all functions
• Scope => Program
• Lifetime => Program

• default value is ZERO


• For static variable memory will be allocated only
once.
• static variable is initialized only once.
• static variable can be used as counter.

C Language 9 AM Page 117


void f1()
static x auto x
{
static int x=0; function call:1
x++; function call:1
printf("function call:%d\n",x); function call:1
}
main()
function call:1
{
function call:2
f1(); f1(); f1();
function call:3
}

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

Storage class Scope Life Storage Location Default value


Time
auto Functio Function RAM 0
n
extern Program Program RAM 0
static local Functio Program RAM 0
n
static global Program Program RAM 0
register Functio - Register garbage
Function n value
Types of Functions : 2 Types : Built-in, user-defined
What are required to use a function? def, dec, call
Argument [Parameter]
Return
Different ways of writing a Function: 4 ways
Creating Header File
Recursion
Storage Classes

C Language 9 AM Page 118


Arrays
Thursday, March 10, 2022 10:35 AM

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

int x; //x => can hold 1 value


Array:
int x[5]; => x => 5 values
• Array is a set of elements of same
x => int array
data type.
• Array elements share common
name.
50
• To refer array elements, use
Indexes. 30
• Array Indexing starts from 0 in 'C'. 90
• Array Indexing cannot be -ve in 'C' 40
• Array elements are stored in 60
sequential memory locations.
• Array name holds first element's
address. This address is called
"Base Address".

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]

200 employees salary values


sal1 = 4000
sal2 = 5000
sal3 = 8000 sal1+sal2+…+sal200
sal4 = 3000
.
.
sal200 = 6000

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

Single Dimensional Array:


It can represent either a row or a column.

Ex:
40
40 90 20
90
ROW
20
Column

C Language 9 AM Page 119


C Language 9 AM Page 120
Column

Multi-Dimensional Array:
It can represent both rows & columns.

Ex:
50 70 40
35 42 61

Single Dimensional Array:


declaring a variable:
Declaring single dimensional array: int x;
Ex-1:
int x[5]; Initializing a variable:
// x array can hold 5 elements int x=50;
//5*4 = 20 Bytes
Printing a variable:
Ex-2: printf("%d",x);
double a[10];
// a array can hold 10 elements Reading a variable:
//10*8 = 80 Bytes scanf("%d",&x);
a[0] => 4000
a[1] => 4008

Initializing single dimensional


array:
int x[5] = {55,89,71,23,92};
(or)
int x[] = {55,89,71,23,92};

Printing single dimensional array: printf("%d\n",x[0]); //55


printf("%d\n",x[1]); //89
for(i=0;i<5;i++)
printf("%d\n",x[2]); //71
printf("%d\n",x[i]);
printf("%d\n",x[3]); //23
printf("%d\n",x[4]); //92

//i=index 5=> no of elements

Reading Single Dimensional Array:

printf("Enter x-array elements:");


for(i=0;i<5;i++)
scanf("%d",&x[i]); scanf("%d",&x[0]);
scanf("%d",&x[1]);
scanf("%d",&x[2]);
scanf("%d",&x[3]);
scanf("%d",&x[4]);

Examples on single dimensional array:

Program to demonstrate initializing 1D-Array:

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.

Program to read & print 1D-Array:

C Language 9 AM Page 121


C Language 9 AM Page 122
Program to assign [copy] one array elements
to another:

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]

Program to assign one array elements to


another reversely: [printing reverse array]:

x[10], y[10] , n= 3

10 x[0] y[0]
20 x[1] y[1]
30 x[2] y[2]

Program to append two arrays:

n=3, x[10], y[10], z[20] 10 z[0]


20 z[1]
10 x[0] 40 y[0] 30 z[2]
20 x[1] 50 y[1] 40 z[3]
30 x[2] 60 y[2] 50 z[4]
60 z[5]

for(i=0;i<n;i++)
{
z[i] = x[i];
z[n+i] = y[i];
}

Appending 2 arrays alternatively

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]

e=100 => element not found


e=50 => element found

2 Searching Techniques:
• Linear Search
• Binary Search

Linear Search [Sequential Search]:


• Compare searching element with every element of
the array.

C Language 9 AM Page 123


C Language 9 AM Page 124
the array.
• It is possible even if elements are in Ascending
Order or Descending Order or any other order.

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;
}

Binary Search [Dictionary Search]:


• It is possible when elements are in
Ascending Order.

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.

C Language 9 AM Page 125


C Language 9 AM Page 126
x[j] x[j+1]
8 8 8 8 8 x[0]>x[1]
3
9 9 5 5 5 x[1]>x[2] 8
for(i=1;i<n;i++)
I-PASS x[2]>x[3]
5 5 9 7 7 {
x[3]>x[4]
7 7 7 9 3 for(j=0;j<n-i;j++)
3 3 3 3 9 {
if(x[j]>x[j+1])
{ temp
8 5 5 5
x[0]>x[1] temp=x[j];
II-PASS 5 8 7 7 x[1]>x[2] x[j]=x[j+1];
7 7 8 3 x[2]>x[3] x[j+1]=temp;
3 3 3 8 }
9 }
}
5 5 5 x[0]>x[1]
III-PASS 7 7 3 x[1]>x[2]

3 3 7
8
9

5 3
x[0]>x[1]
IV-PASS 3 5
7
8
9

Program to find sum of elements of


the Array:

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

Program to find maximum element & minimum


element in the array:

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

• Find average of elements of the


array

MODIFY
INSERT
DELETE

Program to modify an element of the array


at given position:

x[10]
Read elements
10
n=5
20
x[2] = 100;

C Language 9 AM Page 127


C Language 9 AM Page 128
x[10]
Read elements
10
n=5
20
x[2] = 100;
100
for(i=0;i<5;i++)
40
printf("%d\n",x[i]);
50

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

p => index p-1

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;

printf("Enter number of elements:");


scanf("%d",&n);

printf("Enter x-array elements:");


for(i=0;i<n;i++)
scanf("%d",&x[i]);

printf("Enter the position to be modified:");


scanf("%d",&p);

printf("Enter new element:");


scanf("%d",&e);

x[p-1]=e;

for(i=0;i<n;i++)
printf("%d\n",x[i]);
}

Program to insert an element in the array at


given position:

x[10] n=5 p=2


10
e=100
100
10 x[0]
20
20 x[1] 30
30 x[2] 40
40 x[3] x[5] = x[4] 50
x[4] = x[3]
50 x[4]
x[3] = x[2]
x[5]
x[2] = x[1]

x[10] n=5 p=2 e=100

10 x[0]
20 x[1]
30 x[2]
40 x[3]
50 x[4]
x[5]

C Language 9 AM Page 129


C Language 9 AM Page 130
50 x[4]
x[5]

Program to delete an element from the array at


given position:

x[10] n=5 p=2


10
10 x[0] 30
20 x[1] 40
50
30 x[2]
40 x[3]
50 x[4]

x[10] n=5 p=2

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

Two Dimensional Array:


• collection of 1D-Arrays is called
2D-Array.
• Row indexing starts from 0.
• Column Indexing starts from 0 x 1000
int x[3]

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:

int x[2][3] = { {10,20,30},

C Language 9 AM Page 131


C Language 9 AM Page 132
int x[2][3] = { {10,20,30},
{40,50,60}
};
(or)
int x[2][3] = {10,20,30,40,50,60};
(or)
int x[][] = {10,20,30,40,50,60}; //Invalid
int x[][3] = {10,20,30,40,50,60}; //valid

x[0] x[1] x[2]


Printing 2D-Array:
10 20 30
i => row index j=> col index 40 50 60

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");

When i=0 , first row will be printed


When i=1, second row will be printed

Reading 2D-Array:

printf("x-array elements:");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&x[i][j]);

Program to demonstrate initializing


2D-Array:

Program to read & print 2D-Array


elements:

2D-Array is suitable to represent the MATRIX

Square Matrix:
no of rows = no of cols
Ex:
2X2 3X3 4X4

Rectangle Matrix:
no of rows != no of cols
Ex:
2X3 4X2 6X5

Program to read & print square


matrix:

Program to copy [assign] one matrix to another:

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]; }

C Language 9 AM Page 133


C Language 9 AM Page 134
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]
x y y[1][j] = x[1][j]; }

20 20 y=x;

Transpose Matrix:
Interchanging rows & columns

Program to find transpose of given matrix:

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]

i=0 => 1ST ROW OF X BECOMES 1ST COLUMN OF Y


i=1 => 2nd Row OF X becomes 2nd column of y

Program to find sum of elements of


the matrix:

10 20
10 + 20 + 30 + 40
30 40

Program to find sum of elements of


principal diagonal:
SQUARE MATRIX n=3

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

Program to find sum of elements of upper


left triangle:

10 20 30
40 50 60
70 80 90

10+20+30+40+50+70 = 220

C Language 9 AM Page 135


C Language 9 AM Page 136
Program to add two matrices:
[Matrix Addition]

Rule:
first matrix size = second matrix size

X 2X2 Y 2X2 => Addition possible


X 2X2 Y 2X3 => Addition not possible

10 20 1 2
y=
X= 30 40 3 4

10+1 20+2 z[0][0] = x[0][0]+y[0][0]


Z =
30+3 40+4 z[0][1] = x[0][1]+y[0][1]

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

X Matrix => 2X3


Y Matrix => 2X3

X Matrix => 2X3


Y Matrix => 3X2

1*7 + 2*9 + 3*11 = 58


X-Matrix => 2X3 => mXn
Y-Matrix => 3X2 => pXq
1*8 + 2*10 +3*12 = 64

4*7 + 5*9 + 6*11 = 139

4*8 + 5*10 + 6*12 = 154

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
}

x[0][0] * y[0][0] + x[0][0] * y[0][1] +


x[0][1] * y[1][0] + x[0][1] * y[1][1] +
x[0][2] * y[2][0] x[0][2] * y[2][1]
x[1][0] * y[0][0] + x[1][0] * y[0][1] +
x[1][1] * y[1][0] + x[1][1] * y[1][1] +
x[1][2] * y[2][0] x[1][2] * y[2][1]

x[0][0] * y[0][0] + x[0][0] * y[0][1] +


x[0][1] * y[1][0] + x[0][1] * y[1][1] +
x[0][2] * y[2][0] x[0][2] * y[2][1]
x[1][0] * y[0][0] + x[1][0] * y[0][1] +
x[1][1] * y[1][0] + x[1][1] * y[1][1] +
x[1][2] * y[2][0] x[1][2] * y[2][1]

C Language 9 AM Page 137


C Language 9 AM Page 138
for(i=0i;i<m;i++)
{
for(m rows)
for(j=0;j<q;j++)
{
{
for(q columns)
z[i][j] = 0;
{
for(k=0;k<p;k++)
addition
z[i][j] = z[i][j] + x[i][k] * y[k][j];
}
}
}
}

Types of Arrays:
• Single Dimensional => either a row or a column

• Multi-Dimensional => rows & columns


○ 2D-Array => colln of 1d-arrays
○ 3D-Array => colln of 2d-arrays
○ 4D-Array => colln of 3d-arrays
○.
○.
○ nD-Array => colln of n-1d-arrays

Three Dimensional Array:


3D-Array is a collection of 2D-Arrays

10 20 30
40 50 60

11 22 33
44 55 66

3D-Array

x[0] 1st 2D-array Address


x[0][0] 1st 2D-Array 1st row Address
x[0][0][0] 1st 2D-Array 1st row 1st element
&x[0][0][0] 1st 2D-Array 1st row 1st element's address

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:

int x[2][2][3] ={ { {10,20,30}, {40,50,60} },


{ {11,22,33}, {44,55,66} } };
(or)
int x[2][2][3] = {10,20,30,40,50,60,11,22,33,44,55,66};
(or)
int x[][][] = {10,20,30,40,50,60,11,22,33,44,55,66}; //Invalid
int x[][][3] = {10,20,30,40,50,60,11,22,33,44,55,66}; //Invalid
int x[][2][3] = {10,20,30,40,50,60,11,22,33,44,55,66}; //valid

Printing 3D-Array:

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

C Language 9 AM Page 139


C Language 9 AM Page 140
Printing 3D-Array:

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");
}

i=0 => 1st 2D-Array will be printed


i=1 => 2nd 2D-array will be printed

Reading 3D-Array:

printf("Enter x-array elements:");


for(i=0;i<2;i++) i 2D-Array Index
for(j=0;j<2;j++)
j row index
for(k=0;k<3;k++)
k column index
scanf("%d",&x[i][j][k]);

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

Passing arrays to function:

Passing 1D-Array to Function: add(int x, int y)


{
void PrintArray(int[],int); }
void PrintArray(int x[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d\n",x[i]);
}
main()
{
int a[] = {10,50,20,30,80};
PrintArray(a,5);
}

Passing 2D-Array to Function:

void PrintArray(int[][3],int,int);

void PrintArray(int x[][3],int r,int c)


{
int i,j;

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d\t",x[i][j]);
printf("\n");

C Language 9 AM Page 141


C Language 9 AM Page 142
printf("\n");
}
}
main()
{
int a[][3] = { {10,20,30},{40,50,60} };
PrintArray(a,2,3);
}

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;

to hold marks of 100 students for 1 subject => 1D-Array


int m[100];
1st student => m[0]=45
2nd student => m[1]=70
.
.
100th student => m[99] = 89;

to hold marks of 100 students for 3 subjects => 2D-Array

45 67 80
88 55 71

.. .. ..

To hold 100 students marks for 3 subjects for 6


semesters => 3D-Array

int x[6][100][3];

45 67 80
88 55 71

.. .. ..

45 67 80
88 55 71

.. .. ..
.
.
45 67 80
88 55 71

.. .. ..

C Language 9 AM Page 143


C Language 9 AM Page 144
Strings
Tuesday, March 22, 2022 10:33 AM

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.

Program to demonstrate initializing & printing a string:

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");

C Language 9 AM Page 146


}

Program to read & print a string:

#include<stdio.h>
main()
{
char x[10];

printf("Enter ur name:");
scanf("%s",x);

printf("%s",x);
}

Reading & Printing string using gets() & puts():

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()

strlen() [STRing LENgth]:


used to find length of the string.
It means number of characters in
string.

Syntax:
strlen(string)
Ex:
strlen("raju") => returns 4
strlen("sai") => returns 3

Program to find length of the string


using strlen() function:

#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);
}

Find length of the string without using strlen() function:

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

int strlength(char a[])


{
int count=0;

while(a[count]!='\0')
count++;

return count;
}

strcpy():
used to copy one string to another.

Syntax:
strcpy(string1,string2)

Ex:
char x[10];

strcpy(x,"ravi"); => ravi will be copied to x

Program to demonstrate strcpy() function:

#include<string.h>
#include<stdio.h>
main()
{
char x[10],y[10];

C Language 9 AM Page 149


printf("Enter a string:");
scanf("%s",x);

strcpy(y,x);

printf("x=%s \t y=%s",x,y);
}

Program to copy one string to another without


using strcpy() function:

's' x[0] 's' y[0] y[0] = x[0]


'a' x[1] 'a' y[1] y[1] = x[1]
y[2] = x[2]
'i' x[2] 'i' y[2]
'\0' x[3] y[3]

y[3] = '\0';

strrev():
used to find reverse string.

Syntax:
strrev(string)

Ex:
char x[10] = "sai";
strrev(x);
print x => ias

Program to demonstrate strrev() function:


C Language 9 AM Page 150
Program to demonstrate strrev() function:

Program to reverse the string without using


strrev() function:

's' x[0] 'i' y[0]


'a' x[1] 'a' y[1]
'i' x[2] 's' y[2]
'\0' x[3] y[3]

for(i=0;x[i]!='\0';i++)
y[n-i-1] = x[i];

strcat(): [STRing conCATenate]


used to concatenate [combine] 2 strings

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

's' x[0] 't' y[0] 's' z[0] z[i]=x[i]


'a' x[1] 'e' y[1] 'a' z[1] z[0] = x[0]
z[1] = x[1]
C Language 9 AM Page 151
's' x[0] 't' y[0] 's' z[0] z[i]=x[i]
'a' x[1] 'e' y[1] 'a' z[1] z[0] = x[0]
z[1] = x[1]
'I' x[2] 'j' y[2] 'I' z[2]
z[2] = x[2]
'\0' x[3] 'a' y[3] 't' z[3]
'\0' y[4] 'e' z[4]
i
'j' z[5]
for(i=0;x[i]!='\0';i++) z[3] = y[0]
'a' z[6]
z[i]=x[i]; z[4] = y[1]
for(i=0;y[i]!='\0';i++) z[7] z[5] = y[2]
z[n+i]=y[i]; z[6] = y[3]
z[n+i]='\0';

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

strcmp("sai","krishna") => 1st greater => returns 1


strcmp("krishna","sai") => 2nd greater => returns -1
strcmp("Raj","raj") => 2nd greater => returns -1
strcmp("ravi","ravi") => equal => returns 0
strcmp("ravi","raju") => 1st greater => returns 1

Program to check whether the given string is palindrome


or not:
Ex: madam oppo liril oyo noon nun mom dad
arora malayalam

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();

Program to count number of words, lines, upper case chars,


lower case chars, digits & special symbols in the given text:

nw=0; nl=0 nuc=0 nlc=0 nd=0


computer is an
nss=0
electronic device.
while((ch=getchar())!=EOF)
it is used to store
{
the data.
if(ch==' ')
F6
nw++;
else if(ch=='\n')
{
nl++;
A to Z => 65 to 90
nw++;
}
else if(ch>=65 && ch<=90)
nuc++;
else if(ch>=97 && ch<=122)
nlc++;
else if(ch>=48 to ch<=57)
nd++;
else
C Language 9 AM Page 154
else
nss++;
}

#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);
}

1D Char Array => String

2D Char Array:
2D Char Array => a set of 1D Char Arrays

2D Char Array is a set of strings

'r' 'a' 'm' 'u' '\0'


's' 'a' 'I' '\0'
'a' 'r' 'u' 'n' '\0'

C Language 9 AM Page 155


Declaring 2D Char Array:

char x[10][20];

It can hold 10 strings. Each string can have 20 chars

Initializing 2D-Char Array:

char x[10][20] = {"raj","sai","kiran","naresh"};

printing 2D-Char Array:

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]);

reading a set of strings:

printf("Enter 4 strings:"); scanf("%s",x[0]);


for(i=0;i<4;i++) scanf("%s",x[1]);
scanf("%s",x[i]); scanf("%s",x[2]);
scanf("%s",x[3]);

Assignment:

Program to search for a string in a set of strings. Do


this using Linear Search & Binary Search:

'r' 'a' 'j' 'u' '\0'

e 's' 'a' 'I' '\0'


't' 'e' 'j' 'a' '\0'
vijay

C Language 9 AM Page 156


e 's' 'a' 'I' '\0'
't' 'e' 'j' 'a' '\0'
vijay

Binary Search => enter strings in alphabetical order

strcmp() => used for string comparison

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;
}

C Language 9 AM Page 157


Pointers
Monday, March 28, 2022 10:21 AM

Types of Variables:

2 Types:
• Data Variable
• Pointer Variable

• Data Variable => holds data


○ int x => can hold int data
○ float f => can hold float data

• Pointer Variable =>


holds address of variable of same data type

int *p; // p can int variable address int x; // x data variable

int *x; //x pointer variable


Pointer:
• Pointer is a variable that holds address of
variable of same data type.
*** • Pointing to an address gives value at that
address. it means, If we write * [pointer]
in front of address, it gives value at that
address.

for every pointer variable 8 bytes


memory will be allocated.

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
}

Data in memory location can be accessed using 2 ways:


• using name => printf("%d",x); //x name

• using address => [if we want to access data using address


we must use pointer concept]
printf("%d",*&x); // value at address of x will be printed

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

Arrays & Pointers:

• Array elements are stored in sequential


memory locations.
• Pointer concept is suitable to access the array
elements.

Accessing 1D-Array elements using Pointers:


C Language 9 AM Page 159
Accessing 1D-Array elements using Pointers:

x[0] x[1] x[2] x[3] x[4]


10 20 30 40 50
5000 5004 5008 5012 5016 p

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++;

Accessing 2D-Array elements:

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");
}
}

x[i] => *(x+i)

x[i][j] => *(*(x+i)+j)

*(x+i) => row address *(x+0) => 1st row address


*(x+1) => 2nd row address
*(x+i)+j => Element Address

C Language 9 AM Page 160


*(x+i) => row address *(x+0) => 1st row address
*(x+1) => 2nd row address
*(x+i)+j => Element Address
*(x+1)+0 => 2nd row 1st element address
*(*(x+i)+j) => Element *(x+1)+1 => 2nd row 2nd element address

* (*(x+1)+0) => 2nd row 1st element


*(*(x+1)+1) => 2nd row 2nd element

main()
{
int x[2][3] = { {10,20,30},{40,50,60} },*p;
int i,j;

p = &x[0][0];

printf("first element address=%d\n",p);


printf("first row address=%d\n",*(x+0));
printf("2nd row address=%d\n",*(x+1));

printf("first row first ele address=%d\n",*(x+0)+


0);
printf("first row 2nd ele address=%d\n",*(x+0)+
1);

printf("first row first ele=%d\n",*(*(x+0)+0));


printf("first row 2nd ele=%d\n",*(*(x+0)+1));

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) row address


*(x+i)+j element address
*(*(x+i)+j) element

x[i] *(x+i)
x[i][j] *(*(x+i)+j)
x[i][j][k] *(*(*(x+i)+j)+k)

*(x+i) 2D-Array Address


*(*(x+i)+j) 2D-Array Row Address
*(*(x+i)+j)+k Element Address

C Language 9 AM Page 161


*(*(x+i)+j)+k Element Address
*(*(*(x+i)+j)+k) Element

*(x+i)
*(*(x+i)+j)
*(*(*(x+i)+j)+k)
*(*(*(*(x+i)+j)+k)+l)
*(*(*(*(*(x+i)+j)+k)+l)+m)

Call By Value & Call By Reference [Address]:


[Parameter Passing Techniques]:

There are 2 parameter passing techniques. They


are:
• Call By Value
• Call By Reference [Address]

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.

Call By Reference [Address]:


• CALLing the function BY passing the REFERENCE [Address].
• In this, address of variables are passed as arguments.
• If we make any changes in called function variables, it will
applied to calling function variables. Because, called function
• is working with original values using addresses. It is not
working with copy.

void swap(int*,int*);
void swap(int *x,int *y)
{
int temp;
temp=*x;

C Language 9 AM Page 162


temp=*x;
*x=*y;
*y=temp;
}
main()
{
int a=20,b=30;
swap(&a,&b); //call by reference
printf("a=%d\tb=%d",a,b);
}

Call By Value Call By Reference

• values are passed as • addresses are passed as


arguments arguments

• If we make changes in • If we make changes in called


called function variables, function variables,
it will not be applied to it will be applied to calling
calling function variables. function variables.
Because, called function Because, called function
works with copy. not works with original values
original values. using the addresses.

• To make one change in • to make multiple changes in


calling function, use calling function, use call by
call by value. To make reference.
multiple changes in calling
function we cannot
use call by value. Because
function can return one
value only.

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
}

Dynamic Memory Allocation:

There are 2 types of memory allocations:


• Static Memory Allocation
• Dynamic memory Allocation

• Static Memory Allocation: main()

C Language 9 AM Page 163


• Dynamic memory Allocation

• Static Memory Allocation: main()


• If memory is allocated at compile time then it is {
called "Static Memory Allocation". int x,y; //static memory allocation
}
• Dynamic Memory Allocation:
• Allocating memory at run time is called "Dynamic
Memory Allocation".
• Following functions are used for Dynamic Memory
Allocation:
○ malloc()
○ realloc()
○ calloc()

○ free()

(int*)5000 (int)5.6
RAM

main()
{
int x,*p; //static mem alloc

p = (int*)malloc(50);

*p = 50; STACK HEAP


[Static] [Dynamic]
printf("%d",*p);

free(p);
}
main()
{
int x;

x=(int)7.8; //x=7
}

malloc() [Memory ALLOCation]:


• is a built in function included in "stdlib.h" &
"alloc.h".
• used to allocate the specified number of
bytes of memory at run time [at the time of
execution of coding].
• In HEAP memory area memory will be
allocated at run time.
• returns void type address.
• To hold integer, convert void type address to
integer address
To hold float, convert void type address to
float address.

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.

C Language 9 AM Page 164


int *p;

p = (int*)malloc(100);
p = (int*)realloc(p,200);

calloc() [Contiguous memory ALLOCation:

Contiguous => Continuous / Sequential

calloc(no_of_Elements, size);

calloc(5,100); //5 100 bytes


memory blocks will be created

malloc(100)

calloc(5,100)

5000 5100 5200 5300 5400


-99

calloc(3,50)

4000 4050 4100

malloc() used to allocate memory for 1 block


realloc() to expand memory which allocated by
malloc() or calloc()
calloc() used to allocate multiple memory
blocks
free() used to destroy the memory

Note:
Programmer is responsible to destroy the memory
if memory allocated dynamically. Automatic
memory management is not available in C/C++.

Array Of Pointer [Pointer Array]

int x,y[10],*a,*b[10]

*b[10] Array of Pointer [it can hold a set of addresses]

x data variable
y array data array [set of values]
a pointer variable
b pointer array [ a set of addresses]

C Language 9 AM Page 165


main()
{
int x[3] = {10,,20,30}, *p[3]; 10
20
p[0] = &x[0]; 30
p[1] = &x[1];
p[2] = &x[2];

printf("%d\n",*p[0]); //*5000 => 10


printf("%d\n",*p[1]); //*5004 => 20
printf("%d\n",*p[2]); //*5008 => 30
}

C Language 9 AM Page 166


User-Defined data types
Friday, April 1, 2022 9:48 AM

There are 3 types of data types:


Primitive / int float char
Built in /
• predefined
Derived Array String Pointer
User-Defined Structure union Enumeration

int int* int[]


float float* float[]

User-Defined Data Types:


• We can define our own data types like int,
float, char. These are called "User-Defined
data types"
• There are 3 types of user-defined data types:
○ Structure
○ Union
○ Enumeration

1234 Ravi A 678 67.8


45 678 234

int x=45; //declare define student data type


student s1; //declare

student => user-defined data type

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

In case of primitive type:


• directly we declare the variable.
• because data type is ready.

C Language 9 AM Page 167


In case of structure:
• We are defining structure means, we are defining
our own data type.
• Data type is not ready. So follow 2 steps:
○ define data type
○ declare variable for data type

Defining Structure:

Syntax:

struct struct_name
{
data_type1 var1,v2,……;
data_type2 var1,v2,……;
};

int plan 25 data

student plan 25 Ramu A 78.9


data type variable

1234 Ravi 56.78

struct student
{
int sid;
char sname[10];
float avrg;
};

We are defining structure means, we are


defining our own data type.
In the above example we are defining our
own data type "struct student".

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;

C Language 9 AM Page 168


int sid;
char sname[10];
float avrg;
};

Declaring structure variable:

struct student s1; //s1 var of struct student type

int x; //x var of int type

For s1,18 bytes memory will be allocated.

structure var size = sum of sizes of members

int x=25; //initializing int variable

Initializing structure variable: s1 => 18 bytes

sid sname
struct student s1={101,'Sai',56.78};

Printing structure elements:

printf("%d\n",s1.sid)//101
printf("%s\n",s1.sname); //Sai avrg
printf("%f",s1.avrg); //56.78

Reading structure elements:

scanf("%d",&s1.sid);
scanf("%s",s1.sname);
scanf("%f",&s1.avrg);

Program to demonstrate initializing structure:


Define a structure with the name "student"
Define id, name & avrg as members of structure
create one object of structure, initialize & print
the data:

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);
}

Program to read & print structure elements:

#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);
}

typedef [TYPE DEFinition]:


C Language 9 AM Page 170
typedef [TYPE DEFinition]:
• used to give alias name (alternative name) to
the data type.

Syntax:

typedef <data_type> <alias>;

#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:

typedef struct student


{
int id;
C Language 9 AM Page 171
int id;
char name[10];
}std; show(int a)
void show(std s) //struct as arg {
{
printf("%d\t%s\n",s.id,s.name); }
} main()
main() {
{ int x=30;
std s1={10,"Ramu"}; show(x);
}
show(s1);
}

A function can return one value only.


Using structure concept we can return multiple values
[structure elements = structure]

return s1;
//for ex, if s1 has id, name & avrg, all 3 values will be returned

typedef struct student


{
int id; int f1()
char name[10]; {
float avrg; int x=50;
}std; return x;
f1() }
{ main()
std s1={10,"Ramu",56.78}; {
return s1; int k;
} k=f1();
main() print k
{ }
std k;
k=f1();
printf("%d\t%s\t%f\n",k.id,k.name,k.avrg);
}

getchar() putchar()

char ch; putchar(ch);


C Language 9 AM Page 172
getchar() putchar()

char ch; putchar(ch);


ch=getchar();

getstd() putstd()

std s1; putstd(s1);


s1 = getstd();

Array of Structure:
• Array of Structure means STRUCTURE ARRAY.

int x; std s;
int x[10]; std s[10]; //Array of Structure

typedef struct student


{
int id;
char name[10];
}std;
main()
{
std s[10]; //array of structure
int n,i;

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);
}

C Language 9 AM Page 173


Structure of Arrays
Structure in Structure
Pointer to Structure
Union
Enumeration

Structure of Arrays:
Declaring Array as a member in structure is
called "Structure Of Array".

typedef struct student s1


{
int sid; sid sname
char sname[10];
int m[3]; //Structure of Array
}std;

std s1={101,'A',{60,50,80}}; m[0] m[1] m[2]

Define a structure student with


following members:
struct student

sid
sname
m[10]

typedef struct student


{
int sid;
char sname[10];
int m[10];
}std;
main()
{
std s[10];
int ns,i,n,j;

C Language 9 AM Page 174


printf("Enter no of students:");
scanf("%d",&n);

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");
}
}

std s[10]; //Array of structure

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

C Language 9 AM Page 175


typedef struct person
{
int id;
char name[10];
}person;
typedef struct student
{
person p; //structure in
structure
char sec;
int marks;
}std;
typedef struct employee
{
person p; //id,name
char job[10];
double sal;
}emp;
main()
{
std s1={1234,"ABCD",'A',567};
emp e1
={9999,"Srinu","Clerk",8000.00};

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;

C Language 9 AM Page 176


s1

typedef struct student


sid avrg
{
67.89
int sid; 25
float avrg;
}std; 5000 5004
main()
{ p
std s1={25,67.89},*p;
5000

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);

-> Arrow Operator / Indirect Member Access Operator


. Dot Operator / Direct Member Access Operator

-> , . Operators are used to access structure elements

Accessing Structure Elements using Pointers:

(*p).sid = p->sid [value at &sid]


(*p).avrg = p->avrg [value at &avrg]

C Language 9 AM Page 177


Files
Wednesday, April 6, 2022 10:09 AM

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

Functions used to work with files:

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>)

Different Modes to open a file:

Mode Purpose
w write
r read

C Language 9 AM Page 178


r read
a append
w+ write / read
r+ read / write
a+ append / read
wb write binary
rb read binary
w+b write /read binary
r+b read/write binary
ab append binary
a+b append/read binary

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");

=> a new file will be created in "d:" drive


"nareshit" folder with the name "xyz.txt". It will
be opened in write mode.

fopen() function returns file address

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

C Language 9 AM Page 179


fclose():
used to close opened file.

Syntax:
fclose(file_pointer)

Ex:
fclose(fp)

putc(): [prints char in file] putchar() [prints char on o/p screen]


• is a built-in function used to print char
• included in "stdio.h" header on console screen
file.
• it is used to write a char into char ch='S';
file. putchar(ch);

Program to write a char into file:

demo.txt

Program to write a char into file:

xyz.txt

S
FILE *fp;
char ch='S';
fp=fopen("xyz.txt","w");

putc(ch,fp);

fclose(fp);

C Language 9 AM Page 180


fopen("xyz.txt","w") 1st time: fopen("xyz.txt","a") 1st time:

creates new file & opens in write mode creates new file & opens in append mode

fopen("xyz.txt","w") from 2nd time fopen("xyz.txt","a") from 2nd time


onwards: onwards:

opens existing file without data opens existing file with contents
safe

WRITE mode means,


always fresh file will be opened

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

a=97, b=98 … z=122


ASCII => 0 to 255

Reading data from file:


xyz.txt

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);

Writing multiple student records


into file:

#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);
}

C Language 9 AM Page 182


}

#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");

fflush(stdin); //clers stdin file

printf("Do u want to add one


more record?[y/n]?:");
scanf("%c",&ch);

}while(ch=='y' || ch=='Y');

fclose(fp);
}

Program to read student records from file &


display on output screen:

fprintf() write any type data into file


fscanf() read data from file

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);
}

Working with Binary Files:

2 types of files:
• Text File => contains text
Ex: .txt files

• Binary File => contains 0s and 1s


Ex: .jpg files, .mp3 files, .mp4 files, .exe files

Binary File works faster than Text File

To work with binary files, we use 2 functions:

• 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

C Language 9 AM Page 184


r+b read write binary
w+b write read binary
a+b append read binary
ab append binary

student.bin

typedef struct student


{
int sid;
float avrg;
}std;
main()
{
FILE *fp;
std s1;

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);

printf("record saved in file..!


\n");

fflush(stdin);

printf("do u want to add one


more?[y/n]:");
scanf("%c",&ch);
}while(ch=='y' || ch=='Y');
C Language 9 AM Page 185
}while(ch=='y' || ch=='Y');

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()

These 2 functions are used for


random accessing.

demo.txt

computer
getc(fp)

Random Accessing:

fseek()
ftell()

These 2 functions are used for


random accessing.

fseek():
used to go to specified number of bytes from
specified position.

Syntax:
fseek(file_pointer,no_of_Bytes,from_where)

demo.txt

C Language 9 AM Page 186


fseek(file_pointer,no_of_Bytes,from_where)

demo.txt

fseek(fp,2,0); computer

0 Beginning of file SEEK_SET


1 current position SEEK_CUR
2 end of file SEEK_END

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)

C Language 9 AM Page 187


remove():
used to remove the file

Syntax:
remove(filename)

Ex:
remove("aaa.txt")

C Language 9 AM Page 188


Graphics
Saturday, April 9, 2022 9:37 AM

Dev C++ =>


• does not support to Graphics
• does not provide graphics.h, conio.h

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

Draw the shapes & display font different styles:

initgraph():
used to switch from text mode to graphics mode.

initgraph(&graphics_Drivers, &graphics_mode, BGI folder path)

int gd,gm;

gd = DETECT; //detects graphics drivers

initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");

C Language 9 AM Page 189


getmaxx() returns x-axis max value [639]
getmaxy() returns y-axis max value [479]

line():
used to draw the line.

line(x1,y1,x2,y2)

circle():
function is used to draw the circle

circle(x,y,radius)

C Language 9 AM Page 190


setfillstyle()
floddfill()

setfillstyle(pattern_style,color)

rectangle():
used to draw the rectangle

C Language 9 AM Page 191


ellipse():

ellise(x,y,starting_Angle,ending_angle,x-radius,y-radius)

ellipse(200,200,0,360,100,50)

C Language 9 AM Page 192


outtextxy() used to draw the text
settextstyle() to apply font style & size

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;

C Language 9 AM Page 193


{
double y;
int x;
};
double y;
};
struct demo d1;

union demo d1;

Differences b/w structure & union

Structure Union

"struct" keyword "union" keyword

all members have their all members share common


own memory area memory area

size of struct var = size of union var = max size


sum of sizes of members among the members

Enumeration:
• Enumeration is a user-defined data type
• "enum" keyword is used to define enumeration.
• used to define string constants with integer
equivalent values

C Language 9 AM Page 194


Ex:
conio.h graphics.h

enum colors
{
BLACK,
BLUE,
GREEN,
CYAN,
RED,
.
.
WHITE
};

MACRO used to define one string constant


enum used to define a set of string constants

Command Line Arguments:


The mechanism of passing values to main function
from MS DOS command line is called "Command
Line Arguments".

add(int x,int y) show(int x, char y[])


{ {
}
}
main()
{
add(2,3);
}

C Language 9 AM Page 195


main can take 2 arguments.
1st argument => int type
2nd argument => char pointer array type

char pointer array => holds set of strings addresses

main(int argc, char *argv[])


{

}
MS DOS command line

d:\cbatch9am>cla sai raju kumar

#include<stdio.h>
main(int argc,char *argv[])
{
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
}

C Language 9 AM Page 196

You might also like