0% found this document useful (0 votes)
139 views156 pages

C Language

The document outlines 8 chapters to cover C language basics like variables, data types, input/output, operators, control statements, functions, pointers, arrays, strings, structures, and file I/O. It provides examples of basic C programs and explanations of concepts like variables, data types, comments, input, output, arithmetic operations, relational and logical operators, and operator precedence. The first chapter focuses on variables, data types, and examples of taking input and printing output in C programs.

Uploaded by

vinod 7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views156 pages

C Language

The document outlines 8 chapters to cover C language basics like variables, data types, input/output, operators, control statements, functions, pointers, arrays, strings, structures, and file I/O. It provides examples of basic C programs and explanations of concepts like variables, data types, comments, input, output, arithmetic operations, relational and logical operators, and operator precedence. The first chapter focuses on variables, data types, and examples of taking input and printing output in C programs.

Uploaded by

vinod 7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 156

1 HOMEWORK SET

a.W r i t e a program t o calc ulate pe r ime t e r of


rectangle. Take sides, a & b, from t he us e r .

b. Take a number(n) from us e r & o ut p ut i ts


cube(n*n*n).

c. W r i t e comments for programs a &


b.
2 HOMEWORK SET

a. W r i t e a program t o p r in t t he average of 3 numbers.

b.W r i t e a program t o check if given cha r ac t e r is


digit o r no t .

c. W r i t e a program t o p r in t t he smallest number of


tw o .
3 HOMEWORK SET

a.W r i t e a program t o check if a given number


is Armstrong number o r no t .
(Search w ha t is Armstrong number)

b.W r i t e a program t o check if t he given number is


a na tur al number.
( Na tur al numbers st a rt from 1 )
4 HOMEWORK SET

a. Sear ch on w ha t a " ne st ed loop" is & p r in t


this pa tt e r n using i t .
*****
*****
*****
b. W r i t e a program t o check if a number is prime o r
no t .
c. W r i t e a program t o p r in t prime numbers in a
range.
5 HOMEWORK SET

a. W r i t e a function t o find sum of digits of a number.

b. W r i t e a function t o find square r oo t of a number.

c.W r i t e a function t o p r in t " Ho t " o r " Cold " depending


on t he t empe r a tur e us e r en t e rs .

d. Make y o ur own pow function.


6 HOMEWORK SET

a.W r i t e a program in C t o find t he maximum


number between tw o numbers using a pointer.

b.W r i t e a program in C t o p r in t t he elements of


an a rr a y in r e v e rs e o r de r .

c.W r i t e a program in C t o p r in t all t he le tt e rs in


english alphabet using a poin ter.
7 HOMEWORK SET

a.In an a rr a y of numbers, find how many times does


a number ' x ' occ urs .

b.W r i t e a program t o p r in t t he largest number in


an a rr a y .

c.W r i t e a program t o in s e rt an element a t t he end


of an a rr a y .
8 HOMEWORK SET

a.W r i t e a program t o con v e rt all lowercase vowels


t o uppercase in a string.

b.W r i t e a program t o p r in t t he highest frequency


cha r ac t e r in a string.

c. W r i t e a program t o remove blank spaces in a


string.

d.W r i t e a program t o replace lowercase le tt e rs


w i t h uppercase & vice v ers a in a string.
9 HOMEWORK SET

Make a system t ha t can st o r e information of all


stu den ts , t eache rs & staff of y o ur college in t he
form of stru c tur e s .

Yo u can also make this into a C P r ojec t w i t h


o t he r functionalities like cgpa calculation of
stu den ts , storing attendance e t c .
10 HOMEWORK SET

a. W r i t e a program t o read a string from a file


& o ut p ut t o t he us e r .

a. Replace t he da t a in file of Q(a) w i t h t he number


of vowels in t he string.

c. Fo r ma t t he information of 5 stu den ts (name,


marks, cgpa, course) in a table like stru c tur e in a
file.
11 HOMEWORK SET

a. Sea rch abo ut w ha t is a 'dangling poin t e r ' in C .

b.Allocate memory for 500 integers using calloc &


t hen st o r e fi rst 500 na tur al numbers in t ha t space.

c. Sear ch abo ut w ha t is ' memo ry leak' in C .

d. Sear ch & find o ut which is be tt e r malloc( ) o r


calloc ( ).
Variables
Variable is the name of a
memory location which stores
some data.

Memory

a b
25 S
Variables
R u le s

a. Variables are case sensitive

b. 1st character is alphabet or


'_'

c. no comma/blank s pace

d. No other symbol other than


' _'
Variables
Data Ty pes
Constants
Val u e s that don't
change(fixed)

Types

Integer Char acter


Constants Real
Constants Con st an ts
1, 2, 3, ' a', ' b',
0 ' A', '#',
1.0, 2.0,
, -1, -2 '&'
3.14, -
24
K eywor ds
Reserved words that have
special meaning to the compiler

32 Ke yw o r d s in C
K eywor ds
auto double int stru ct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned


Program
Structure
# incl u de < s t dio . h >

