0% found this document useful (0 votes)
17 views152 pages

C Complete Notes

The document provides an introduction to C programming, detailing its history, uses, and fundamental concepts such as variables, constants, and keywords. It outlines the basic structure of a C program, including the importance of the main function, comments, and the compilation process. Additionally, it covers various programming instructions, operators, and control structures necessary for decision-making in C.

Uploaded by

Bibin K Bino
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views152 pages

C Complete Notes

The document provides an introduction to C programming, detailing its history, uses, and fundamental concepts such as variables, constants, and keywords. It outlines the basic structure of a C program, including the importance of the main function, comments, and the compilation process. Additionally, it covers various programming instructions, operators, and control structures necessary for decision-making in C.

Uploaded by

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

URBAN

EDG3

C Programming Noks
by Code With Harry
What is
Programming?
Computer Programming is a medium for
us to communicate with computers. Just
like we use "Hindi"' or 'English' '
to Communicate with each other,
programming is a way for us to deliver
our instructions to the Computer... What
is Co
C is a programming
language.
C is one of the oldest and
finest programming languages.
C was developed by Dennis
Ritchie at AT&T's Bell Labs, USA in
1972.

Uses of C
of
C Language is used to program a
wide variety of System's. Some of
the uses of C are as follows: "
Care

11⁄2 Major parts of Windows,


Linux and other operating
systems are written in
C.

22 C is used to write driver


programs for devices like
Tablets,
printers etc.
3- C language is used to program
embedded systems where progrants
need to run faster in limited memory
(Microwave,
Cameras
etc.)

4. C is used to develop games, an


area where latency is very
important. ic. Computer has to react
quickly on user input."
Scanned with CamScanner
URBAN

EDG3
Chapter 1: Variables,
Constants & Keywords
Variables
A variable is a Container which stores
a Valsse In Kitchen, we have
containers storing Rice, Dal,
Sugar etc. Similar to that
Variables in C stores. Value of a
constant. Example:
a = 3;
b = 4.7;
C = 'A';
// a is
assigned "3""
11 b is assigned "4.7": 11. C is
assigned 'A' indi
Rules for naming
variables in C
1. First character must be an alphabet
or underscore (-)
27 No Commas, blanks
allowed.

32 No special Symbol other


than allowed
42 Variable names are case
sensitive.

We must create meaningful variable


names in our
This enhances readability of
our programs.
progra
ms
Constan
ts
An entity whose value doesn't
change is called as a
Constant!

A variable is an entity whose value


can be changed.

Scanned with CamScanner


URBAN

EDG3

Types of
constants
Primarily, there are three
types of constants
‫ހ‬
- 1967
12 Integer Constant ! 6, 7, 91.
627

Real Constant radio 32


Character Constant →

Key
words
-322·1 2·57·0%
'a' '$' '@' (Must be enclosed within
~ Single inverted
Commas)

These are reserved words, whose


meaning is
already known to the compiler. There
are 32 keyword's available in C
Auto
double
Mint en struct
break
long
else
Switch
Case
tud return enum
enum typedef
in
char
register
extern
union

Const
Short
Continue
signed
float Unsigned dis
Void

Static
if
while
fox
default Size of goto il
volatile

Our First C
Program
#include
<stdio.h>