in t main () {
prin t f (" Hello World ");
re t u rn 0 ;
}
Comments
Lines that are not part of
program

Single M u ltiple
Line Line

/*
/
*
/
/
Output

printf(" Hello Wo r ld
");

new line
printf(" kuch bhi \
n ");
Output
CASES
1. integers
pr intf(" age is % d " , age);

2. real numbers
printf(" value of pi i s % f ", pi);

3. characters
printf(" star looks like this % c ",
star);
Inpu
t
scanf(" % d ",
&age);
Compilation
A computer program that translates C
code into machine code

a.exe (windows)
Hello.c C Compiler
a.out (linux &
mac)
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Variables, Data Types + Input/Output


(Chapter 1)

1. First Program
#include<stdio.h>

int main()
{ printf("Hello
World"); return 0;
}

2. Variables & Data Types + Constants & Keywords


#include<stdio.h>

int main()
{ int
number;
int age;
int price;
return 0;
}
#include<stdio.h>

int main() {
int age = 22;
float pi = 3.14;
char percentage = '%';
return 0;
}

3. Comments
#include<stdio.h>
//This program prints Hello World
int main() {
printf("Hello World");
return 0;
}

4. Output
#include<stdio.h>

int main() {
int age = 22;
float pi = 3.14;
char percentage
= '%';

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


printf("age is %f", pi);
printf("age is %c", percentage);
return 0;
}

5. Input (Sum of 2 numbers)


#include<stdio.h>

int main() {
int a,
b;

printf("enter a \n");
scanf("%d", &a);

printf("enter b \n");
scanf("%d", &b);

printf("sum of a & b is : %d \n", a+b);

return 0;
}

6. Practice Qs 1 (Area of Square)


#include<stdio.h>
//area of square
int main() {
int side;
scanf("%d", &side);
printf("%d", side * side);
return 0;
}

7. Practice Qs 2 (Area of Circle)


#include<stdio.h>
//area of square
int main() {
float radius;
scanf("%f", &radius);
printf("%f", 3.14 * radius * radius);
return 0;
}
In stru c t ion s
These a r e st a t emen ts in a
Program

Types

Type Con tr ol
Declaration A r i t hme t ic Instru ct ions
In stru c t ion s Instru ct ions
In stru c t ion s
Type Declaration Declare v a r before using
In stru c t ion s it
VALID INVALID
in t a = in t a =
22 ; in t b 22 ; in t b
= a; = a;
in t c = b + in t c = b +
1 ; int d = 1 , 2 ; int d = 2 ,
e ;
in t a,b,c; e;
in t a,b,c = 1 ;
a=b=c=
1;
A r i t hme t ic In stru c t ion s

a+
b
Oper and 1 Oper and 2

Oper at or

NOTE - single variable on t he


LHS
A r i t hme t ic In stru c t ion s
VALID INVALID
a=b+ b+c=
c a

a=b* a = bc
c a=b a=
/ c b ^c

NOTE - pow(x,y) for x t o t he pow er


y
A r i t hme t ic In stru c t ion s
Mod u la r Ope r a t o r %
Re tur n s remainder for in t

3%2=1

-3 % 2 = -1
A r i t hme t ic In stru c t ion s
Type
Conversion
int
in t op in t

int op float float

float op float float


A r i t hme t ic In stru c t ion s
Ope r a t o r Precedence

*, / , x = 4 + 9 * 10
%

+, -

= x=4*3/ 6*2
A r i t hme t ic In stru c t ion s
Associativity (for same
precedence)

Lef t t o Right

x=4*3/ 6*2
In stru c t ion s
Con tr ol In stru c t ion s
Used t o determine flow of
program
a. Sequence Con tr ol

b. Decision Con tr ol

c. Loop Cont r ol

d. Case Con tr ol
Oper at or
s
a. A r i t hme t ic Ope r a t o rs

b. Relational Ope r a t o rs

c. Logical Ope r a t o rs

d. Bi tw i s e Ope r a t o rs

e. Assignment Ope r a t o rs

f. Te r na ry Ope r a t o r
Oper at or
sRelational Ope r a t o rs

==

>, >=

<, <=

!=
Oper at or
sLogical Ope r a t o rs

&& AND

|| OR

! NOT
Ope r a t o r Precendence
P r io r i ty Oper at or
1 !

2 *, / ,
%
3 +, -

4 <, <=, >,


>=
5 ==, !=

6 &&

7 ||

8 =
Oper at or
sAssignment Ope r a t o rs

=
+=

-=

*=

/=

%=
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Instructions & Operators


(Chapter 2)

1. Type Declaration Instructions


#include<stdio.h>

int main() {
int age = 22;
int oldAge = age;
int newAge = oldAge + 2;
printf("new age is : %d", newAge);

int rupee = 1, dollar;


dollar = 74;

/*
order of declaration is important - Wrong Declaration Order
float pi = 3.14;
float area = pi * rad * rad;
float rad = 3;
*/
// valid declaration
int age1, age2, age3;
age1 = age2 = age3 = 22;

//invalid
//int a1 = a2 = a3 = 22;

return 0;
}

2. Arithmetic Instructions
#include<stdio.h>

int main() {
int a = 1, b = 2, c = 3;
//valid
a = b + c;

//invalid
// b + c = a;

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


printf("%d \n", -3 % 2);
return 0;
}

> Type Conversion


#include<stdio.h>

int main() {
printf("sum of 2 & 3 : %d", 2 + 3);
printf("sum of 2.0 & 3 : %f", 2.0 + 3);
printf("sum of 2.0 & 3.0 : %f", 2.0 + 3.0);
return 0;
}

> Associativity
#include<stdio.h>

int main() {
printf(" Output : %d", 5+2/2*3);
return 0;
}

3. Relational Operator
#include<stdio.h>

int main() {
printf("%d \n", 4==4);

printf("%d \n", 4<3);


printf("%d \n", 3<4);
printf("%d \n", 4<4);
printf("%d \n", 4<=4);

printf("%d \n", 4>3);


printf("%d \n", 3>4);
printf("%d \n", 4>4);
printf("%d \n", 4>=4);

printf("%d \n", 4!=4);


printf("%d \n", 3!=4);
return 0;
}

4. Logical Operator
#include<stdio.h>

int main() {
printf("%d \n", 3<4 && 3<5);
printf("%d \n", 3<4 && 5<4);

printf("%d \n", 3<4 && 5<4);


printf("%d \n", 3>4 && 5>4);
printf("%d \n", 3<4 && 3<5);

printf("%d \n", !(3<4 && 3<5));


printf("%d \n", !(4<3 || 5<3));
return 0;
}
5. Assignment Operator
# include <stdio.h>

int main()
{ int a =
10; a +=
10;
printf("a+10 = %d \n", a); a
-= 10;
printf("a-10 = %d \n", a); a
*= 10;
printf("a*10 = %d \n", a); a
/= 10;
printf("a/10 = %d \n", a); a
%= 10;
printf("a%c10 = %d \n", '%', a);
return 0;
}
Condi t ional S t a t emen ts

T y pe s

if - S w i tch
el s e
if -
el s e
if ( Condi t ion ) {
//do s ome t hing if TRUE
}
el s e {
//do s ome t hing if
FALSE
}

Ele i s op t ional block

can al s o w o r k w i t ho ut
{}
el s e if

if ( Condi t ion 1 ) {
//do s ome t hing if TRUE
}
el s e if ( Condi t ion 2 ) {
//do s ome t hing if 1st i s FALSE & 2 nd i s
TRUE
}
Condi t ional Ope r a t o rs
Te r na ry

Condi t ion ? doSome t hing if TRUE : doSome t hing if


FALSE ;

giv e 1 & 0
ca s es
Condi t ional Ope r a t o rs
sw i t ch