int main () {
printf ("Hello, I am learning
( with Harry");
return 0;

File: first. C

Scanned with CamScanner


URBAN

EDG3
Basic Structure of a C
Program
All C programs have to follow a
basic structure AC program starts
with a main function and executes
instructions present inside it.
Each instruction is terminated with a
semicolon (;)

There are some rules which are


applicable to all
the C
programs:

12 Every program's execution starts


from main() function. 27 All the
statements are terminated with a semicolon
37 Instructions are lase sensitive
100%

4, Instructions are executed in the same order


in which
they are written.
Commen
ts
Comments are used to clarify
something about the program in
plain language. It is a way for us
to add notes to our program.
There are two types of comments
in C
Single line comment: /|/ This
is a comment.
22 Multi-line Comment: /* This is a
multi line Comment */

Comments in a c program are not


executed and
are
ignoud.
Scanned with CamScanner
URBAN

EDG3

Compilation and Execution


in Wilmeld

first.C

in VS Code
C
Compiler
first
exe
cxc]

500 gcc
дас

A compiler is a computer
program which converts a C
program in to machine language so
that it can be easily understood
by the computer
A C program is written in
plain text·
а
This plain text is combination of
Instructions in ia particular
sequence. The compiler performs
Some basic checks and finally
converts the
program into an
executable.
Library
functions
C language has a lot of valuable
library functions which is used to
carry out Certain tasks. for instance
printf function is used to
Values on the screen

printf ("This
is %d", i);
%d for integers If for
real values % C
for characters
prin
t

Scanned with CamScanner


URBAN

EDG3

Types of
Variables
12 Integer variable → int
a = 3; 22 Real variables
32 Character
Variably
7 Wrong as 7-
7 is real
→ int a = 7·7; float a =
7·7;
Chai a = 'B';

Receiving input
from the User
In order
to take input from the user
and assign it to a variable, we use
scanf function
Syntax for using
scanf :
Scanf("%d",
&i):
1 This & is
important!
& is the "address of" operator and it
means that the supplied value should be
copied to the address which is
"indicated by variable i

Scanned with CamScanner


Chaplex 1- Practice
Get
URBAN

EDG3

Q1 Write a C program to calculate


area of a
rectangl
e:
(a) Using hard
coded inputs
(6) using inputs supplied
by the User

Q2 Calculate the area of a circle and modify


the
Same program to calculate the
Volume of a cylinder given its
radius and height.
Q3
R

Write a program to convert


Celcius (Centigrade
degrees temperature
to farenheit)
Q4 Write a program to calculate
simple interest for a set of values
representing principal,
of years and rate of
interest
no of
Scanned with CamScanner
URBAN

EDG3

Chapter 2: Instructions and


Operators
AC program is a set of Instructions.
Just like a recepic - which contains
Instructions
to prepare a particular
Dish. Types of
bestructions
1 Type declaration
Instruction 22 Arithmetic
Instruction 32 Control
Instruction

Type declaration
Instruction
int Ai
float bi
Other
Variations:

int i=10; int j = i;


int a = 2
int
|1=
a + j = i;

float b = a +3; float a=1.1 =>


ERROR! as we are

int a, b, c, d;
a = b = 6 = d = 30;
Mala
teying to
use a before.
defining it.

→ Value of 9 b, c &d
will
be 30 each.]

Scanned with CamScanner

Arithmetic Instructions I
operators

int
i
=3
32
* 2 +1
2)+

opera
nds
URBAN

EDG3
Operands can be int
/flat ek..
+ - * / are arithmetic
operators
intz, Z =
int b = 2, C= 3;
b*C; ✓ legal
int Z;

%
-

%
%
%
bac = 2; x Illegal (Not
allowed)
→ Modular division
operator

%
5% 2 = 1

Note -
Returns the remainder

Cannot be applied on float Sign is


same as of numerator (-5%.
2=1)

-5% 2 = -1
Ni

17 No operator is assumed
to be present
int i= ab
→ Invalid
int i= a*b → Valid

27 There is no
operator to perform
exponentiation in C However we
can use pow (2,y) from
<math.h>(More
Jatu

Scanned with CamScanner

Type
Conversion
An Arithmetic
operation between
Int and Int Int
and float Float
and float
Int names

Float
Float

5·0/22·5
URBAN

EDG3

5/2 → 20
Important!
!
2/5
2·0/5 → 0.4

Note =
crot wisdo
Q
5/11

int a = 3·5; In this case 3.5 (fbat)


will be

float
a=
8;
demoted to 3(int) because a is
not able to store
floats.
a will Store 8.0 winded
18→ 8.0 (promotion to
float
XY

Quick
Quiz: a
int k = 3.0/9
3.0/9 -


Value of K? and
why?
0.333. but since k is an
int
it cannot store feats
& value 0:33 is demoted
to 0.

Scanned with CamScanner


URBAN

EDG3

Operator
precedence In C
3 #2 -
8y is (3x) - (8y) or
3(2-8 4)?

In ( language simple
mathematical rules like
BODMAS,
no longer
applies.
The answer to the above question
is provided
by operator precedence &
associativity. Operator precedence:
The following table lists
the operator priority
in C Priority Operators
* /%
21
nd
2
3rd
+

Operators of higher
priority are evaluated
first
absence
of
parenthesis
in the

Operator
Associativity ÷
When operators
of equal
priscity are present in an
expression, the tie is taken care
of by associativity.
x* 4/z => (x * y)
/z
x/ y * z
= (x/y) * Z

*/ follows Left to right


associativity

Scanned with CamScanner


URBAN

EDG3

Control
Instructions
wolded.
Determines the flow of Control in
a program Four types of
control Instructions in Care:
17 Sequence Control
Instruction
27 Decision Control
Instruction od 32 Loop
Control Instruction
42

Case Control Instruction...


tai

ut
dah tod

tone
PP
Scanned with CamScanner

Q1
URBAN

EDGE

Chapter 2 -
Practice Set
Practice Set India

Which of the following is


Invalid in C?
"(it int a;
b=a;
(ii) int V = 3^3;
(iii) char dt = '21 Dec 2020';

Q2 What data
type will
3.0/8-2 return.
Q3 Write a program to check
whether a number
is divisible by 97 or
not.
Q4
Explain

95
‫ހ‬

Explain step by step evaluation


of 3* x/y-Z + k
where x = 2
y=3

3·0 + 1 will be:


(a) Integer
(b) Floating point
number
(C)
Character
3*%ly.
Z=3 R=1

Scanned with CamScanner


->
URBAN

EDGE

Chapter 3 - Conditional
Instructions
Sometimes we want to watch
comedy videos on You Tube if the
day is Sunday
Same times we order junk food if it is
our friend's
birthday in the
hostel.
You might want to buy an
Umbrella if its raining
and
you
have the money.
You order the meal if dal or your
favorite bhindi is listed on the menu.

All these are decisions


which depends
being
met.
depends on a
condition
In C language too, we must be able
to execute
on a condition (s)
being met.
instructions"

Decision Making
Instructions in C. if-
else statement
→ Switch
Statement.

If-else
Statement
bo
au

The syntax of an If- else statement


in C looks like:

if (condition to
be checked) {
Statements -if-
Condition-true;
else {
Statements - if -
condition - false;
Insipe
Scanned with CamScanner
URBAN

EDG3

Vi

Code example:
int a = 23;

if (a
718) {
printf (" You can
drive \n");

Note that else block is not


necessary but optional.
Relational operators
in C
Relational operators are used to
evaluate
Conditions (tiue or false) inside the
if Statements. Some examples of
relational operators are =
>=, >, <, <=, !=

equals greater
than equal to
not equal
to
to als

Important note = '' is used


for assignment where as
is used for
equality check
ob

The condition can be any vald expression.


In C a non- zero value is considered
to be true.

Logical
Operators
&&

11 and ! are three logical


operators in C These are read as
"AND", ""OR" and "NOT"
They are used to provide
legic to our C
progra
ms
Scanned with CamScanner
URBAN

EDG3

Usage of Logical
Operators:
(ii) 8
88
→>

AND

1 and 0
→ is true when both the
conditions
are true

is evaluated as
false.
false 10
"

。 and 0" is evaluated


as false.
1
and I"
is
evaluated as true

(1) || → OR + is true when at least


one of the
conditions is true. (1 or 0 + 1) (1
or 1+1)

returns true if given false


and false if
given
time
(iii)
!

!
(3==3
(3730) →
→ evaluates to
false
evaluates to
true.

As the number of conditions increases, the level


of indentation increases. This
reduces readability Logical
operators come to rescue in such
cases.
else if
clause
Instead of using multiple if
statements, we can also use else if
along with if thus forming an if-else if-
else ladder
it { 11
Statements;
}

else if
&
}
else {
}

Scanned with CamScanner

Using if- else if-else


reduces indents
The last "else" is
optional Also there
can be any
number
URBAN

EDG3

of
else
if
fail
.
Last else is executed
only if all conditions.
Operator
precedenc
e
Priori
ty
1st
2nd
3rd
Operat
or

+-
4th
th
5'
6
7


th

th
==, |=
&&

Conditional
Operators
A short hand" "if - else" can be
Conditional or
written using the
ternary operators
Condition ? expression-if-tume;
expression-it-false
Ternary
operators
Scanned with CamScanner
URBAN

EDGE

Switch Case Control Instruction


self two
Switch-Case is used when we have to make
a choice between number
alternatives for a
given
Variable.

Switch (integer-
expression)
{
Case C1:
Code:

Case C2:
Code;
of
C1, Cz & Ca →
Constants.

Code → Any
valid C code
Case C3:
Code:

default
:
Code
;

The value of integer-expression


is matched against
C+s 62, 632...
If it matches any
any of these
Cases, that case along with all
subsequent "Case" and "default"
Statements are executed.
Quick Quiz: Wrik a program to
find grade of
a student given his marks based
on below:
→90-100 →
80 90
-

A
B
→ 70 - 80 c
→ 60.70 → D.
->

→ <70 → F
Scanned with CamScanner
URBAN

EDG3

Important
Notes polo
tan
t
17 We can use switch-case
statements even by
writing cases in any order of our
choice. (not necessarily
ascending)'
2>

37

char Values are allowed as they can


be easily evaluated to an integer
A Switch can occur within another but in
practice this is rarely done

hail

Scanned with CamScanner


URBAN

EDG3
it' Chapter 3 - Practice
Setod ik w
!!! 3.-.
1 What will be the output of
this program
in lint a = 10:
if (a =
11)!
else
ud
printf (" I
am 11");
printf (" I am
not 1|
11"
);
2 Write a program to find out
whether a student is pass or fail; if it
requires total 40% and at least 33% in
each subject to pass. Assume 3 Subjects
and take marks as an input from the
user. 3 Calculate income tax paid by an
employee to the
government as per the slabs
mentioned below.
Income Slab
2.5L5OL
5.01
1

10.0L
Tax
5%
20%
30%
4
J/
N
Above
10.0L

Note that there is no tax below 2.5L.


Take income amount as an input
from the user.
Write a program to find whether a
year entered by the
user is a leap year or not.
Take
year as an input from the
user.

Scanned with CamScanner


URBAN

EDG3
5 Write a program to determine
whether a

6
Character
or not
entered by the user is
lowercase
notit

Write a program to find


greatest of four numbers
entered by the user?
well
italiale

-X08
hiad not

1012
102
10:01

20

Scanned with CamScanner


URBAN.
Chapter 4 - Loop
Control Instruction
Why
Loops
EDG3

WA

Sometimes we want our programs to


execute few set instructions over
and over again. for ex:
printing 1 to 100 first 100 even
numbers etc. Hence Loops make it
easy for a programmer to tell
computer that a given set of
instructions. must be executed
repeatedly.
Types of
Loops d
Primarily, there are three types of
loops in C
Langua
ge:
12 While
bop
do- while loop
27

37

for
loop
We will look into these one

While
loop
While (condition is
true) {
// Code it has 11 Code

}
-
han
by
one

The block keeps


executing
was long as the
condition
is true.
Scanned with CamScanner

An example :
loan ton
int i=0
par latgal

While (i
<10){
L
URBAN

EDGE

printf(" The value of i is %d", i);


i++; Note: If the condition never
becomes false, the while loop
keeps getting executed. Such a
known as an infinite
loop.
is

Quick Quiz: Write a program to


print natural
numbers from 10 to
20
10 to 20 when
initial
is initialized to
0.
Loo
p
Counter
i
The loop counter need not be int,
it can be float
as well!
deal

Increment and decrement


operators
L++ i is increased by
1
→ i is decreased by 1
dool slidW
ed", --i);
printf("-
-i
--i = %d

This first decrements i and


then prints it
print f(" i-- = %d",
(--);
printf(
"
This first prints i and then
decrements it

Scanned with CamScanner

+
URBAN

EDG3

त्रे


Importan
t
+++ operator does not exist.
+= is compound assign
ment operator just like == *
= /= 8 % =
do-While
Loop
=> Also
Important

The syntax of do- While loop


looks like this:
do $
// Code:

// Code;
} while
(Condition)
-

do while loop works very similar to


while loop While checks the condition &
then executes the lode do-while Executes the
code & then checks the condition

do - while loop = While loop


which executes
at least
once.

Quick Quiz: Write a program to


brint first n natural numbers using
do- while
loop

Input
Out
put
:4

:
1
Du w

Scanned with CamScanner


URBAN

EDG3

for
Loop
The syntaxe of for loop looks
like this:
fox (initialize; test;
increment)
E
// Code; toledook
WW
11 Code;
// Code:

Initializ
e
or decrement

a loob Counter to an initial


value
Setting
Checking a
condition
Test →→ Increment

rait An example:
Updating the loop
Counter lekua ahl

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


{
printf("%d", &();
printf("\n");
tai

Outpu
t
0
1

Quick Quiz: Write a


program to print first.
natural numbers using for loop
n

Scanned with CamScanner


URBAN

EDG3

17

A Case of
Decrementing for
loop
of
i
for (i=5; ; ;
; -- )
printf("%d\n",
i);
03

This for loop will keep on


running until i becomes.
0.

The
loop
loop runs
in
runs in
following
following
steps:
i is
initialized to 5
2. The condition "i" (o or nono)
is tested
27

3- The code is
executed.
42 i is
decremented
[

5. Condition i is checked & code is


executed if its not 0.
& So on until i is
non o
67

Quick Quiz: Write a program


to print n natural
in reverse order.
numbers in

The break Statement in


C
The break statement is used to exit
the loop irrespective of whether the
condition is frue
Whenever a "break" is encountered
inside the loop.
the control is sent
outside the loop
Let us see this
with
the help of an
Example

Scanned with CamScanner

for (i=0; i ¿ 1000; i++) {


ret
printf ("%d\n",
i); if (i ==
5) { break;
}

‫الب جاد‬
URBAN

EDG3

output =
0

2
Anal 3
4
PALLY
45

The Continue statement


in C
and not o to 100

The continue statement is used


to immideately
to the next iteration
move

of
the
loop
The control is taken to the next
itration thus Skipping everything
below "continue" inside the bop
for that iteration
Let
Ms
look at an
example
int skip
=53
int i=0;al

while (i
<10){
if (i!=
skip)!!!
Continue;
else
}
printf("%d",
i);
quito? davrd
Anand

Outful
=>
5

and not o..


9

Scanned with CamScanner


URBAN

EDG3
3

Notes:
tod vitam!
1. Sometimes, the name of the
variable might not indicate
the
behaviour
of
the!
progra
m
2. break statement completely
exits the loop.
Continue Statement Skips the
particular iteration of
the
loop.
Scanned with CamScanner

7
51
Chapter 4-
Practice Set
Love Maica
URBAN

EDG3

1 Write a program to print


multiplication table of
a given number
n
ia
seduc

2 Write a program to print


multiplication table
of 10 in reversed
order
"

A do while loop is
executed:
12 at least once
2. at least twice
37 at most once
What can be done using one type
of loop can
done using the other two
types of
True or
False?
4 What
also be
Loop
s -

Write a program to sum first ten


natural numbers using while loop.
6 Write a program to implement
program 5 using
for and do- while
loop!
Write a program to calculate
the sum of the numbers
occurring in the multiplication
table of 8. ( consider 8x1 to
8×10).
Write a program to calculate
the factorial of a given
number using a for loop

Scanned with CamScanner

9
Repeat 8 using while
bops or!
URBAN

EDG3

10 Write a program to check


whether a given
number is prime or not using
loops.

1118

!!! Implement 10 using other


types of leeps.
01 M.
iswal
Sooks l

Scanned with CamScanner

will
fun!
ou!
URBAN
EDGE

Game
and

Project 1: Number guessing


Game Problem: This is going
to program that generates I
to be fun! write a random number
and asks the Blayer to
highet
Quess it. If the player's guess I
is theam the actual number the
program display " Lower number
please". Similarly if the user's is
too low, the program prints"
Higher
"

quesenber please! When the user


quesses the correct number, the
program displays the number of
player used
to arrive at the

Hint: Use
loops
Use a random
number generator

numb
er
the
Scanned with CamScanner
URBAN

EDG3

Chapter 5 - Functions and


Recursion hand
Sometimes our program gets
bigger in size and its not possible
for a programmed to track which
piece of code is
doing what
function is a way to break our code into
chunks so that it is possible for a
programmer to reuse
them:
‫احال‬
What is a Function ?
pan
A
function is a block of code
which performs
A function can be reused by the
programmer in "A given
program any
а
number
of
times.

Example and Syntax of a


function is waillot
#include <stdio.h>
muh
а
Void
display ();
=> Function
prototype.
int main() {
inta;
display
();
=> Function call
returno;
Rink

Void display
() {
١٤
= function
definition
}

printf(" Hi I
am display ");

Scanned with CamScanner

function prototype is a
way to tell the compiler
function prototype & Nina
going to
define about the function we are
going
in

Here void indicates that the


function returns nothing muc
function
call
function call is a way to tell
the compiler to execute the
function body at the time the A
call is made a dhold
Note that the program execution
starts from the main function in
the sequence the
instructions are
written
Novin

the
Function definition it to motor?
han aldona
This part contains the exact set of
instructions which are executed during
the function call. When va function
is called from main() main
function falls asleep and gets
temporarily Suspended. During
this time the control gols to the
function being called. When
the function body is
done executing main
() resumes.
7

Quick
Quiz
Quiz → 1. Good morning
function which prints "Good Morning"
27 Good afternoon function which
prints "Good Afternoon 37 Good
night function which prints"
Good night"
Write a program
with three
functio
1/

main() should call all of these in


order 1 →2→3
Scanned with CamScanner
URBAN

EDG3
Important
Points
+ Execution of a C program
starts from main () → AC
program can have more than
one function.
Every function gets called
directly or indirectly from
main()
→>

->

There are two types of


functions in C. Lets talk
about them ad
Types of
Functions
->

Commonly required
functions grouped
disks
mutton
17 Library
functions.
together in a libray
file on disk

declared and defined by the


user..
2- User defined
functions
Why use
functions?
These are the
functions

agai
n.
1. To avoid rewriting the
same logic again and
2. To keep track of what we
are doing in a program 3. To test
and check logic independently
Scanned with CamScanner
URBAN

EDG3

Passing values
to functions.
We can pass values to a
function and can Value in
return from a function. wewn
int
intb.) w
maspore
sum (int a,
int b
gete

The above prototype means that


sum is a function which takes
values va (of type int) and b ( of type
int)
and returns a value of
type int
function definition of
sum can be
int sum (int a,
int b) {
int c;
Marinac = a+bs
=> a and b are
param
eters
return C
}

Now we can call Sum (2,3); from


main to
get 5 in
return.
Ly Here 283 are
DX JAN

int d = Sum (2, 3); => d


becomes 5
Note:
Kiokn
argume
nts

12 Parameters are the values or


variable placeholders in
the function definition.
Ex a &b.
27
Arguments are the actual values
passed to the function to
make a call. Ex 283.

Scanned with CamScanner


URBAN

EDG3

3- A function can return only one


value at a time
47

4. If the passed variable is


changed inside the function,
Calling function call
doesn't change the
value in the
functio
n.
int change (int
a) {

1 13
a = 17 7 317
01
return 0;

change is a
funct
=> Misnomer

is a function which changes a


to 77. No if we call it from main
like this
leird and
int b = 22
(b);
change
("%d",
"bis "%d", b);
printf
(
JNG

=> The value of b


remains 22

=> prints "b is


22" Aires ?
JTCIA

This happens because a copy of


b is passed to the change
"function

Use the library functions to


calculate
with side a
Quick
Quiz
the area of a square
1619

←a

vil Arca?)
a

Scanned with CamScanner


URBAN

EDG3
Recursi
on
A function defined in C can call
itself. This is called recursion.DOI.
A function calling itself is also
called recursive function.
Example of
Recursion
to

A very good example of


recursion is factorial
factorial
(n)
= 1×2×3
X N

factorial
(n)
1 × 2 × 3 ..! n-
1~xn
Linny

factorial
(2)
factorial (n-1)
xn
(d) sanad]

Since we can write factorial


of a pumber
of itself, we can
program it using
terms
recursion.
Jadal

int factorial
(int x) {
int fi
if ( x == 0 ||
x == 1) ...||
return 1;
else
f = x + factoral
(x-1);
return fi
wh drick
ли

= A program
to
calculate factorial using recursion
Scanned with CamScanner
URBAN

EDG3

5
X

How does it
work?

factorial
(5)

x factorial (4)
+
x factorial (3)
4
5
X
4
X
3.
X

factorial (2)
5
X
4
X
3
X
2x

factorial
(1)

5
X
4
x 3 x
2 x

Important
Notes:
1. Recursion is sometimes
the most direct way
27

Code an
algorithen
to

The condition which doesn't call the


function any further in a recursive
function is
the
base condition 8

called as

3. Some times, due to a mistake made by


the programmer,
a recursive function can keep running
without returning resulting in a memory
error.
Scanned with CamScanner

Chapter 5 -
Practice Set
URBAN

EDG3

Write a program using


functions to find average of
of three
numbers.
? Write a function to convert
Celsius temperature
into
farenheit.
3

4
=

5
=

Write a function to calculate force


of attraction on a body of mass m
exerted by earth
опа
(9 =
9·8m/s2) Write a program using
recursion to calculate
nth element
of fibonachi
series.
What will the following line
produce in a c program
printf("%d %d "%d\n",
a, +ta, a++);

Write a recursive function to calculate the


sum of first n
natural numbers. and
Write a program using functions
to print the following pattern (first
n lines)

** *
*
** * *

Scanned with CamScanner


URBAN

EDG3

Chapter 6 -
Pointers
A pointer is a variable which stores the
address
Another variable
of

72
87994

address 87994
address+
87998

Lis a
pointer j
points to i
i
#

The "address of" (8)


operator
1

The address of operator is used


to obtain the Address of a given
variable
If you refer to the
diagrams above
20mod

& i => 87994


& j => 87998

Format specifier for printing


pointer address is "%u
The value at address
operator (*)
The value at address or & operator
is used to
obtain the value
al of

present at a given memory


address. It is denoted by *
= 72
* & i) *(81) =
87994

Scanned with CamScanner


URBAN

EDG3

How to declare a
Pointer ?
the
following
syntax
→ declare a variable 1 of
type int-pointer
Store address of i
in j
1.
int *j;
J=&i

Just like pointer of type integer,


we also have pointers to char,
float etc.
int ch-ptr;
char * ch
ptrs

Pointer to integer:
Pointer to
character
fbdt * ch -
Chaptx; → Pointer
to fleat
1. Although its a good practice
to use meaningful
Variable names,
we should be very careful
while reading & working on
porgrams from fellow
programmers.
A Program to
demonstrate
pointers
#include
<stdio.h>
int main () {
int i=83
int #1;
1=2i;

printf(" Add i = "%% um,


& i); Brint +
("Add i = "/4 12, 1);
f "baintf (" Add | = "/ou \
n", &f); brintf ("
Value i = "%d\n", i);
"brintt (" Value i = "/ed
\n", * (li)); printf ("
Value i = "/1⁄2d
In", * 1);
return 0;.
wi

Scanned with CamScanner


URBAN

EDGE

Output:
Add i =
87994 Add i =
87994 Add 1 =
87998 Value =
8 Value = 8
i
Value = 8
i

Thave program sums


it all. If you
understand it, you
have got the idea of
painters
Pointer to a
pointer
Just like i is pointing to i or
storing the address of
j i, we can have another variable k
which can further store the address
of j. what will
be the type of
R
int **R;
k = bj
chinixo
l

72
J
R

87994
87998

87994
int
29487998
int "
88004
*
int **

We can even go further. One level


and create a Variable I of type int *** to
store the address of R. We mostly
k. We mostly use int * and int
** game times real would programs.
in

Scanned with CamScanner


URBAN

EDGE

Types of
function calls
Based on the way we pass
arguments to the function,
function calls are of two
types.
17

17

Call by Value
call by
reference
->

Sending the values


of arguments
Gending the
address of
arguments

Call by Value
Here the value of the
arguments are passed to the
function. Consider this
example:
int c
= sum (3,4); => assume
1=3 and y=4
x, y unitaind
if sum is defined as
sum (int a, int b)
the
Values
3 and 4 are copied to a and 5.
Now ever we change a and b,
nothing happens to the variables I
and y.
and
it
This is call by
value.
In 6 we usually make a
call by value.
Call by
reference
is
passed
Here the address of the variables
is to the function as
arguments
Now since the Addresses are
passed to the function, the
function Can à Variable in
Calling function using * and
now modify the
value of operators. Example:

Scanned with CamScanner

Void Swap (int *1,


int *y,
{


?
int temp;
temp = * x;
* 1 = xy;
temp;
¥ y==
URBAN

EDG3

This function is capable of


swapping the values passed to it.
if a = 3 and b = 4 before a call to
swap (a, b), α = 4 and b=3
after calling Swap.
int main() {
Lint a = 3
int b = 4
b=
Swap
(a,b)
return 0;
}
=> a is 3 and bis 4

=> Now a is 4 and 6 is 3


bis

Scanned with CamScanner


URBAN

EDG3

Chapter 6 - Practice Set I


love how
1 Write a program to print the
address of a Variable. Use this
address to get the value of this
variable.
2
1

Ha!

6
8/11
Write a program having a
variable i. Print the address of i!
Pass this variable to a
of
Pass this variable to wa
function and print its address. Are
these addresses
Arca these wa
Same? why?

Write a program to change the value


of a variable to ten times of its current
value. Write va function and pass
the value by reference.
Write a program using a
function which calculate the
sum and average of two
numbers. Use pointers and print
the values
in Main ()
of Sum and
averag
e

Write a program to print the


value of a variable i by
using "pointer to pointer"
type of Variable
Try problem 3 using call by
value and verify that it doesn't
change the value of the said
Variable.
Scanned with CamScanner

Chapter 7 -
Arrays Atwo
An array is
a
URBAN

EDGE

is a collection of similar
elements.
1 imp

One Variable => capable of


storing multiple values
Synta
x
The Syntax of declaring an Array
looks like this:
+ int marks
[90]; char name
[20];

TH.
=> Integer array →
Character array or
String
float percentile
[90]; → flat array
HARPA

w The values can now be assigned


to marks array
like this:

marks [o] = 33;


33 8
marks [1] = 12;
(H

Note: It is very important to note


that the array
index starts with o!

Marks →→
7 6 21 391 3
888893AI

‫م‬
234 5
00

88 89

01622

Total = 90 elements
wit
Scanned with CamScanner

Accessing
elements
188A - I
wouldad
URBAN

EDGE

Elements of an array can be


accessed using:
MARRO

Scanf("%d", &
marks [o]);
=>

Input first
value
printf ("%d", marks [o]); =>
output first value
Quick
Quiz
→>>

of the
array
Write a program to
of five students
accept marks
in an array and print
them to the screen.

Initialization of an
Array
Hop]
I

There are many other ways in which


an array can be initialized.
int
capa [3] = { 9, 8, 8 3 =>
Arrays can be float marks[] =
= { 33, 40}

Arrays in
memoryped an
Consider this
array:
initialized
while
declaratie

int arr. [3] = { 1, 2 3} => 1 integer = 4


byles
P&

This will reserve 4×3 =


12 bytes in memory 4 bytes for
each integer.
23
62302 62306 62310
=> arr in memory

Scanned with CamScanner


WA
URBAN

EDG3

Pointer
Arithmeticatio
A pointer can be incremented to
point to the
next
memory
Location

Consider this
example.
int i = 32;
of
that
type
.
i

int * a = & i; => a =


87994
=
a ++;
32

->>

address 87994
4+ vdc => Now a = 87998al
Anied

char a =
'A';
NO

char * b = &a;
=> a = 87994
b++: s

float i = 1·7;
=> Now b = 87995

float * a = &i; => Address of i or


a = 87994
a ++;
=> Now a = 87998+

Following operations can be


performed on a pointers:
1. Addition of a number
to a pointer 22 Subtraction of
a number from a pointer 37
Subtraction of one pointer from
another 42 Comparison of two
pointer variables
->>

wind

Quick Quiz Try these operations on


another variable by creating pointers in
a separate program. Demonstrate all
the four operations.

Yay! we
understood
pointer
arithmetic
Scanned with CamScanner

Accessing Arrays
using pointers
Consider this array dow
off
7928
index
2 34

Ptr

will
point
to
If ply points to index o,
ptr ++ will
index i & so on ...
1

This way we can have an


integer pointer pointing to first
element of the array! like this:
int *
ptx ptx
++s
*

= & arr [o]; → or


simply arr
ptr => will have 9 as its
value.
Passing arrays to functionsin
indovida parte Arrays can be
passed to the functions like this
print Array (arra); => function
call.
Void print Away (int" i,
int n); => function
prototype
or

Win Void print Array ( int


i[], int n);
dawb
Scanned with CamScanner

Multidimension
al Arrays
URBAN

EDG3

An Array can be of 2
dimension / 3 dimension / n
dimensio
ns
A 2 dimensional array can be
defined as:
int arr [3][2] =
{
{1,4}
27, 93
{1, 22 } } ;

We can access the elements of this


array as
arr [0][0], arr [0][1] & so on...
‫ال‬

= 1
Value = 1

Value=4

2-D arrays in
Memory
A 2d arlay like a 1-6 array
is stored in
contiguous memory blocks
like this:
arr[o][o] arr[0][1]

14
87224 87228
7
91122
Quick Quiz: Create a 2-d array
by taking input from the user.
Write a display function to print
the content of this 2-d Array in
the screen.

Scanned with CamScanner

=
URBAN

EDG3

Chapter 1- Practice Set);


mlinomikilladel
1 Create an array of 10 numbers.
Verify using pointer arithmetic that
(ptx+2) points to the third
clement where pto is a pointer
pointing
first element of the
array.
to the

2 If 9[3] is a 1-D array of


integers then *(5+3) refers to the
third element:
z
3

5
‫اما‬

7
(1) True
(1) False
(ii)
Depends
.
Write a program to create an
array of 10 integers and store
multiplication table of 5
in itinata
D

Repeat Problem 3 for a general


input provided by the user
using scanf:

Write a program containing a


function which reverses the
array passed to it.. Array passed
to it
Write
N

Counts the linggram


containing functions which
Counts the number of positive
integers in an array.
Create an array of size 3x10 containing
multiplication tables of the
numbers 2, 7 and 9 respectively

Scanned with CamScanner

&

g
URBAN

EDG3

Repeat problem 7 for a


custom imput given
by the user
Create a three-dimensional
array and print the address
of its elements in increasing
element
hay
order
sharad

Fotona modland Ai

VSSAN
Scanned with CamScanner

You might also like