sw i tch (n u mbe r ) {

ca s e C 1 : //do
s ome t hing
b r eak ;
ca s e C 2 : //do
s ome t hing
b r eak ;
defa u l t : //do
s ome t hing
Condi t ional Ope r a t o rs
sw i t ch P r ope rt ie s

a. Ca s e s can be in an y
o r de r

b . Ne st ed sw i t ch ( sw i t ch in s ide sw i t ch ) a r e
allo w ed
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Conditional Statements
(Chapter 3)

1. If-else
#include<stdio.h>

int main() {
int age = 19;
if(age >= 18) {
printf("you
are an
adult");
}
else {
printf("you
are not an
adult");
}
return
> check 0;number is odd or even
if a
}
#include<stdio.h>

int main()
{ int
number;
scanf("%d", &number);

if(number % 2 == 0) {
printf("even");
}
else {
printf("odd");
}
return 0;
}

> Use of else if


#include<stdio.h>

int main() {
int age;
printf("Enter age : ");
scanf("%d", &age);

if(age < 12)


{ printf("child
");
}
else if(age < 18)
{ printf("teenager
");
}
else {
printf("adult");
}
return 0;
2. Ternary
} Operator
#include<stdio.h>

int main() {
int age;
printf("Enter age : ");
scanf("%d", &age);

age > 18 ? printf("adult \n") : printf("not adult \n");

int number = 7;
int luckyNumber = 7;

number == luckyNumber ? printf("you are lucky \n") : printf("you are


not lucky \n");

return 0;
}

3. Switch (integer)
#include<stdio.h>
#include<math.h>

int main()
{ int day =
5;
switch(day) {
case 1 :
printf("
monday \
n");
br
e
a
k
;
case 2 : printf("tuesday \n");
break;
case 3 : printf("wednesday \n");
break;
case 4 : printf("thursday \n");
break;
case 5 : printf("friday \n");
break;
case 6 : printf("saturday \n");
break;
case 7 :
4. Switch printf("sunday \n");
(character)
#include<stdio.h>
break;
#include<math.h>
}
return 0;
int
} main() {
char day = 'f';
switch(day) {
case 'm' : printf("monday \n");
break;
case 't' : printf("tuesday \n");
break;
case 'w' : printf("wednesday \n");
break;
case 'T' : printf("thursday \n");
break;
case 'f' : printf("friday \n");
break;
case 's' : printf("saturday \n");
break;
case 'S' : printf("sunday \n");
break;
}
return 0;
}
Loop Con tr ol
In stru c t ion s
To r epea t s ome pa rts of t he
p r og r am

T y pe s

fo r do w hile
w hile
fo r Loop

fo r ( ini t iali s a t ion ; condi t ion ; u pda t ion )


{
//do s ome t hing

}
Special Thing s

- Inc r emen t Ope r a t o r

- Dec r emen t Ope r a t o r

- Loop co u n t e r can be
floa t o r e v en cha r ac t e r

- Infini te Loop
w hile Loop

w hile ( condi t ion )


{
//do s ome t hing

}
do w hile
Loop
do
{
//do s ome t hing

}
w hile (condi tion );
b r eak S t a t emen t

e x i t t he
loop
con t in u e S t a t emen t

s kip to ne xt
i t e r a t ion
Ne st ed Loop s

fo r ( .. ) {
fo r ( .. )
{

}
}
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Loop Control Statements


(Chapter 4)

1. Syntax of 3 Loops
# include <stdio.h>

int main () {
//for loop
for(int i=1; i<=100; i++) {
printf("%d\n", i);
}

//while loop int


i=1;
while(i<=100) {
printf("%d\n", i); i+
+;
}

//do while loop i


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

return 0;
}
Function s

block of code that performs particular


task

Take Do Retur n
Ar gu men Wo r k
t Re su l t

it can be us ed multiple
times increase code
reusabili ty
Syntax 1
Function
Prototype

void printHello( );

> Tell the


Syntax 2
Function
Definition

void printHello() {
pr intf(" Hello");
}

> Do the
Syntax 3

Function Call
int main() {
pr intHello( )
; return 0 ;
}

> U s e the
P r operties

- Execution al w a ys st a rts from main

- A function gets called directly or indirectly from


main

- Ther e can be mu ltiple fu nctions in a


pr ogr am
Function
Types

Library U s er -
defined
fu nction
Special declar ed & defined
fu nctions by programmer
inbuilt in C
s canf( ), pr intf(
)
Passing
Arguments
fu nctions can take v alu e & giv e s ome
v alu e
par ameter r etur n v al ue
Passing
Arguments
void printHello( );

void printTable(int

n); int sum(int a, int

b);
Passing
Arguments
fu nctions can take v alu e & giv e s ome
v alu e
par ameter r etur n v al ue
Argument v/s
Parameter
v al u e s that v al u e s in
are passed in function
function call declaration &
definition

us ed to us ed to
send receive
v al ue v al ue

actual formal
par ameter par ameters
NOTE

a. Function can only retur n one val ue at a time

b.Changes to parameters in function don't change the v al u e s

in calling function.
Beca us e a copy of argument i s passed to the function
Recurs io
n
When a function calls itself, i t ' s called
recursion
P r operties of
Recurs ion
a.Anything that can be done with Iteration, can be done
with recursion and vice-versa.

b. Recursion can sometimes give the most simple solution.

c. Ba s e Ca s e i s the condition which st op s recursion.

d. Iteration has infinite loop & Recursion has stack overflow


C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Functions & Recursion


(Chapter 5)

1. Function to print Hello


#include<stdio.h>

//function declaration/prototype
void printHello();

int main() {
//function call
printHello();
return 0;
}

//function
definition void
printHello() {
printf("Hello!\
n");
}
2. Function to calculate square of a number
# include <stdio.h>
//function to calculate square of a number
int calcSquare(int n);

int main() {
int n;
printf("ente
r n : ");
scanf("%d",
&n);
printf("square is : %d", calcSquare(n));
return 0;
}

int calcSquare(int n) {
return n * n;
}

3. Function to calculate n factorial (using recursion)

# include <stdio.h>
//function to print factorial of n
int factorial(int n);

int main() {
int n;
printf("ente
r n : ");
scanf("%d",
&n);
printf("factorial is : %d", factorial(n));
return 0;
}

int factorial(int n) {
if(n == 0) {
return 1;
}
int factnm1 = factorial(n-1);
int factn = factnm1 * n;
return factn;
}
Poin ter
s
A va riable t ha t stores t he
memo ry address of ano t he r
va r iable
M emo ry

age p tr

22 2010

2010 2013
Sy n t a normal
x variable
nenavav
2023-02-12 19:52:47
--------------------------------------------
normal variable

in t age = 22 ;

in t *p tr =

& age ; in t _ age

= * p tr ;
M emo ry

age p tr

22 2010

2010 2013
Decla ring Pointers

in t * p tr ;

cha r * p tr ;

floa t

* p tr ;
Fo r ma t Specifie r

p r in t f ("% p ", &age);

p r in t f ("% p ", p tr );

p r in t f ("% p ", & p tr );


Pointer t o
Pointer
A va riable t ha t stores t he
memo ry address of ano t he r
poin t e r
M emo ry

age pp tr p tr

22 2013 2010

2010 2012 2013


Pointer t o
Pointer
Syntax

in t ** pp tr ;

cha r ** pp tr ;

floa t

** pp tr ;
Pointers in F u nc t ion Call

Call b y call b y
Value Refer ence

We pass value We pass address


of v ariable as of v ariable as
argumen t argument
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Pointers
(Chapter 6)

1. Syntax
#include<stdio.h>

int main() {
int age = 22;
int *ptr = &age;
int _age =
*ptr;
printf("%d\n",
_age);

//address
printf("%p\n", &age);
printf("%p\n", ptr);
printf("%p\n",
&ptr);

//data printf("%d\
n", age);
printf("%d\n", *ptr);
printf("%d\n", *(&age));
return 0;
}

2. Pointers in Function call


# include <stdio.h>

void square(int n);


void _square(int* n);

int main() {
int number = 4;

//call by value

square(number);
printf("n is :
%d\n", number);

//call by
reference
_square(&number
);
printf("n is : %d\n", number);
return 0;
}

void square(int n) {
n = n * n;
printf("square is :
%d\n", n);
}

void _square(int* n)
{
3. Swap 2 numbers
*ninclude
# = *n * <stdio.h>
*n;
printf("square is :
%d\n", *n);
void swap(int a, int b);
}
void _swap(int* a, int *b);

int main() {
int x = 3, y = 5;

//call by value
swap(x, y);
printf("x = %d & y = %d\n", x, y);

//call by reference
_swap(&x, &y);
printf("x = %d & y = %d\n", x, y);
return 0;
}

void swap(int a, int b) {


int t = a;
a = b; b
= a;
}

void _swap(int* a, int* b) {


int t = *a;
*a = *b;
*b = *a;
}
Ar r ays

Collection of similar dat a ty pe s st o r ed


a t contiguous memory locations
S y nt a x
in t marks[3];

char name[10];

float price[2];
Input & Out put
scanf(" % d" ,
&mar ks[0 ]);

pr int f(" % d" ,


mar ks[0 ]);
Inititalization of
A rr a y
int mar ks[ ] = {97 , 98 , 89 };

int mar ks[ 3 ] = {97 , 98 ,


89 };

Memo ry
Reserved :
Poin t e r A r i t hme t ic
Poin t e r can be
incremented &
decremented

CASE 1
Poin t e r A r i t hme t ic
CASE 2

CASE 3
Poin t e r A r i t hme t ic

- We can also su b tr ac t one pointer from


ano t her

- We can also compar e 2


point ers
A rr a y is a
Poin t e r
int * pt r =
&ar r [0 ];

int * pt r =
ar r ;
Traverse an
A rr a y
in t aadhar[10];

int * pt r =
&aadhar [0 ];
A rr a ys as F u nc t ion
Argument
//Function Declaration
void p r in t Numbers (int a rr [ ], in t
n)
OR
void p r in t Numbers (int * a rr , in t
n)

//Function Call
p r in t N umbe rs (a rr ,
n);
Multidimensional A rr a ys
2 D A rr a ys
int ar r [ ][ ] = { {1 , 2 }, {3 , 4 } };
//Declar e

//
Access

a rr [ 0 ][ 0 ]
a rr [ 0 ][ 1 ]
a rr [ 1 ][ 0 ]
a rr [ 1 ][ 1 ]
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Arrays
(Chapter 7)

1. Syntax
# include <stdio.h>

int main() {
int marks[3];
printf("physics : ");
scanf("%d",
&marks[0]);

printf("chem : ");
scanf("%d",
&marks[1]);

printf("math : ");
scanf("%d",
&marks[2]);

printf("physics = %d, ", marks[0]); //physics


printf("chem = %d, ", marks[1]); //chem
printf("math = %d \n", marks[2]); //math
return 0;
}

2. Pointer Arithmetic
# include <stdio.h>

int main() {

int age = 22;


int *ptr = &age;

int _age = 25;


int *_ptr =
&_age;

printf("%u\n", ptr);
ptr++; printf("%u\
n", ptr); ptr--;
printf("%u\n", ptr);
ptr = ptr - _ptr;
printf("%u\n", ptr);

ptr = &_age;
printf("%d\n", ptr
== _ptr);

return 0;
}

3. Accessing an Array
# include <stdio.h>

void printNumbers(int *arr, int n);


void _printNumbers(int arr[], int n);

int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
printNumbers(arr, 6);
printNumbers(arr, 6);
return 0;
}
void printNumbers(int *arr, int n) {
for(int i=0; i<n; i++) {
printf("%d : %d\n", i, arr[i]);
}
}

void _printNumbers(int arr[], int n) {


for(int i=0; i<n; i++) {
printf("%d : %d\n", i, arr[i]);
}
}
Strings

A character array terminated by a ' \ 0 ' (null


character)

null character denotes string

termination EXAMPLE
char name[ ] = {' S ', ' H ', ' R ', ' A ', ' D ', ' H ', ' A ',' \0 '};

char cla ss [ ] = {' A ', ' P ', ' N ', ' A ', ' ', ' C ', ' O ', ' L ', ' L ', ' E ', ' G ', ' E ', ' \
0 '};
Initialising
Strings
char name[ ] = {' S ', ' H ', ' R ', ' A ', ' D ', ' H ', ' A ',' \
0 '};

char name[ ] = " SHRADHA ";

char cla ss [ ] = {' A ', ' P ', ' N ', ' A ', ' ', ' C ', ' O ', ' L ', ' L ', ' E ', ' G ', ' E ', ' \
0 '};

char cla ss [ ] = " APNA COLLEGE ";


Wha t Happens in
Memo ry ?
char name[ ] = {' S ', ' H ', ' R ', ' A ', ' D ', ' H ', ' A ',' \
0 '};

char name[ ] = " SHRADHA ";

nam
e
S H R A D H A \0

2000 2001 2002 2003 2004 2005 2006 2007


String Format
Specifier
"% s "

char name[ ] =
" Sh r adha "; printf("%s",
name);
IMPORTANT
scanf( ) cannot input multi-word strings with
spaces

Here,
gets( ) & puts ( ) come into picture
String
Functions Dangerous
gets(str) & puts(str)
Outdated
input a string
output a
(even
string
mu ltiwor d)

fgets( str , n,
file)
stops when n - 1
chars input or
new line is
entered
String using
Pointers
char *str = " Hello Wo r ld ";
Store string in memory & the assigned
address is stored in the char pointer
' str '

char *str = " Hello // can be


Wo r ld "; reinitialized

char str [ ] = " Hello


Wo r ld ";
// canno t be reinitialized
Standard Library
Functions
<string.h>

1 strlen(str)
count number of characters excluding
'\0'
Standard Library
Functions
<string.h>

2 strcpy(newStr, oldStr)
copies value of old string to new
string
Standard Library
Functions
<string.h>

3 strcat(firstStr, secStr)
concatenates first string with second
string

firstStr should be
large

enough
Standard Library
Functions
<string.h>

4 strcpm(firstStr, secStr)
Compares 2 strings & returns a
value

0 -> string equal

positive -> first > second (ASCII)

negative -> first < second

(ASCII)
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Strings
(Chapter 8)

1. Strings
# include <stdio.h>
# include <string.h>

int main() {
//declaration
char name[] = "Shradha Khapra";
char course[] = {'a','p', 'n', 'a', ' ', 'c', 'o', 'l', 'l', 'e', 'g',
'e', '\0'};

//printing string
for(int i=0; name[i] != '\0'; i++) {
printf("%c", name[i]);
}
printf("\n");

//printing string with pointer


for(char *ptr=name; *ptr != '\0'; ptr++) {
printf("%c", *ptr);
}
printf("\n");

//printing using format specifier


printf("%s\n", name);

//input a string
char firstName[40];
printf("enter first name : ");
scanf("%s", firstName);
printf("you first name is %s\n", firstName);
char fullName[40];
printf("enter full name : ");
scanf("%s", fullName);
printf("you first name is %s\
n", fullName);

// gets & puts


char fullName[40];
printf("enter full name : ");
fgets(fullName, 40, stdin);
puts(fullName);

//Library Functions
char name[] = "Shradha";
int length = strlen(name);
printf("the length of name
: %d\n", length);

char oldVal[] = "oldValue";


char newVal[50];
strcpy(newVal, oldVal);
puts(newVal);

char firstStr[50] = "Hello ";


char secStr[] = "World";
strcat(firstStr, secStr);
puts(firstStr);

char str1[] = "Apple";


char str2[] = "Banana";
printf("%d\n",
strcmp(str1, str2));

//enter String using %c


printf("enter string : ");
char str[100];
char ch;
int i = 0;

while(ch != '\
n') {
scanf("%c", &ch);
str[i] = ch;
i++;
}
str[i] = '\0';
puts(str);

return 0;
}

> Some more Qs


# include <stdio.h>
# include <string.h>

// void printString(char arr[]);


// int countLength(char arr[]);
// void salting(char password[]);
// void slice(char str[], int n, int m);

//int countVowels(char str[]);

void checkChar(char str[], char ch);

int main() {
char str[] = "ApnaCollege";
char ch = 'x';
checkChar(str, ch);
}

void checkChar(char str[], char ch) {


for(int i=0; str[i] != '\0'; i++) {
if(str[i] == ch) {
printf("character is present!");
return;
}
}
printf("character is NOT present:(");
}

// int countVowels(char str[]) {


// int count = 0;

// for(int i=0; str[i] != '\0'; i++) {


// if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
// str[i] == 'o' || str[i] == 'u') {
// count++;
// }
// }
// return count;
// }

// void slice(char str[], int n, int m) { // n & m are valid value


// char newStr[100];
// int j = 0;
// for(int i=n; i<=m; i++, j++) {
// newStr[j] = str[i];
// }
// newStr[j] = '\0';
// puts(newStr);
// }

// void salting(char password[]) {


// char salt[] = "123";
// char newPass[200];

// strcpy(newPass, password); // newPass = "test"


// strcat(newPass, salt); // newPass = "test" + "123";
// puts(newPass);
// }

// int countLength(char arr[]) {


// int count = 0;
// for(int i=0; arr[i]!='\0'; i++) {
// count++;
// }
// return count-1;
// }

// void printString(char arr[]) {


// for(int i=0; arr[i] != '\0' ;i++) {
// printf("%c", arr[i]);
// }
// printf("\n");
// }
S tru c tur e s

a collection of values of different da ta


ty pe s

EXAMPLE

Fo r a stu den t st o r e t he
following : name (String)

r oll no (Int eger )

cgpa (Float )
S y nt a x

stru c t stu den t { stru c t stu den t s1 ;

char name [ 100 ]; s1.cgpa = 7 . 5 ;

in t r oll ;

float cgpa;

};
S y nt a x

stru c t stu den t {

char name [ 100 ];

in t r oll ;

float cgpa;

}
S tru c tur e s in Memo ry nam r oll cgp
e a

stru c t stu den t {

char name [ 100 ]; 2010 2110 2114

in t r oll ;

float cgpa;

stru c tur e s a r e st ored in contiguous memory


locations
Benefits of using
S tru c tur e s
- Saves us from creating too many
variables

- Good data management/organization


Ar r ay of
S t r u ct ur es
stru c t stu den t ECE [ 100 ];

stru c t stu den t COE [ 100 ];

stru c t stu den t IT [ 100 ];

ACCESS
IT [ 0 ]. r oll = 200 ;
IT[0].cgpa =
7.6;
Initializing S tru c tur e s

stru c t stu den t s1 = { " s h r adha ", 1664 ,


7 . 9 };

stru c t stu den t s2 = { " r aja t ", 1552 ,

8 . 3 }; stru c t stu den t s3 = { 0 };


Poin t ers t o S tru c tur e s

stru c t stu den t s1 ;

stru c t stu den t * p tr ;

p tr =& s1 ;
A rr o w Ope r a t o r

(*ptr).code pt r -> code


Passing stru c tur e t o
function
// F u nc t ion P r o t o ty pe
void p r in t Info ( stru c t stu den t
s1);
typedef Ke yw o r d

used t o c r ea t e alias for da t a


ty pe s

coe
st u dent 1 ;
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Structures
(Chapter 9)

1. Structures
# include <stdio.h>
# include <string.h>

struct student
{ char
name[100]; int
roll;
float cgpa;
};

typedef struct ComputerEngineeringStudent{


int roll;
float cgpa; char
name[100];
} coe;

void printInfo(struct student s1);

int main() {
struct student s1;
// s1.name = "Shradha"; // not a modifiable value
strcpy(s1.name,"Shradha");
s1.roll = 64;
s1.cgpa = 9.2;

printf("student info : \n");


printf("name = %s\n", s1.name);
printf("roll no = %d\n", s1.roll);
printf("cgpa = %f\n", s1.cgpa);

//array of structures
struct student IT[60];
struct student COE[60];
struct student
ECE[60];

//declaration
struct student s2 = {"Rajat", 1552, 8.6};
struct student s3 = {0};

printf("roll no of s2 = %d\n", s2.roll);


printf("roll no of s3 = %d\n",
s3.roll);

//pointer to structure
struct student *ptr = &s1;
printf("student.name = %s\n", (*ptr).name);
printf("student.roll = %d\n",
(*ptr).roll); printf("student.cgpa = %f\
n", (*ptr).cgpa);

//arrow operator
printf("student->name = %s\n", ptr->name);
printf("student->roll = %d\n", ptr-
>roll); printf("student->cgpa = %f\n",
ptr->cgpa);

//Passing structure to function


printInfo(s1);

//typedef keyword
coe student1;
student1.roll =
1664;
student1.cgpa =
6.7;
strcpy(student1.name, "sudhir");

return 0;
}

void printInfo(struct student s1)


{ printf("student info : \n");
printf("name = %s\n", s1.name);
printf("roll no = %d\n", s1.roll);
printf("cgpa = %f\n", s1.cgpa);

//change
s1.roll = 1660; //but it won't be
reflected to the main function
//as structures are
passed by value
}
> Some more Qs
# include <stdio.h>
# include <string.h>

//user defined
typedef struct student {
int roll;
float cgpa; char
name[100];
} stu ;

typedef struct computerengineeringstudent {


int roll;
float cgpa; char
name[100];
} coe;

struct address {
int houseNo;
int block;
char city[100];
char state[100];
};

struct vector {
int x;
int y;
};

void calcSum(struct vector v1, struct vector v2, struct vector sum);

struct complex {
int real;
int img;
};

typedef struct BankAccount {


int accountNo;
char name[100];
} acc ;

int main() {
acc acc1 = {123, "shradha"};
acc acc2 = {124, "rajat"};
acc acc3 = {125, "sudhir"};

printf("acc no = %d", acc1.accountNo);


printf("name = %s", acc1.name);
return 0;
}

void calcSum(struct vector v1, struct vector v2, struct vector sum) {
sum.x = v1.x + v2.x;
sum.y = v1.y + v2.y;

printf("sum of x is : %d\n", sum.x);


printf("sum of y is : %d\n", sum.y);
}
File IO

RAM Har d
Dis k
File IO

FILE - container in a storage device to store


data

- RAM i s volatile

- Contents are lost when program


terminates

- File s are us ed to pe rs i st the data


Oper ation on
F iles
Create a File

Open a File

Close a File

Read from a

File

W r i t e in a File
Ty pes of
F iles
Text File s Bina ry File s

textual binary data


data
. txt , . c . e x e , . mp 3 , .jpg
File
Pointer
FILE i s a (hidden)structure that needs to be created for opening a
file A FILE ptr that points to this stru c tur e & i s us ed to
acce ss the file.

FILE * fp tr ;
Opening a
File
FILE * fp tr ;

fptr = fopen("filename", mode);

Closing a
File
fclose(fptr);
File Opening
Modes
"r" open to
read
" r b" open to read in
binary
"w" open to
write
" w b" open to write in
binary
"a" open to
append
BEST
Practice
Check if a file e x i sts before reading from
it.
Reading from a
file

char ch ;

fscanf(fptr, "% c ", & ch );


Writing to a
file

char ch = ' A ';

fprintf(fptr, "% c ", ch);


Read & W r i t e a
char
fgetc(fptr)

fputc( ' A ', fptr)


EOF (End Of
File)
fgetc r e tur n s EOF to show that the file has
ended
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

File I/O
(Chapter 10)

# include <stdio.h>

int main()
{ FILE
*fptr;
//Reading a file
char ch;
fptr = fopen("Test.txt", "r");
if(fptr == NULL) {
printf("doesn't exist!\n");
} else {
fscanf(fptr, "%c", &ch);
printf("character in file is : %c\n", ch);
fscanf(fptr, "%c", &ch);
printf("character in file is : %c\n", ch);
fclose(fptr);
}

//Writing in a file
ch = 'M';
fptr =
fopen("NewFile.txt"
, "w");
fprintf(fptr, "%cANGO", ch);
fclose(fptr);

//fgets
fptr = fopen("NewFile.txt",
"r");
printf("character in file is : %c\n", fgetc(fptr));
printf("character in file is : %c\n",
fgetc(fptr)); printf("character in file is : %c\
n", fgetc(fptr)); printf("character in file is :
%c\n", fgetc(fptr)); printf("character in file
is : %c\n", fgetc(fptr)); fclose(fptr);

//fputc
fptr = fopen("NewFile.txt", "w");
fputc('a', fptr);
fputc('p', fptr);
fputc('p', fptr);
fputc('l', fptr);
fputc('e', fptr);
fclose(fptr);

//read the full


file (EOF)
fptr = fopen("NewFile.txt", "r");
ch = fgetc(fptr);
while(ch != EOF)
{ printf("%c",
ch); ch =
fgetc(fptr);
}
printf("\n");
fclose(fptr);

return 0;
}
D y namic Memo ry Alloca t ion

I t is a way t o alloca t e memo ry t o a data structure


d ur ing t he ru n t ime .

We need some f u nc t ion s t o alloca te


& f ree memo ry d y namicall y .
F u nc tion s fo r
DMA
a. malloc ( )

b. calloc ( )

c. free( )

d. realloc ( )
malloc ( )
memo ry alloca t ion

takes n u mbe r of bytes t o be


alloca t ed & returns a poin t e r of ty pe
v oid

p tr = (*int) malloc ( 5 * sizeof(int));


calloc ( )
con t in u o us alloca t ion

init ializ es w i t h 0

p tr = (*int) calloc ( 5 , sizeof(int));


free( )
We use i t t o f r ee memo ry t ha t is
alloca t ed using malloc & calloc

free(ptr );
realloc ( )
r ealloca t e (increase o r decrease)
memo ry using t he same poin t e r & size.

p tr = r ealloc ( p tr , newSize);
C Language Tutorial
(Basic to Advanced)

Topics to be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic
Memory Allocation

Dynamic Memory Allocation


(Chapter 11)

# include <stdio.h>
# include <stdlib.h>
//Dynamic Memory Allocation

int main() {
//sizeof function printf("%d\
n", sizeof(int)); printf("%d\
n", sizeof(float));
printf("%d\n", sizeof(char));

//malloc
// int *ptr;
// ptr = (int *) malloc(5 *
sizeof(int));

// for(int i=0; i<5; i++) {


// scanf("%d",
&ptr[i]);
// }

// for(int i=0; i<5; i++) {


// printf("number %d =
%d\n", i+1, ptr[i]);
// }

//calloc
int *ptr = (int *) calloc(5, sizeof(int));

for(int i=0; i<5; i++) {


printf("number %d = %d\n", i+1, ptr[i]);
}

//free
free(ptr);

return 0;
}

You might also like