0% found this document useful (0 votes)
8 views460 pages

Module 1 PT 1 - Merged

The document provides an introduction to computer programming, covering fundamental concepts such as algorithms, flowcharts, and the C programming language. It explains the phases of problem-solving, the structure of a C program, and the importance of constants, variables, and data types. Additionally, it includes examples of algorithms and flowcharts for basic programming tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views460 pages

Module 1 PT 1 - Merged

The document provides an introduction to computer programming, covering fundamental concepts such as algorithms, flowcharts, and the C programming language. It explains the phases of problem-solving, the structure of a C program, and the importance of constants, variables, and data types. Additionally, it includes examples of algorithms and flowcharts for basic programming tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 460

Module-1 (Part-1)

Introduction to Computer Programming

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Contents
 Introduction to Programming

 Algorithm & Flowchart

 Introduction to C programming

 Constants, Variables & Data Types


Introduction
 All digital computers, regardless of their size, are electronic
devices that can transmit, store, and manipulate information.

 Several different types of data can be processed by a computer-


 numeric data
 character data (names, addresses, etc.)
 graphic data (charts, drawings, photographs, etc.)
 sound (music, speech patterns, etc.), etc

 To process a particular set of data, the computer must be given an


appropriate set of instructions called a program.
Program

 A program is a set of instructions that a computer follows in


order to perform a particular task.

 The instructions are entered into the computer and then stored in
a portion of the computer‟s memory.

 A stored program can be executed at any time.


Cont…
Program Execution:
1. Input:
 A set of information, called the input data entered into the
computer (from the keyboard and stored in a portion of the
computer‟s memory.

2. Processing:
 The input data is processed to produce certain desired results,
known as the output data.

3. Output:
 The output data, and perhaps some of the input data, will be
printed onto a sheet of paper or displayed on a monitor
Example
 Finding area of a rectangle
A=length × width

 Input: read the numeric value for length and width

 Processing: calculate the area of the rectangle using the formula

 Output: print(display) the value of area


Phases of Problem Solving
 A typical programming task can be divided into two phases:

 Problem solving phase


 produce an ordered sequence of steps that describe solution of a
problem
 this sequence of steps is called an algorithm

 Implementation phase
 implement the program in some programming language

Algorithm: step by step execution of a program


Steps in Problem Solving

1. First produce a general algorithm (one can use pseudocode)

2. Refine the algorithm successively to get step by step detailed


algorithm that is very close to a computer language.

Pseudocode:
 It is an artificial and informal language that helps programmers
to develop algorithms. It is very similar to everyday English.
Example-1
 Write an algorithm to find the sum of two numbers

Pseudo code:
 Input two numbers
 Calculate sum of the two numbers
 Print the sum

Detailed Algorithm:
Step 1: Input a, b
Step 2: sum=a + b
Step 3: Print sum
Example-2
 Write an algorithm to find average of three numbers

Pseudo code:
 Input three numbers
 Calculate average of the numbers
 Print the average

Detailed Algorithm:
Step 1: Input a, b, c
Step 2: average=(a + b + c) / 3
Step 3: Print average
Example-3
 Write an algorithm to find area of a rectangle

Pseudo code:
 Input the height and width of the rectangle
 Calculate area by multiplying height with width
 Print the area

Detailed Algorithm:
Step 1: Input h, w
Step 2: area=h × w
Step 3: Print area
Example-4
 Write an algorithm to find area and circumference of a circle

Algorithm:
Step 1: Input r
Step 2: area= π × r × r
Step 3: circumference=2 × π × r
Step 4: Output area and circumference
Flowchart
 A flowchart is a type of diagram that represents
an algorithm, workflow or process, showing the steps and their
order by connecting them.

 In simple, we can say-


“it‟s the graphical representation of the algorithm that
illustrates a solution model to a given problem”.

 Flowcharts are used in analyzing, designing, documenting or


managing a process or program in various fields.
Some Flowcharts Symbols
Example-1
Flowchart to find sum of two numbers

Algorithm:
Step 1: Input A
Step 2: Input B
Step 3: Sum=A + B
Step 4: Print Sum
Example-2
Flowchart for average of three numbers
START

Input
Algorithm: a, b, c

Step 1: Input a, b, c
average = (a+b+c)/3
Step 2: average= (a+ b + c) / 3
Step 3: Print average
Print
average

STOP
Example-3
Flowchart to find area of a rectangle START

Input
h, w
Algorithm:
Step 1: Input h, w
area = h × w
Step 2: area=h × w
Step 3: Print area
Print
area

STOP
Example-4
Homework Question:
Draw flowchart for finding area and circumference of a circle from the
given algorithm

Algorithm:
Step 1: Input r
Step 2: area= π × r × r
Step 3: circumference=2 × π × r
Step 4: Output area and circumference
Example-5:
Flowcharts for Decision Making
START
Algorithm and flowchart to find
greatest among 2 numbers Input
a, b

Algorithm:
Step 1: Input a, b, Y is N
Step 2: if a>b then a>b ?

Step 3: Print a is greater


Step 4:else Print Print
a is greater b is greater
Step 5: Print b is greater

STOP
What is Programming ?
• Programs are set of instructions given to a computer to accomplish
a task.

• Instructions must be written in a way the computer can understand


• Programming languages are used to write programs

• Once the code (language) of a program has been written, it must be


executed (run, started).

• There are many programming languages available today with


varying features.
• Our focus will be on the C Programming Language
How to Write a Program?
• Understand the problem

• Decide what steps are needed to solve the task

• Write the steps in pseudocode (written in English) or as a flowchart


(graphic symbols)

• Translate the steps into the programming language

• Execute the program and “debug” it (fix if necessary)


Cont...

To translate the steps needed(algorithm or flowchart) to


solve a computing task into any programming language,
the syntax of the language must be known.
Introduction to C Programming
History of C
 C was invented by Dennis Ritchie at Bell Laboratories

 The rapid growth of C lead to the development of different


versions of the language that were similar but often incompatible
which cause serious problems for system development.

 To assure that the C language remains standard, in 1983, ANSI


(American National Standard Institute) appoints a committee to
define the standard for C called ANSI C (or c89) which was then
approved by ISO in 1989.
History and Development of C
Importance of C
 It‟s a robust language with rich set of build in functions and
operations to write any complex program

 Programs written in C are Efficient, faster and highly portable

 It‟s a structured language that makes debugging, testing, and


maintenance easier

 It has the ability to extend itself


 We can add our own functions to C libraries

…….
Sample Program-1

#include<stdio.h>
main()
Output:
{
My first C Program
printf(“My first C Program”);
}
Executing a C Program
 Executing a C program involves-
1. Creating the program

2. Compiling the program

3. Linking the program with functions that are needed from


the C library

4. Executing the program


Process of Compiling and Running a C
Program
Cont…

 The compilation command converts the source code into a form that
is suitable for execution by the computer (known as object code).

 The compiled and linked program is called the executable object


code and is automatically stored in the file named a.out
Creating, Compiling and Executing c
Programs
1. Create the program and save with .c extension
example: prog1.c
Rules for file names:
 There should not be any space between file name
 The file name should not be any keyword name.

2. Compile the program


cc filename.c
example: cc prog1.c

3. Run the program


./a.out
An Overview of the Structure of a C
Program
Simpler Structure to be used for
Module-1

X
Including Comment Section in
Program
/*
Program Details: Printing hello world Documentation
Author: Amit Kumar Section
Date of creation: 16th September2024
*/
#include<stdio.h> Linking Section
main()
{ main function Section
printf(“Hello World !”);
} Output:
HelloWorld !
Sample Program Description
Comment lines:
 Comment lines are not executable lines however, are used to
enhance the readability and understanding must be included
within /* */
<stdio.h>
 Pre-defined library for standard input/output
main()
 The program execution begins from main().
 Every C program must have only one main().

printf():
 Predefined standard C function for printing output.
 prints everything between “ ” and ends with a ;
Comments in C
 Comments in C language are used to provide information about
lines of code.

 It is widely used for documenting code.

 There are 2 types of comments in the C language:


 Single Line Comments
 Single line comments are represented by double slash //

 Multi-Line Comments
 Multi-Line comments are represented by slash asterisk /* ... */.
Different forms of main()

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


main() void main() int main()
{ {
{
printf(“ Welcome”);
printf(“ Welcome”); printf(“ Welcome”); return 0;
} } }

Output: The function does This function returns an


not return any integer value to the
Welcome
information to the operating system.
operating system The last statement of
the program should
be return 0.
Constants, Variables and
Data Types
 The task of processing of different data is accomplished by
executing a sequence of precise instructions called a program.

 These instructions are formed using certain symbols and words


according to some rules called syntax rues.

 Every program instruction must confirm precisely to the syntax


rules of the language.

 Like any other programming language, C has its own syntax rules.
Character Set
 The character set in c is grouped into the following types:
 Letters:
Uppercase A, B….Z
Lowercase a, b, c….z

 Digits:
all decimal digits 0,1,2,….9

 Special Characters:
, . : ? ! | /% & ^ - + > > ) ( { } [ ], etc

 White space
C Tokens
 The smallest individual units in c programming are known as C
tokens.
 C has 6 types of tokens and programs are written using these
tokens and the syntax of the language
Keywords
 Every c word is classified as either a keyword or an identifier.

 All the keywords have fixed meanings and these meanings can
not be changed.

 There are 32 keywords in c and all written in lower case


Identifiers
 Identifiers refers to the name of the variables functions etc.
 These are user defined names consisting of a sequence of letters
and digits.

Rules:
1. First character must be an alphabet
2.Must consists only letters, digits or underscore (both uppercase
and lowercase letters are allowed)
3. Only first 31 characters are significant
4. Can‟t use a keyword
5. Must not contain white space
Cont…
correct Identifiers are represented in green color

12prog
prog12
prog 12
prog_12
my program 1
myProgram
myProgram$
Prog#,
Constants
 Refers to fixed values that do not change during program
execution.
Integer Constants
 An integer constant refers to a sequence of digits.

 Decimal (0-9)
examples: 7, 11, 123, -321

 Octal (0-7)
examples: 037, 0

 hexadecimal (0-9, A-F)


examples: 0X2

 Character spaces are not allowed between integer constants.


examples: 15 756 (illegal)
Real Constants
 Deals with fractional values called floating point constants
Examples: 215.5, -0.75 , 15.89

 A real number may also be expressed in exponential notation.

Example:
215.65 may be written as 2.1565e2 in exponential notation,
where e2 means multiply by 102

Other examples of valid real constants:


0.65e4, 12e-2, 3.18E3, -1.2E-1
Cont…
 General form:
mantissa e exponent

 The mantissa part is either a real number expressed in decimal


notation or an integer.

 The exponent is an integer number with an optional plus or minus


sign
Cont…
correct numeric constants are represented in green color

Examples:
27 756
25,000
3.5e2
3.5e-5
+5.0E3
7.1e 4
-4.5e-2
1.5E+2.5
$255
0X7B
Single characters
 Contains a single character enclosed with a single quote

Examples: „x‟ „;‟ „ ‟


Note: the character constant „5‟ is not the same as number 5.

String constants
 A sequence of characters enclosed in double quotes.

Examples: “hello” “1990” “ welcome to SIT” “5+3”


Examples of Escape Sequence in C
Variables
 A variable is a data name used to store a data value.
 Variable may take different values at different time during
execution.

 May consist of letters, digits or underscore (_)


 Only first 18 characters are significant

Examples of valid variable names:


First_tag
Avg_num
sum
Sum
sum1
Cont…
Examples of invalid variable names:
Avg marks
Price$
$count
sum of numbers
123 (area)
% 25th
void
Data Types
 3 classes of data types available in c:

1. Primitive or fundamental data types


2. Derived data types
3. User defined data types
Primitive Data Types
 All C compilers support 5 major fundamental data types:
 char (character)
 int (Integer)
 float (floating point)
 double (double precision floating point)
 void

 However some extended type may be possible


 long int
 long double
Cont…

 In order to provide some control over the range of numbers and


storage space, C has:
 3 classes of integer
 3 classes of floating point values
Range of Basic Data Types on 16 bit
Machine

Data Type Range of values


char -128 to 127
int -32768 to 32767
float 3.4e-38 to 3.4e+e38
double 1.7e-308 to 1.7e+308
Range of Basic Data Types on 16 bit
Machine
Declaration Variables
 All variables must be declare to the compiler for their use in the
program.
 Declaration of a variable tells the compiler what is the variable
name and what type of data the variable will hold.

Syntax for declaring variables:


data_type v1, v2, …vn;

Examples:
int a, b;
//declares 2 integer type variables with names a and b
float avg;
//declared a floating point variable with name avg
Assigning Values to Variables
 Values can be assigned to variables using assignment operator =

Syntax:

variable_name=constant;

Example:
a=10;
b=20;
Declaration and Value Assignment in
One Step

int a, b;
a=10;
b=20;

or

int a=10;
int b=20;
Printing Values of Variables
Examples
C statement:
int a=10; Output:

printf(“a”); a

10
printf(“%d”, a);

printf(“a=%d”, a); a=10

printf(“The value of a is: %d”, a); The value of a is: 10


Program
Write a C program to print sum of 2 integers

#include<stdio.h>
main()
{ Output:
int a, b, sum; The sum of 2 numbers is: 30

a=10;
b=20;
sum=a+b;

printf(“The sum of 2 numbers is: %d”, sum);


}
Reading Data from Keyboard
 Input data through keyboard suing the scanf function

Syntax:
scanf(“control string”, &var1,&var2,…);

Example:
int a;
printf(“Enter the value of a”);
scanf(“%d”, &a);
Cont…
Example:
int a,b;
printf(“Enter the value of a and b”);
scanf(“%d%d”, &a,&b);

or

printf(“Enter the value of a”);


scanf(“%d”, &a);
printf(“Enter the value of b”);
scanf(“%d”, &b);
Example Program
Write a C program to enter 2 numbers and print the sum
#include<stdio.h>
main()
{
int a, b, sum; Output:
printf(“Enter the value of a”); The sum of 2 numbers is: 30
scanf(“%d”, &a);
printf(“Enter the value of b”);
scanf(“%d”, &b);

sum=a+b;
printf(“The sum of 2 numbers is: %d”, sum);
}
Module-1 (Part-2):
Operators & Expressions in C

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Contents
 Operators

 Operator precedence and associativity

 Expression evaluation

 type conversion
Operators and Expressions
 An Operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.

 Operators are used in programs to manipulate data and variables.

 C supports a rich set of built-in-operator


 Examples: +, -, *, /,..&&,…etc

 An expression is a sequence of operands and operators that


reduces to a single value

Example: 10+15
 this expression value is 25
C Operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and decrement Operators
 Conditional Operators
 Bitwise Operators
 Special Operators
Arithmetic Operators
Operator meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% modulo division
Examples
a-b
a+b
a*b
a/b
a%b
-a * b
Here a and b are variables known as operands

 Note:
 Integer division truncates remainder
 The % operator cannot be applied to a float or double.
Examples
Convert a given number of days into months and days

Example: 45 days
1 month, 15 days

364 days
months=12 months, 4 days
Example Program
Q. write a C Program to convert a given number of days into
months and days.

#include<stdio.h>
main()
{
int ndays, month, days;
printf(“Enter number of days\n”);
scanf(“%d”, &ndays);
months=ndays/30;
days=ndays%30;
printf(“Months=%d \n Days=%d”, months, days);
}
Homework Questions
1. Write a program to convert an entered distance in meters to
corresponding kilometers and remaining meters.

2. Write a program to convert an entered distance in inches to


corresponding feets and remaining inches.
Relational Operators

Operator Meaning
< less that
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Examples
 A relational expression yields a value of 1 or 0.

5<6 1

-34 + 8 > 23 - 5 0

if a=3, b=2, c =1;


then the statement a > b > c will print 0

 The associativity of relational operators is:


left  right
Logical operators
 C has the following three logical operators:
 && meaning logical AND
 || meaning logical OR
 ! meaning logical NOT ( unary operator )

 Expressions connected by && or || are evaluated left to right,


and evaluation stops as soon as the truth or falsehood of the
result is known.
Examples
a> b && a>c

age >55 && salary < 1000

number <0 | | number > 100


Assignment Operator
 Assignment operators are used to assign values to variables
or assign expression results to variables.

Examples:
a=10
b=20* 30
Example Program
/*Swap two integers using 3rd variable */
#include<stdio.h>
void main() {
int a=10, b=20,c;
printf(“Before swapping a=%d and b=%d\n”, a,b)
c=a; //c stores 10
a=b; // a becomes 20
b=c; // b becomes 10
printf(“After swapping a=%d and b=%d\n”, a, b)
}
Output:
Before swapping a=10 and b=20
After swapping a=20 and b=10
Example Program
/* Swap two integers without using 3rd variable */
#include<stdio.h>
void main()
{
int a=10, b=20,c;
printf(“Before swapping a=%d and b=%d”, a,b)
a=a+b; //a becomes 30
b=a-b; //b becomes 10
a=a-b; //a becomes 20
printf(“after swapping a=%d and b=%d”, a, b)
}
Output:
Before swapping a=10 and b=20
After swapping a=20 and b=10
Increment and Decrement Operators
 C provides two unusual operators for incrementing and
decrementing variables.

 The increment operator ++ adds 1 to its operand.


 The decrement operator -- subtracts 1 from its operand.

 The unusual aspect is that ++ and -- may be used either as prefix


operators (before the variable) or postfix operators (after the
variable).

Examples:
n++ ++n
n-- --n
Examples
Increment Operator: Decrement Operator:
m=5; n=6;
y=m++; x=n--
Output: Output:
value of y=5, value of m=6 value of x=6, value of n=5

n=6;
m=5;
x=--n
y=++m; Output:
Output: value of x=5, value of n=5
value of y=6, value of m=6
Examples
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a, b; int a,b;
a=2; a=2;
b=a++; b=++a;
printf(“%d %d”, a, b); printf(“%d \n %d”, a, b);
} }

Output: 3 2 Output: 3
3
Examples
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a,b; int a,b;
a=2;
a=2;
b=a--;
b=--a;
printf(“%d%d”, a, b);
} printf(“%d %d”, a, b);
}
Output: 12
Output : 1 1
Examples
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int p, q; int p,q;

p=10
p=10
q=p++;
q=p++;
printf(“%d ”, ++q);
printf(“%d ”, p++);
printf(“%d ”, -- p);
printf(“%d ”, q); printf(“%d ”, p);
printf(“%d ”, p); printf(“%d ”, q);
} }
Output: 11 10 12 Output: 11 10 10 11
Examples
#include<stdio.h>
void main()
{
int x,y;

x=5
y=x--;
printf(“%d ”, x++);
printf(“%d ”, ++y);
printf(“%d ”, x--);
printf(“%d ”, --y);
}

Output: 4 6 5 5
Conditional Operator
 A ternary operator pair “ ? : ” is available in C to construct
conditional expressions of the form:

expr1 ? expr2 : expr3

 The expression expr1 is evaluated first.


 If it is non-zero (true), then the expression expr2 is evaluated,
and that is the value of the conditional expression.

 Otherwise expr3 is evaluated, and that is the value.

 Only one of expr2 and expr3 is evaluated.


Examples-1
Find greatest among two numbers using conditional
operator:

max = (a > b) ? a : b;

If a=20, b=10
Then value of max=20

If a=10, b=30
Then value of max=30
C program to find greatest among two numbers
using conditional operator
#include<stdio.h>
void main()
{
int a, b, max;
a=20;
b=10;
max = (a > b) ? a : b;
printf(“The greatest among the two numbers is %d”, max);
}

How to find smallest among two numbers??


Find greatest among three numbers using
conditional operator
max = (a > b) ? a : b;
max = (c > max) ? c : max;
printf(“The greatest numbers is %d”, max);

or

max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);

How to find smallest among three entered numbers??


Example Program
Enter the age of a person and print whether the person is eligible to
vote or not using conditional operator.

#include<stdio.h>
void main()
{
int age;
printf(“enter the age of the preson”);
scanf(“%d”, &age);
age>=18? printf(“Eligible to vote”): printf(“Not eligible to vote”);
}
Special Operators
 C supports some special operators such as:
 comma operator
 sizeof operator
 Pointer operators (&, *)
 Member selection operators (. and ->)

Note:
 In Module- 1 only comma and sizeof operators will be discussed.
 Pointer and member selection operators will be discussed in Module-5
The Comma Operator
 The comma operator can be used to link the related expressions
together.
 A comma-linked list of expressions is evaluated left to right and
the value of right-most expression is the value of the combined
expression.
#include <stdio.h>
Example:
void main() {
value = (x=10, y=5, x+y);
int x, y, value;
value = (x=10, y=5, x+y);
/*first assigns 10 to x, then
printf("%d", value);
assigns 5 to y, and finally
assigns 15(i.e. 10+5) to }
value*/ Output: 15
The sizeof Operator
 The sizeof is a compile time operator and when used with operand,
it returns the number of bytes the operand occupies.

Example:
#include <stdio.h>
void main()
{
printf("%d", sizeof(int));
return 0;
}
Output: 4 /* on a 64 bit processor*/

 It is normally used to determine the length of arrays and structures


when their sizes are not known to the programmer.
Some Mathematical Functions

 To use any of the predefined mathematical functions use:

#include<math.h>

Note: during compilation you have to link the math library:

Compilation syntax:
cc prog1.c -lm
Some Mathematical Functions
#include<math.h>
Functions Description
pow(x,y) : find xy
sqrt(x) :find square root of x
ceil(x) :x rounded up to nearest integer
floor(x) :x rounded down to nearest integer
fabs(x) :find absolute value of x
cos(x) :find cosine of x
sin(x) :find sine of x
tan(x) :find tan of x

Where x, y are variables


Arithmetic Expressions
 An arithmetic expression is a combination of variables, constants
and operators arranged as per the syntax of the language.
Examples:

Arithmetic Expression C Expression


a × b -c a * b -c
(m+n) (x+y) (m+n) * (x+y)
ab (a * b )/c
__
c
3x2+2x+1 3 * x * x + 2* x + 1
x x/y+c
__ + c
y
Evaluation of Expression
Syntax:
Variable =expression

Example:

x= a * b + c;
y= b / c – d;
Operator Precedence and
Associativity
 Rules of Precedence and Associativity:

(1) Precedence rules decides the order in which different operators


are applied.

(2)Associativity rule decide the order in which multiple


occurrences of the same level operator are applied.
Precedence of Arithmetic Operators
 An arithmetic expression without parenthesis will be evaluated
from left to right using the rules of precedence of operators

High Priority: * / %
Low Priority: + -
Example:
x=9-12/3+3*2-1

Step-1: 9-4+3*2-1
Step-2: 9-4+6-1

Step-3: 5 + 6-1
Step-4: 11 - 1
Step-5: 10
Cont…
 The order of evaluation of arithmetic expression changes
with parenthesis:
 First parenthesis sub section from left to right

Example:
x=9-12/(3+3)*(2-1)

Step-1: 9-12/6*(2-1)
Step-2: 9-12/6*1

Step-3: 9-2*1
Step-4: 9-2
Step-5: 7
Type Conversions in Expressions
1. Implicit Type Conversion
 C automatically converts any intermediate values to the proper
type so that the expression can be evaluated without loosing any
significance.
 This automatic conversion is known as implicit type conversion.
 The rule of type conversion: the lower type is automatically
converted to the higher type.

2. Explicit type conversion is required for converting the higher


types to lower types
Example: Implicit type conversion
int a=5;
float b=4.6;
float c;
c=a + b;

Allowed
Example: Explicit type conversion
int a=5;
int d, e;
float b=4.6, c=5.6;
d=b - a; d=(int) b - a;
e=c + a; e=(int) c + a

Not Allowed Correct version


Identify Errors/
Reasons for Wrong Output
Example-1
/*Find the sum of 2 integers*/

#include<stdio.h>
#include<stdio.h>
void main()
void main()
{
{
int a=3,b=3, sum;
int a=3,b=3, sum;
sum=a+b
sum=a+sum;
printf(“ %d", sum);
printf(“ %d", sum);
}
}

Output: Error....
Example-1
/* Find the sum of 2 integers*/
#include<stdio.h>
void main()
{
int a=3,b=3, sum;

sum=a+sum b ;

printf(“ %d", sum);


}

Output: 6
Example-2
/* Find the average of 3 numbers*/
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a=3,b=3,c=2; int a=3,b=3,c=2;
float avg; float avg;
avg=a+b+c/3; avg=(a+b+c)/3;
printf(“%f ", avg); printf(“%f ", avg);
} }

Output: 6.000000 Output: 2.000000


/*No errors but wrong result */ /*still wrong Result */
Example-2
/* Find the average of 3 numbers*/

#include<stdio.h>
void main()
{
int a=3,b=3,c=2;
float avg;
avg=(float)(a+b+c)/3;
printf(“%f ", avg);
}

Output: 2.666667
Example-3
/*Find the CGPA to equivalent percentage*/

#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
float cgpa=6.5, per; float cgpa=6.5, per;
per=cgpa-0.50*10; per=(cgpa-0.50)*10;
printf("%f ", per); printf("%f ", per);
} }

Output: 1.500000 Output: 60.000000


/*No errors but wrong answer*/
Example-4
/* Find DA=40% of basic salary */

#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int basic=10000, da; float basic=10000.0, da;
da=40/100*basic; da=40/100*basic;
printf("%d ", da); printf("%f ", da);
} }

Output: 0 Output: 0.000000


/*No errors but wrong result*/ /*still wrong result*/
Example-4
/* Find DA=40% of basic salary */
#include<stdio.h>
void main()
{
float basic=10000, da;
da=40.0/100*basic; or da=(float)40/100*basic
printf("%f ", da);
}

Output: 4000.000000
Example-4
/* Find DA=40% of basic salary */

#include<stdio.h>
void main()
{
int basic=10000, da;
da=basic/100*40; or da=(basic/100)*40; or da=basic*0.4;
printf("%d ", da);
}

Output: 4000
Homework Questions
Write C programs for the following questions:
1. Find the area of a circle.
2. Enter the length and breadth of a rectangle and find the area.
3. Find the average of 3 entered numbers.
4. Enter the CGPA obtained by a student and find the equivalent
percentage of marks.
5. Swap the values of two variables using a third variable.
6. Swap the values of two variables without using a third variable.
7. Find the sum of the individual digits of any entered three-digit positive
number.
8. Enter the principal, time, and rate of interest. Calculate the simple
interest.
9. Convert any input temperature in Fahrenheit to Celsius.
10. Find the percentage of marks obtained by a student by entering the
marks secured by the student in 5 subjects. Consider the total mark in
each subject is 100.
Homework Questions Cont…
11. Calculate the gross salary of an employee by entering the basic salary.
DA is 42%, HRA is 30% of the basic salary and a fixed other allowance
(OA) of Rs. 2000. (Gross salary=Basic+DA+HRA+OA)
12. Convert an input total number of days into corresponding number of
years, months and remaining days. Consider 1 month=30 days.
(Example- Input days: 450 days; Output: 1 year, 2 months, 25 days
13. Input some quantity weight in grams and calculate the corresponding
weight in Kilograms and remaining grams (Example- Input weight:
1500 grams; Output: 1 KG 500 grams)
14. Input the time in seconds and calculate the corresponding hours, minutes,
and remaining seconds. (Exa: Input time in seconds: 3665; Output: 1
Hour 1 minute 5 seconds).
15. Calculate the distance between two points (x1, y1) and (x2, y2) for any
entered values of x1,y1 and x2, y2.
Homework Questions Cont…
16. Calculate area of a triangle by Herron’s method for any entered values
of a, b and c.
17. Print the size of various basic data types (char, int, float, double) in C.
18. Calculate the total bill to be paid by a customer entering the price of 3
products and their quantities. Include a 10% tax on total bill amount for
calculation of the amount to be paid by the customer.
19. Find the smallest number among three entered numbers using
conditional operator.
20. Enter the total price of some food order by a customer in a restaurant.
The restaurant charges a 12% GST on total amount. If the total amount
exceeds RS 1000, the restaurant offers a 5% discount. Otherwise no
discount is provided. Use conditional operator for discount calculation.
Print the final amount payable by the customer.
Module-II(Part-1):
Decision Making & Branching

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Decision Making and Branching
 Decision making is choosing
among alternates (branches).

Entry
 Why is it needed?

False
Test
 When alternative courses of
Expression?
action are possible and each
action may produce a
different result. True
Cont…
 C supports the following statements to support decision making:

1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement

 These statements control the flow of execution, therefore also called


control statements
1. The if statement
 The if statement is used to control the flow of execution of statements.

 It is a two-way decision statement and is used in conjunction with an


expression.
Decision Making with if Statement

General Form:
Entry

if (test expression) False


Test
Expression?

True
Different Forms of if Statement
(i) Simple if statement

(ii) if …. else statement

(iii) Nested if…else statement

(iv) else if ladder


(i) Simple if statement
 If the test expression is true statement block will be executed;
 otherwise the statement block will be skipped and the execution will
jump to statement x.

Entry

General form:
True
if (test expression) Test
Expression?
{
statement block Statement-block
False
}
Statement-x
Statement-x;

Next Statement
Example
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int marks=95; int marks=85;
if (marks>=90) if (marks>=90)
{ {
printf(“Outstanding Student\n”); printf(“Outstanding Student\n”);
} }
printf(“Good student”); printf(“Good student”);
} }

Output: Outstanding student Output: Good student


Good student
(ii) if-else statement
 If the test expression is true, the true General Form:
statement block will be executed; if (test expression) {
otherwise the false block statements true block statement (s)
are executed. }
else{
 In all cases either true block or false
false block statement (s);
block will be executed; not both.
}
Entry Statement-x;

True False
Test
Expression?

True block False block


Statements Statement

Statement-x
Example-1: Find greatest among 2
numbers
#include<stdio.h> #include<stdio.h>
void main() { void main() {
int a=20, b=10; int a=20, b=10;
if (a>b) if (a>b)
{ printf(“a is greater");
or
printf(“a is greater"); else
} printf(“b is greater");
else }
{
printf(“b is greater");
Output: a is greater
}
} Note: Multiple statements inside if/else block must be
included within { }
For single statements inside if/else { } is optional
Cont…

#include<stdio.h>
void main() {
int a=5, b=6;
if (a>b)
printf(“a is greater");
else Output:
printf(“b is greater"); b is greater
}
If case

Else case
Example-2: Check whether an entered
number is even or odd
#include<stdio.h>
void main()
{
int n;
printf(“Enter a number”);
scanf(“%d”, &n); If n=6
if (n%2==0) Output: Even number
printf(“Even number”);
else If n=5
If case
printf(“Odd number”); Output: Odd number

}
Else case
(iii) Nested if else statement
 When a series of decisions are involved more than one if else statement
may be used in nested form.

General Form:
if (test condition-1) {
if(test condition-2) {
Statement-1;
}
else {
Statement-2;
}
}
else {
Statement-3;
}
Statement-x;
Nested if else statement Cont…
Entry

True
False Test
Condition-1
?

Statement-3
True
False Test
Condition-2
?
Statement-2 Statement-1

Statement-x

Next Statement
Example-1: Find greatest among 3 numbers using nested-if
statement
#include<stdio.h>
void main(){ int a, b, c;
/*enter the values for a, b and c*/ printf(“Enter three numbers”);
scanf(“%d%d%d”.&a,&b,&c);
if (a>b)
{
If a=30 b=20 c=10
if(a>c) Output: a is greatest
printf(“a is greatest”);
else If a=30 b=20 c=40
printf(“c is greatest”); Output: c is greatest
}
else
{
If a=30 b=50 c=40
if(b>c) Output: b is greatest
printf(“b is greatest”);
Else case
else If a=30 b=50 c=60
printf(“c is greatest”); Output: c is greatest
}
Example-2: Check whether an entered number is positive,
negative number or zero using nested if statement
#include<stdio.h>
……
void main() {
if (num==0)
/*enter a number*/
{
if (num!=0)
printf(“Number is zero”);
{
or }
if(num>0)
else
printf( “Positive number”);
{
else
if(num>0)
printf(“Negative number”);
printf( “Positive number”);
}
else
else
printf(“Negative number”);
{
Else case }
printf(“Number is zero”);
}
}
(iv) The else if ladder
 Used when multipath decisions are involved.
 It‟s a chain of ifs in which the statement associated with each else is an if

General form:
if (test condition-1)
Statement-1;
else if (test condition-2)
Statement-2;
else if (test condition-3)
Statement-3;
….
else if (test condition-n)
Statement-n;
else
default statement;

Statement x;
The else if ladder Cont…
Entry

True False
Condition-
1

Statement-1 False
True Condition-
2

Statement-2 True False


Condition-
3

……
Statement-3
……

True False
Condition-
n

Statement-x Statement-n Default


Statement

Next Statement
Example
/*Check an entered number is positive, negative
or zero using else if ladder*/

#include<stdio.h>
void main()
{
//enter a number
if (num > 0)
printf(“Positive number");
else if(num < 0)
printf(“Negative number");
else
printf(“Number is zero”);
}
Example
/*Find greatest among 3 entered numbers
using else if ladder*/
#include<stdio.h>
void main()
{
//enter three number

if (a>b && a>c)


printf(“a is greatest”);
If case
else if(b>a && b>c)
printf(b is greatest”);
else
printf(“c is greatest”);
Else case
}
2. The switch Statement
 The complexity of if statement increases when the
number of alternatives increases.The program becomes
difficult to read and follow.

C provides another multi-way decision statement


„switch‟

 The switch statement tests the value of a given variable


(or expression) against a list of case values and
 when a match is found, a block of statements
associated with that case is executed.
switch(expression) { General form
case value-1:
block-1
break;
case value-2:
block-2
break;
…….
…….
default:
default block
break;
}
Statement-x;
Entry Cont…
Switch
expression

Expression=value-1
Block-1

Expression=value-2
Block-2

……
……
(no match) default
Default Block

Statement-x
void main(){ Example-1
int ch;
//enter a number from 1 to 7
switch(ch){
case 1:
printf(“Monday”);
break;
case 2:
printf(“Tuesday”);
break;

case 7:
printf(“Sunday”);
break;
default:
printf(“Invalid choice”);
break; } }
void main(){ Example-2
char ch;
//enter a small case alphabet a, e, i, o, u
switch(ch){
case ‘a’:
printf(“You entered vowel a”);
break;
case ‘e’:
printf(“You entered vowel e”);
break;
……
If case
case ‘u’:
printf(“You entered vowel u”);
break;
Else case
default:
printf(“Entered character is not a vowel”);
break; } }
3. The Conditional Operator
 Used for two way decision making.
 It‟s a ternary operator that takes 3 operands.
 A ternary operator pair “ ? : ” is available in C to construct conditional
expressions of the form:

expr1 ? expr2 : expr3

 The expression expr1 is evaluated first.


 If it is non-zero (true), then the expression expr2 is evaluated, and that
is the value of the conditional expression.
 Otherwise expr3 is evaluated, and that is the value.

 Only one of expr2 and expr3 is evaluated.


Example-1
max = (a > b) ? a : b;

If a=20, b=10
Then value of max=20

If a=10, b=30
Then value of max=30
Example-2
if (x<0)
flag=0;
else
flag=1;

can be written using conditional operator:


flag=(x<0) ? 0 : 1;
4. The goto Statement
 The „goto‟ statement is used for unconditional branching from one part
of the program to another part.
 However, goto statements must be avoided in a highly structured
program.
 The goto statement requires a label in order to identify the place where
the branch is to be made.

General form:
label:
goto label;
statement;
.....
.....
....
....
label:
goto label;
statement;
Forward jump Backward jump
Example-1
/*Find the square root of any positive number. If the user enters a negative
number it will ask the user to to enter a positive number again*/
main()
{
int x, y;
read:
printf(“Enter a positive number”);
scanf(“%d”, &x);
if(x<0)
goto read;
y=sqrt(x);
printf(“The square root of %d is %d\n”, x, y);
}
Example-2
/*Find the square root of a series of positive number. If the user enters a
negative number it will ask the user to to enter a positive number
again*/
main()
{
int x, y;
read:
printf(“Enter a positive number”);
scanf(“%d”, &x);
if(x<0)
goto read;
y=sqrt(x);
printf (“The square root of %d is %d\n”, x, y);
goto read;
}
Questions to Practice
Write C programs for the following questions:
1. Find greatest among two entered numbers.
2. Check whether an entered number is even or odd.
3. Check whether an entered character is a vowel or not.
4. Check whether an entered number is divisible by 3 and 5.
5. Check whether an entered year is a leap year or not.
6. Check whether any entered number is positive, negative or zero using
nested if-else statement
7. Check whether two entered numbers are equal or the first number is
greater than the second number or the second number is greater than the
first number using nested if-else statement.
8. Find greatest among 3 entered numbers using nested if-else statement.
9. Find smallest among three entered numbers using else if ladder. Use
logical AND operator to combine multiple conditions.
10. Enter the cost price and selling price of a product and check profit or
loss. Also, print the percentage of loss or profit for the product.
Cont…
11. Enter mark obtained by a student in a subject and print the respective
grade using else-if ladder statement. Consider the following grading system:
Score out of 100 Marks Grade
90 & above up to 100 O
80 & above but less than 90 E
70 & above but less than 80 A
60 & above but less than 70 B
50 & above but less than 60 C
40 & above but less than 50 D
Less than 40 or Absent in Exam U

12.Compute the real roots of a quadratic equation ax2 + bx + c=0 (given a, b


and c) for the following conditions:
i) No solution, if both a and b are zero.
ii) Only one root if determinant (b2 - 4ac)=0
iii) No real roots if b2 - 4ac < 0
iv) Otherwise there are 2 real roots
Cont…
13. Calculate the income tax payable by a person by entering the total
taxable income as per the below slabs:
Taxable Income range (in RS) Tax%
0 – 3,00000 0
3,00001 – 7,00000 5
7,00001- 10,00000 10
10,00001- 12,00000 15
12,00001 – 15,00000 20
Greater than 15,00000 30

14. Calculate the age of a person, given date of birth (DOB) and current date
(CD). A date is represented as three integers (say dd, mm, and yyyy). The
result to be printed as YY years, MM months, DD days. Consider a month
consist of 30 days.
` Example: Input DOB: 29/10/1980, CD: 27/8/2011
Output: Age: 30 years 9 Months and 28 days
Cont…
15. Enter the total purchase amount for a customer and calculate the amount
payable by the customer after discount, if a shopping mall announced the
following discounts on total purchase amount:
Purchase amount (RS) Discount
< 1000 -
1000-3000 5%
3001-6000 7%
6001-10000 10%
Above 10000 Rs 2000

16. Enter the previous month and current month meter reading. Calculate the
electric bill amount for any customer as per the following rules:
First 100 units : Rs 3.20 per unit.
Next 200 units : Rs 5.40 per unit.
Remaining units : Rs 6 per unit
Cont…
17. Given a number between 1 to 7, print the day name (Monday- Sunday)
using switch-case statement.

18. Given a number 0-9, print the corresponding English word for the
number using switch-case statement.

19. Check whether an entered character is a vowel or not using switch-case


statement.

20. Create a menu-driven program using switch–case statement that will ask
the user to enter two numbers and an operator (+, -, *, /). When the user
enters a valid choice, the program prints the result of the respective
operation as per the entered choice, otherwise prints an error message.
Module-2(Part-2):
Loops

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Decision Making and Looping
 In looping a sequence of statements are executed until some
conditions for termination of the loop are satisfied.
 A program loop consist of 2 segments: body of the loop and
control statement.

 The control statement tests certain conditions and then directs


the repeated execution of the statements contained in the body of
the loop.
 Depending on the position of the control statement in the loop, a
control structure is classified as:
 Entry-controlled loop
or
 Exit-controlled loop.
Entry-controlled Vs. Exit-controlled Loop
Entry-controlled loop Exit-controlled loop
 In the entry controlled loop, the  In the exit-controlled loop, the test is
control conditions are tested before the performed at the end of the body of
start of the loop execution. If the the loop; therefore, the body is
conditions are not satisfied, then the executed unconditionally for the
body of the loop will not be executed. first time.
 This is also called pre-test loop.  This is also called post-test loop
 The while and for loop are entry-  The do-while loop is exit-controlled
controlled loops. loop Entry
Entry

Body of the loop


Test
False
condition
?
True
Test
True condition
?
Body of the loop
False
Sentinel Loops
 Based on the nature of control variable and the kind of value
assigned to it for testing the control expression, the loops may be
classified into 2 types:

1. Counter-controlled loops
2. Sentinel-controlled loops
1. Counter-controlled loops
 When we know in advance exactly how many times the loop will
be executed, the counter controlled loops are used.

 Here a control variable is used known as counter.


 The counter must be initialized, tested and updated for the desired
loop operations.

 It is also called definite repetition loop.

Example: Printing numbers between 1 to 10: loop will execute 10


times then stop
2. Sentinel-controlled loops
 A special value called sentinel value is used to change the loop
control expression from true to false.

 This is also called indefinite repetition loop as the number of


repetitions is not known before the loop begins executing.

 For example, when reading data, the end of data may be indicated
by a special value -1
Loops
 The C language provides 3 constructs for performing loop
operations:

1. The while statement

2. The do statement

3. The for statement


The while Statement
 The while loop is an entry-controlled loop.
 The test condition is evaluated first, if the condition is true then
only the loop body will be executed.

 After execution of the body, the test condition is again evaluated,


if it is false the loop will terminate, otherwise it will continue till
the test condition is false.
Entry

General format: False


Test
while(test condition) condition
?

{ True
Body of the loop
Body of the loop
}
Example-1
//Print first n natural numbers using while loop
If n=10:
#include<stdio.h>
void main() Output:
1
{ 2
int n, i; 3
4
printf(“Enter a number”); 5
scanf(“%d”,&n); 6
/* initialization*/ 7
i=1; 8
while(i<=n) /*Condition Checking*/ 9
10
{
printf(“%d \n”, i);
i++; /* Increment/decrement*/
}
}
Example-2
//Print first n natural numbers in reverse order using while loop
#include<stdio.h>
If n=10:
void main()
Output:
{ 10
int n, i; 9
8
printf(“Enter a number”); 7
scanf(“%d”,&n); 6
/* initialization*/ 5
i=n; 4
while(i>=1) /*Condition Checking*/ 3
2
{ 1
printf(“%d \n”, i);
i--; /* Increment/decrement*/
}
}
Example-3
//Print the natural numbers in a range using while loop
#include<stdio.h>
If m=10
void main() n=20
{ Output:
int m, n, i; 10
11
printf(“Enter the starting and ending range”); 12
scanf(“%d%d”,&m,&n); 13
14
i=m; 15
while(i<=n) 16
17
{ 18
printf(“%d \n”, i); 19
20
i++;
}
}
Example-4
//Print the number table of any user entered number
#include<stdio.h>
void main()
{ If num=2
int num,i; Output:
//Enter a number 2 * 1=2
2 * 2 =4
i=1; ….
while(i<=10) ….
2 * 10 = 20
{
printf(“%d * %d =%d”, num, i, num*i);
i++;
}
}
Example-5
//Find sum of first n natural numbers using while loop
#include<stdio.h>
void main()
int n, i, sum=0; If n=5
printf(“Enter a number”); Output:
scanf(“%d”,&n); 15
i=1;
while(i<=n)
{
sum=sum+i;
i++;
}
printf(“sum of first n natural numbers is: %d \n”, sum);
}
Example-6
//Find sum of digits of a number
#include<stdio.h>
void main()
{ If num=123
int num, rem, sum=0; Output:
//Enter a number 6
while(num!=0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
//print the sum result
}
Example-7
//convert a binary number to decimal
void main(){
int n;
int dec=0,d; If n=101

//Enter a binary number Output:


while(n!=0) 5
{
d = n % 10;
dec=dec+d*pow(2,i);
n=n/10;
}
//print the decimal number
}
Note: Fill the missing lines as discussed in the class
Example-8
//convert decimal to binary number
void main(){
int bin=0, rem, i = 1,n;
//Enter a decimal number If n=5

while (n != 0) Output:
{ 101
rem = n % 2;
n =n/2;
bin=bin + rem * i;
i= i* 10;
}
//print the binary number
}
The do Statement
 The do-while loop is an exit-controlled loop.
 Here the body of the loop is executed first and then the test condition is
checked.
 If the test condition is true then the body will continue for the next
iteration, otherwise the loop will terminate.

 The do-while loop will execute at least once even if the test condition is
false.
Entry

General format:
Body of the loop
do
{
True
Body of the loop Test
condition
?
} while(test condition);
False
Example-1
Print first n natural numbers using do-while loop

If n=10
#include<stdio.h>
void main() Output:
{ 1
2
int n,i; 3
//Enter a number 4
5
i=1; 6
do{ 7
8
printf(“%d \n”, i); 9
i++; 10
} while(i<=n);

}
Homework Questions
1. Find Fibonacci series up to an entered number using do-while loop.
Test data: Entered number=90
Output series: 0 1 1 2 3 5 8 13 21 34 55 89

2. Find the sum of all user entered numbers until the sum exceeds 100
using do-while loop.
The for Statement
 The for loop is an entry-controlled loop that provides a more
concise loop control structure

General format:
for(initialization; test_condition; increment)
{
Body of the loop
}

 Note: In place of increment, decrement statements can be written


based on program requirements
Example-1
Print first n natural numbers using for loop
#include<stdio.h> If n=10:
void main()
Output:
{ 1
int n,i; 2
3
//Enter a number 4
for(i=1;i<=n;i++) 5
6
{ 7
8
printf(“%d \n”, i); 9
} 10

}
Example-2
Print first n natural numbers in descending order using for loop
#include<stdio.h> If n=10:
void main()
Output:
{ 10
int n,i; 9
8
//Enter a number 7
for(i=n;i>=1;i--) 6
5
{ 4
3
printf(“%d \n”, i); 2
} 1

}
Example-3
Print numbers in a range
#include<stdio.h> If m=10, n=20
void main()
Output:
{ 10
11
int m, n, i; 12
//Enter starting and ending range in variables m and n 13
14
for(i=m;i<=n;i++) 15
16
{ 17
printf(“%d \n”, i); 18
19
} 20

}
Example-4
//Find sum of first n natural numbers
#include<stdio.h>
void main()
If n=5
{
int num, i, sum=0; Output:
15
/*Enter a number*/

for(i=1; i<=num; i++)


{
sum=sum+i;
}
//print the sum result
}
Example-5
//Find factorial of a number
#include<stdio.h>
void main()
If n=5
{
int num, i, fact=1; Output:
120
/*Enter a number*/

for(i=1;i<=num;i++)
{
fact=fact*i;
}
//print the factorial result
}
Example-6
//Print all even numbers in a range
#include<stdio.h>
void main()
If m=10, n=20
{
int m, n,i; Output:
10
//Enter the starting and ending range 12
for(i=m;i<=n;i++) 14
16
{ 18
20
if(i%2==0)
printf(“%d\n”, i);
}

}
Example-6
//Print all numbers divisible by 3 and 5 in a range
#include<stdio.h>
void main()
If m=10, n=50
{
int m, n,i; Output:
15
//Enter the starting and ending range 30
for(i=m;i<=n;i++) 45

{
if(i%3==0 && i%5==0)
printf(“%d\n”, i);
}
}
Additional Features of for Loop
1. More than one variable can be initialized at a time in the for
statement

Example:
p=1;
for(i=0;i<20;i++)

Can be written as:


for(p=1,i=0; i<20;i++)

//the initialization section has 2 parts: p=1 and i=0 separated by a comma
Cont…
2. The increment section may also have more than one part separated
by a comma

Example:

for(p=1,i=0;i<20; p++,i++)
Cont…
3. The test condition section may also have any compound relation
and the testing need not be limited only to the loop control
variable

Example:
sum=0;
for(i=1; i<20 && sum<100; i++)
{
sum=sum+i;
printf(“%d %d\n”, i,sum);
}
Cont…
4. One or more sub sections can be omitted if necessary

Example:
m=0;
for( ; m!=100 ; )
{
printf(“%d \n”, m);
m=m+5;
}
Example-7
//Check a number is prime or not
void main(){ If n=5
int n, i, flag=0; Prime number

//enter a number If n=9


Not a prime number
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
Example-8
//GCD of 2 numbers
void main(){
int n1, n2, i, gcd;
//enter 2 numbers If n1=10, n2=20
GCD=10
for(i=1; i <= n1 && i <= n2; i++)
{ If n1=5, n2=7
GCD=1
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
Example Programs
/* Check whether a number is palindrome or not*/
#include <stdio.h>
void main()
{
int n, rev=0,rem, num;
printf("Enter a number: ");
If n=121
scanf("%d",&n); Palindrome
num=n;
while (n != 0) If n=123
{ Not palindrome
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if (num==rev)
printf("%d is a palindrome number", num);
else
printf("%d is not a palindrome number", num);
}
/* Check whether a number is armstrong number of 3 digit or not*/
#include <stdio.h>
void main() If n=153
{ 13+53+33=153=n
int n, num, rem, sum=0; =>Armstrong number
printf("Enter a number ");
scanf("%d", &n); If n=123,
13+23+33=36 ≠ n
num=n;
=> Not Armstrong number
while(n!=0) {
rem= n%10;
sum=sum + (rem* rem * rem);
n=n/10;
}
if (sum == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
}
Logic to find number of digits of any number

int d=0;
while(n!=0)
{
n=n/10;
d++;

printf("%d\n", d);
/*Check whether a number is armstrong number or not (any digit)*/
#include <stdio.h>
int main(){ If n=8208
int n, num, rem, sum=0; 84+24+0+84=8208=n
//enter a number =>Armstrong number
num=n;
//find number of digits If n=8201,
84+24+0+14=4113 ≠ n
while(n!=0)
=> Not Armstrong number
{
rem= n%10;
sum=sum + pow(rem,d);
n=n/10;
}
if (sum == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;}
Module-2(Part-3):
Nested Loops

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Nested Loops
 The loops may be nested within another
loop

Example:

for(i=1;i<=5;i++) //Outer loop


{
for(j=1;j<=3;j++) //Inner loop
{
…..
}
}
Example
for(j=1;j<=3;j++)
Output:
{
printf(“* ”); ***

}
for(i=1;i<=5;i++)
{
Output:
} * * * will be printed
for 5 times

Output:
***************
Example-1

for(i=1; i<=5;i++)
Output:
{
*****
for( j=1;j<=5; j++) *****
{ *****
printf(“* ”); *****
} *****
printf(“\n”);
}
Jumping out of a Loop
break:
 When the break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement
immediately following the loop.

 When the loops are nested, the break would only exit from the loop
containing it. i.e. the break will exit only a single loop.
Example:
for(…) {
for(….) {
while(…) { …..
….. if (…..)
if (…..) break;
Exit from …..
break;
Exit inner loop ….
…..
from }//end of inner loop
….
the loop ……..
}
…..
} //end of outer loop
Skipping a part of a Loop
continue
 The continue statement causes the loop to be continued with the next
iteration after skipping any statements in between.
Example:
while (test condition)
{
…..
if(condition)
continue;
…..
statement-x
}
 If the condition in if is true the loop will continue with next iteration
skipping the lines below the continue statement till statement-x.
Example
/* Print all natural numbers in descending order up to 1 from an
entered number except the numbers divisible by 7 (use continue
statement) */
If n=15
Outut:
void main(){ 15 13 12 11 10 9 8 6 5 4 3 2 1
int n, i;
//enter the value of n
for (i = n; i >=1; i--) {
if (i % 7 == 0) {
continue;
}
printf("%d \t", i);
}
}
Printing Patterns using Nested Loops
Example-2

If rows=3, cols=5
for(i=1; i<=rows;i++)
{
for( j=1;j<=cols; j++) Output:
{ *****
printf(“* ”); *****
} *****
printf(“\n”);
}
Example-3

for(i=1; i<=3;i++)
Output:
{
11111
for( j=1;j<=5; j++)
22222
{
33333
printf(“%d ”,i);
}
printf(“\n”);
}
Example-4

for(i=1; i<=3;i++) Output:


{ 12345
for( j=1;j<=5; j++) 12345
{ 12345
printf(“%d ”,j);
}
printf(“\n”);
}
Example-5
aaaaa
bbbbb
ccccc
ddddd
eeeee

Alphabet: ASCII code:


A 65
a 97
ASCII Table
Example for char data type
Output:
Example-1:
65
#include <stdio.h>
main(){
printf(“%d”, 65);
}

Example-2:
#include <stdio.h>
Output:
main(){ A
printf(“%c”, 65);
}
Example for char data type

Example-3:
#include <stdio.h> Output:
main(){ a
printf(“%c”, 97);
}
Cont…
Example-4
#include <stdio.h>
Output:
main(){
a
char ch='a';
printf("%c", ch);

}
Example-5
#include <stdio.h>
main(){ Output:
char ch='a'; 97
printf(“%d", ch);
}
Example-5
Output:
for(i=1; i<=rows;i++)
aaaaa
{
bbbbb
for( j=1;j<=cols; j++)
ccccc
{
ddddd
printf(“ %c ”, i+96);
eeeee
}
printf(“\n”); Alphabet: ASCII code:
a 97
}
Example-6: Homework

Output:
Alphabet: ASCII code: AAAAA
A 65 BBBBB
CCCCC
DDDDD
E E E EE
Example-7

for(i=1; i<=5;i++) Output:


{ *
for( j=1;j<=i; j++) **
{ ***
printf(“ * ” ); ****
} *****
printf(“\n”);
}
Homework Questions
Example-8 Example-9 Example-10
1 A
1
22 BB
12
333 CCC
123 DDDD
4444
1234 EEEE E
55555
12345
Example-11
for(i=1; i<=rows; i++) Output:
{ A
for(j=1; j<=i; j++) AB
ABC
{ ABCD
printf("%c ", j+64);

}
printf("\n");
}
Example-12
for(i=1; i<=rows; i++)
{ Output:
for(j=1; j<=i; j++) 1
{ 00
if(i % 2 != 0) 111
printf("1 "); 0000
else 11111
printf("0 ");
}
printf("\n");
}
Example-13

for(i=1; i<=row; i++) Output:


{
1
for(j=1; j<=2*i-1; j++)
{ 123
printf("%d ", j); 12345
}
printf("\n");
}
Example-14
for(i=5; i>=1;i--)
Output:
{
*****
for( j=1;j<=i; j++)
****
{
***
printf(“ * ”);
**
}
*
printf(“\n”);
}
Homework Questions

Example-15 Example-16
55555
12345
4444
1234
333
123
22
12
1
1
m=1 Example-17
for(i=5; i>=1;i--)
{ ----*
for( j=1;j<=i-1; j++){ ---**
printf(“ ”); --***
} -****
for(k=1;k<=m; k++){ *****
printf(“* ”);
}
printf(“\n”);
m++;
}
m=row
for(i=1; i<=5;i++)
Example-18
{
for( j=1;j<=i-1; j++) { Output:
printf(“ ”); * * * * *
} * * * *
* * *
for(k=1;k<=m; k++) {
* *
printf(“* “);
*
}
printf(“\n”);
m--;
}
m=row Example-19
for(i=1; i<=row;i++)
{
for( j=1;j<=m-1; j++) { Output:
printf(“ ”); *
} ***
for(k=1;k<=2*i-1; k++) { * * * * *
printf(“* “);
}
printf(“\n”);
m--;
}
m=1
Example-20
for(i=row; i>=1;i--)
{
for( j=1;j<m; j++){
printf(“ ”); Output:
} * * * * *
for(k=1;k<=2*i-1; k++) { * * *
printf(“* “); *
}
printf(“\n”);
m++;
}
for(i=1;i<=row;i++)
{
Example-21
for(j=1;j<=row-i;j++){
printf(" ");
} Output:
for(j=1;j<=i; j++) { 1
printf("%d", j);
121
}
for(j=i-1;j>=1;j--) { 12321
printf("%d", j);
}
printf("\n");
}
More programs on Nested Loop
//Check a number is prime or not
void main(){
int n, i, flag=0;
for (i = 2; i <= n / 2; i++)
{
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
Print Prime numbers in a range
//Enter the starting and ending range in num1 and num2
for (i = num1; i <= num2; i++)
{

flag = 0;

//prime number testing logic

if (flag == 0)
{
printf("%d\n", i);
}
}
Print Prime numbers in a range
//Enter the starting and ending range in num1 and num2
for (i = num1; i <= num2; i++)
{
flag = 0;
for (j = 2; j <= i/2; j++)
{
if ((i % j) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
printf("%d\n", i);
}
}
//Check whether a number is palindrome or not
#include <stdio.h>
int main()
{
int n, rev=0,rem, num;
printf("Enter a number: ");
scanf("%d",&n);
num=n;
while (n != 0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if (num==rev)
printf("%d is a palindrome number", num);
else
printf("%d is not a palindrome number", num);
return 0; }
Print all palindrome numbers within a given range.
int n, i,num1,num2, rev, rem;

//Enter the range in num1 and num2

for(i=num1;i<=num2;i++)
{
n=i;
rev=0;
//logic for finding reverse of a number

if (i==rev)
printf("%d ", i);
}
Print all palindrome numbers within a given range.
int n, i,num1,num2, rev, rem;
//Enter the range in num1 and num2
for(i=num1;i<=num2;i++)
{
n=i;
rev=0;
while (n != 0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if (i==rev)
printf("%d ", i);
}
Print all armstrong numbers within a given range.

//Enter the range in n1 and n2


for(i=n1;i<=n2;i++)
{
n=i;
sum=0;
//logic to find sum of cube of digits of the number

if (sum == i)
printf("%d\n", i);
}
Print all armstrong numbers within a given range.
//Enter the range in n1 and n2
for(i=n1;i<=n2;i++)
{
n=i;
sum=0;
while(n!=0)
{
rem= n%10;
sum=sum + (rem* rem * rem);
n=n/10;
}
if (sum == i)
printf("%d\n", i);
}
Module-3 (Part-I):
Array

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Introduction
 The variables of char, int, float and double type can store only one
value at a given time.

 Those can be used to handle limited amount of data.

 However, in many applications we need to handle a large volume of data


in terms of reading, processing and printing.

Example:
 List of temperature values recorded every hour in a day, month or year
 List of employees in an organization
 List of products and their price
 Marks of student of a class, etc
Data Types
 3 classes of data types available in c:

1. Primitive or fundamental data types


2. Derived data types
3. User defined data types
Array
 An array is a fixed size sequenced collection of elements of the same
data type.

 An array is a collection of items stored at contiguous memory


locations.

 The idea is to store multiple items of the same type together with a
single name.

 Arrays can be used to represent simple list of values, table of data in


two, three or more dimensions:
 One-dimensional array
 Two dimensional array
 Multidimensional arrays
One-dimensional Array
 A list of items can be given one variable name

 Example: finding average of n numbers

avg= (n1+n2+n3+….)/n

Can declare an array of size n that can hold all numbers under one name
Declaration of 1D Array
General form:
type variable_name[size];

Example:
int num[10];
//array num can store 10 values of integer type

float marks[20];
//array marks can store 20 values of float type

char name[30];
//array name can store a string of maximum 30 characters
1D Array Index
Example:
int a[10];
size-1

0 1 2 3 4 5 6 7 8 9

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Initialization of 1D Array
 After an array is declared, its elements must be initialized, otherwise
they will contain garbage values.

 An array can be initialized:

 At Compile time
 At run time
Example: Compile time initialization

Variable initialization: Array initialization:


int a=10; int arr[5]={1,2,3,4,5};

float f =1.5; float b[3]={1.5, 3.4, 2.6};

char ch=„C‟; char c[7]={„W‟, „E‟, „L‟, ‟C‟, „O‟, „M‟, „E‟};

or
char c[7]= “Welcome”;
Accessing Array Elements
Example:
int a[5]; 0 1 2 3 4

a[0] a[1] a[2] a[3] a[4]

Example:
int a[5]={10,20,30,40,50}; 0 1 2 3 4

a 10 20 30 40 50
a[0] contains the value 10
….
a[0] a[1] a[2] a[3] a[4]
a[4] contains the value 50
Displaying Array Elements
#include<stdio.h>
main()
{
int a[5]={10,20,30,40,50};
printf(“%d”, a[0]);
0 1 2 3 4
}
a 10 20 30 40 50

Output: a[0] a[1] a[2] a[3] a[4]

10
Cont…
#include<stdio.h>
main()
{
int a[5]={10,20,30,40,50};
printf(“%d \t”, a[0]); 0 1 2 3 4
printf(“%d \t”, a[1]);
a 10 20 30 40 50
printf(“%d \t”, a[2]);
printf(“%d \t”, a[3]);
a[0] a[1] a[2] a[3] a[4]
printf(“%d \t”, a[4]);
}

Output:
10 20 30 40 50
Displaying Array elements using loop
#include<stdio.h>
main()
{
int i;
int a[5]={10,20,30,40,50}; 0 1 2 3 4
for(i=0;i<5;i++) a 10 20 30 40 50
{
printf(“%d \t”, a[i]); a[0] a[1] a[2] a[3] a[4]
a[i]
}
}

Output:
10 20 30 40 50
Run time initialization
Example: Run time initialization

Variable initialization: Array initialization:


int a; int a[5];
for(i=0,i<5;i++)
scanf(“%d”, &a); {
scanf(“%d”, &a[i]);
}
0 1 2 3 4
a
a

a[i] a[0] a[1] a[2] a[3] a[4]


Example-1
//Enter 5 elements into an array and display them
#include<stdio.h>
void main()
{
int i;
int a[5];
0 1 2 3 4

printf(“Enter the array elements: \n”); a


for(i=0;i<5;i++)
{ a[i] a[0] a[1] a[2] a[3] a[4]
scanf(“%d”, &a[i]);
}
Cont…
printf(“The array elements are \n”);
for(i=0;i<5;i++)
{
0 1 2 3 4
printf(“%d \t”, a[i]);
a
}
}
a[i] a[0] a[1] a[2] a[3] a[4]
Example-2
//Logic for sum of all array elements

sum=0;
for(i=0;i<5;i++)
{ 0 1 2 3 4
sum=sum+a[i]; a 10 20 30 40 50
}
a[i] a[0] a[1] a[2] a[3] a[4]

Output:
150
Program
//Find sum of all array elements
#include<stdio.h>
main()
{
int i, sum=0;
int a[5];

printf(“Enter the array elements: \n”);


for(i=0;i<5;i++)
{
scanf(“%d”, &a[i]);
}
Cont…
for(i=0;i<5;i++)
{
sum=sum+ a[i];
}

printf(“The sum of the array elements are: %d\n”, sum);


}
Example-3
//Find average of all array elements

Logic:
sum=0;
0 1 2 3 4
for(i=0;i<5;i++)
{ a 10 20 30 40 50

sum=sum+a[i];
} a[i] a[0] a[1] a[2] a[3] a[4]
avg=sum/5;

Output: 30
Example-4
//Find element wise addition results of two one dimensional arrays

Input: a 5 10 15 20 25

b 1 2 3 4 5

Output:
c 6 12 18 24 30
Program
#include<stdio.h>
main()
{
int i;
int a[5], b[5],c[5];

printf(“Enter the elements of the first array: \n”);


for(i=0;i<5;i++)
{
scanf(“%d”, &a[i]);
}
Cont…
printf(“Enter the elements of the second array: \n”);
for(i=0;i<5;i++)
{
scanf(“%d”, &b[i]);
}
for(i=0;i<5;i++)
{
c[i]=a[i]+b[i];
}
printf(“The element wise addition results of the two arrays is:\n”);
for(i=0;i<5;i++)
{
printf(“%d \t”, c[i]);
}
}
Example-5
//Print all even numbers present in the array.

Logic:
for(i=0;i<5;i++)
{ 0 1 2 3 4
if(a[i]%2==0) a 3 4 6 7 8
{
printf(“%d \t”, a[i]);
}
}
Example-6
//Find the largest element in an array

Logic:
int max=a[0];
for(i=1;i<5;i++)
0 1 2 3 4
{
if(a[i]> max)
a 3 4 6 7 8

{
max=a[i];
}
}
//print max
Example-7
Find the smallest element in an array

int min=a[0];
for(i=1;i<5;i++)
{ 0 1 2 3 4
if(a[i]< min) a 3 4 6 7 8
{
min=a[i];
}

}
//print min
Example-8
Search whether an element is present in an array

Input:
Array
an Element 0 1 2 3 4
a 3 4 6 7 8
Output:
Element Present
or
Element not present
Example Code
//Search whether an element is present in an array
void main()
{
int a[5];
int ele; 0 1 2 3 4
int c=0; a 3 4 6 7 8
//Enter the array elements
//Enter the element to be searched
for(i=0;i<5;i++){
if(a[i]==ele) {
c=1;
break;
}
}
Cont…
if(c==1)
print(“Element is present”);
else
printf(“Element is not present”

}
Example Code for runtime entry of
array elements
int a[5];

printf(“Enter the array elements: \n”);


for(i=0;i<5;i++)
{ 0 1 2 3 4
scanf(“%d”, &a[i]); a
}

a[i] a[0] a[1] a[2] a[3] a[4]


Example Code for runtime entry of
Partially filled Array
int a[10];
int n; //let n=5
printf(“Enter the number of elements you want to enter into the array
\n”);
scanf(“%d”,&n);

printf(“Enter the array elements: \n”);


for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
0 1 2 3 4 5 6 7 8 9
a 33 44 66 77 88
Inserting an Element into an Array
Input:
0 1 2 3 4 5 6 7 8 9

a 33 44 66 77 88

element 55
position 2

Output:

0 1 2 3 4 5
a 33 44 55 66 77 88
Cont…

Input: 0 1 2 3 4
a 33 44 66 77 88

element 55
position 2

Logic:
pos i i+1
0 1 2 3 4 5 6 7 8 9
a 33 44 66 77 88
pos
Example
i i+1
Input:
0 1 2 3 4 5 6 7 8 9
a 33 44 66 77 88

55
a[i+1]=a[i]
i
0 1 2 3 4 5 6 7 8 9
a 33 44 66 77 88 88

i
0 1 2 3 4 5 6 7 8 9
a 33 44 66 77 77 88

pos
0 1 2 3 4 5 6 7 8 9
a 33 44 66 66 77 88 a[pos]=ele
55
Sample Code

pos i i+1
0 1 2 3 4
for(i=n-1;i>=pos;i--)
{ a 33 44 66 77 88
a[i+1]=a[i]; n-1
}
a[pos]= ele;
0 1 2 3 4 5
n=n+1
a 33 44 55 66 77 88

n-1

//n is the number of elements entered in array a


Deleting an Element from the Array
Input: 0 1 2 3 4
An array a 33 44 66 77 88
position of the element to be deleted pos

Output:
0 1 2 3 4 5
Updated array
a 35 44 77 88
Logic
pos n-1
0 1 2 3 4
a 33 44 66 77 88

n-1
0 1 2 3 4 5
a 35 44 77 88
Sample Code

i i+1
//enter the position from which you want to delete 0 1 2 3 4

for (i = pos ; i < n; i++) a 33 44 66 77 88

{ n-1
arr[i] = arr[i+1]; pos
}

n=n-1;
0 1 2 3 4 5
a 33 44 77 88
Sort the Elements of the Array in
Ascending Order
Input:
0 1 2 3 4
a 55 44 88 11 22

Output:
0 1 2 3 4
a 11 22 44 55 88
Example Code i=0:
//enter an array i
0 1 2 3 4
for (i = 0; i < n; i++) a 55 44 88 11 22
{ j
for (j = i + 1; j < n; j++) i
{ 0 1 2 3 4
if (a[i] > a[j]) a 44 55 88 11 22
{
j
temp = a[i]; i
a[i] = a[j]; 0 1 2 3 4
a[j] = temp; a 44 55 88 11 22
}
j
}
i
} 0 1 2 3 4

//print the sorted array „a‟ a 11 55 88 44 22


j
i=1:
Cont…
i i=2:
0 1 2 3 4
i
a 11 55 88 44 22 0 1 2 3 4
j a 11 22 88 55 44
i j
0 1 2 3 4
i
a 11 55 88 44 22 0 1 2 3 4
j a 11 22 55 88 44
i
j
0 1 2 3 4 i
0 1 2 3 4
a 11 44 88 55 22
j
a 11 22 44 88 55

i j
0 1 2 3 4
a 11 22 88 55 44
j
Cont…
i=3:

i
0 1 2 3 4
a 11 22 44 88 55
j

i
0 1 2 3 4
a 11 22 44 55 88
j
i=4:
i
0 1 2 3 4
a 11 22 44 55 88 Sorted Array
j
Sample Code for Bubble Sort
i
//Array sorting in ascending order
0 1 2 3 4

for (i = 0 ; i < n - 1; i++) a 55 44 88 11 22


{ j

for (j = 0 ; j < n - i- 1; j++) a 44 55 88 11 22


{
j
if (a[j] > a[j+1])
{ a 44 55 88 11 22
j
temp = a[j];
a[j] = a[j+1]; a 44 55 11 88 22
a[j+1] = temp; j
}
} a 44 55 11 22 88

//Continue same inner loop iteration for i=1, 2, 3


i=1:
Cont…
i
0 1 2 3 4

a 44 55 11 22 88
j

a 44 55 11 22 88
j

a 44 11 55 22 88
j

a 44 11 22 55 88
Cont…
i=2:
i=3:
i
0 1 2 3 4 i
0 1 2 3 4
a 44 11 22 55 88
a 11 22 44 55 88
j
j
a 11 44 22 55 88
j a 11 22 44 55 88
j
a 11 22 44 55 88

i=4: loop terminates

a 11 22 44 55 88

Sorted Array
Merge two arrays
Input: 0 1 2 3 4
a 11 22 33 44 55 size=m

0 1 2 3
b 66 77 88 99 size=n

Output: 0 1 2 3 4 5 6 7 8
c 11 22 33 44 55 66 77 88 99 size=m+n
Logic for Merging 2 Arrays
for (i = 0 ; i < m ; i++)
{
c[i]=a[i];
}

for(j=0;j<n;j++)
{
c[i]=b[j];
i++;
}

for(i=0;i<m+n;i++)
{
printf(“%d\t”,c[i]);
}
Homework Questions
Write C programs for the following:

1. Search whether an element is present in an array or not. Also, print the


array index where the element is present.
2. Sort the elements of an array in descending order.
3. Reverse the array elements
4. Count how many times a particular element is present in an array
5. Count how many even numbers are present in an array
Two-dimensional Arrays
Two-dimensional array
 A table of values can be given one variable name

 Example: Marks obtained by 60 students in 3 subjects

 We can declare a two dimensional array (Matrix) of size 60 × 3 that can


hold all numbers under one name

 The table contains 180 values under one variable name


Declaration of 2D Array
General form:
type variable_name[row_size] [column_size] ;

Example:
int a[3][3];
//2D array „a‟ can store 9 values of integer type

col
rows 0 1 2
0
a 1

2
Compile time Initialization
int a[3][3]={1,2,3,4,5,6,7,8,9};

or

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

or

int a[3][3]={ {1,2,3},


{4,5,6},
{7,8,9}
};
2D Array Index and Accessing
Elements
Example:
int a[3][3];
//2D array „a‟ can store 9 values of integer type and each value
can be accessed by its row and column number:

0 1 2
0 a[0][1]
a 1

2 a[2][2]
a[0][0]

Row no. Col. no.


Displaying 2D Array elements
#include<stdio.h>
main()
col
{
rows 0 1
int a[2][2]={10,20},{30,40}};
0 10 20
printf(“%d \t”, a[0][0]);
a 30 40
printf(“%d \t”, a[0][1]); 1
printf(“%d \t”, a[1][0]);
printf(“%d \t”, a[1][1]);
}
Output: 10 20 20 40
Displaying 2D Array elements
#include<stdio.h>
main()
col
{
rows 0 1
int a[2][2]={10,20},{30,40}};
0 10 20
printf(“%d \t”, a[0][0]);
a 30 40
printf(“%d \t”, a[0][1]); 1
printf(“\n”);
printf(“%d \t”, a[1][0]);
printf(“%d \t”, a[1][1]);
}
Output: 10 20
20 40
Displaying 2DArray elements using loop
#include<stdio.h>
main()
{
int i;
int a[2][2]={10,20},{30,40}};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++){
printf(“%d \t”, a[i][j]);
}
}
Output:
10 20 30 40
Displaying 2DArray elements using loop:
(Matrix Form)
#include<stdio.h>
main()
{
int i;
int a[2][2]={10,20},{30,40}};
for(i=0;i<2;i++)
Output:
{
10 20
for(j=0;j<2;j++)
30 40
{
printf(“%d \t”, a[i][j]);
}
printf(“\n”);
}
Run time initialization
int a[3][3];
for(i=0,i<3;i++)
{
for(j=0,i<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
Program-1
//Entering a 3 × 3 matrix and displaying the elements
#include<stdio.h>
main()
{
int i;
int a[3][3];
printf(“Enter the matrix elements: \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
Cont…
printf(“The matrix elements are \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d \t”, a[i][j]);
}
printf(“\n”);
}
}
Example-2
//Find sum of all Matrix elements

sum=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=sum+a[i][j];
}
}
Example-3
//Multiply 5 to all matrix elements

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=a[i][j]*5;
}
}
Example-4
//Find addition results of two Matrix

//Enter the number of rows and number of columns of the matrix

//enter the elements of the 2 matrix a and b

for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
Program-5
//Find element wise multiplication results of two Matrix

for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
c[i][j]=a[i][j]*b[i][j];
}
}
Homework Questions
1. Write a program to print all odd numbers present in a matrix.

2. Write a program to count how many even numbers are present in a


matrix
3. Write a program to check how many times a particular element is
present in a matrix.

4. Write a program to print the diagonal elements of any user entered


matrix.

5. Write a program to find matrix chain multiplication results of


two user entered Matrix.
Matrix Multiplication

Rule:
number of columns in the 1st matrix is equal to the rows in the 2nd matrix

Result matrix will have:


number of rows = number of the rows in the 1st matrix
and
number of columns= number of columns of the 2nd matrix
C

A= [ ] [ ]
r1 x c1
B= A x B=
r2 x c2
[] r1 x c2
int main()
{
int a[10][10],b[10][10],mul[10][10];
int r1,c1,r2, c2;
int i,j,k;

printf(“Enter the number of rows and columns of matrix-1:\n”);


scanf(“%d%d”,r1,c1);

printf(“Enter the number of rows and columns of matrix-2:\n”);


scanf(“%d%d”,r2,c2);
printf("enter the first matrix element: \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("enter the second matrix element:\n");


for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mul[i][j]=0;
for(k=0;k<c1;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
printf(“the multiplication results of the two matrices is:\n”);

for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Module-3 (Part-II):
Character Array and Strings

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Introduction
 A string is a sequence of characters that is treated as a single data item.

Example:
printf( “Hello World”);

here “Hello world” is a string that is a group of characters


defined between double quotes

and printf is used to print it on the output screen

 Character strings are often used to build meaningful and readable


programs.
Cont…
 Common operations performed on character strings:
 reading and writing strings
 combining strings
 copying one string to another
 comparing strings
 extracting a portion of a string.
Declaration of Character Array
char name[30];

0 1 2 3 4 5 29
Compile time initialization
Variable initialization:
char ch=„C‟;

Array initialization:
char c[8]={„W‟, „E‟, „L‟, ‟C‟, „O‟, „M‟, „E‟, „\0‟};

or
char c[8]= “Welcome ”;

Note: When the compiler assigns a character string to a character array, it


automatically supplies a null character („\0‟) at the end of the string.

Therefore, the size should be equal to the maximum number of characters in


the string plus one
Run time initialization
Reading one character:
char ch;
scanf(“ %c”, &ch);

Reading a string of characters:


char name[30];
scanf(“%s”, name);

Note: scanf can‟t read space in between strings using %s format


specifier, use the below syntax to read space in between strings:
scanf(“%[^\n]”,name);
Using getchar function to read
characters
char ch;
ch=getchar();

Receive one character from keyboard at runtime and store in variable ch


Sample Code:
//Using getchar() to read one one character and store in arr[]

main()
{
char arr[10];
char ch;
int i=0
printf(“enter the characters you want to store in the array:\n”);
do{ for(i=0;ch!='\n';i++)
ch=getchar(); or {
arr[i]=ch;
ch=getchar();
i++;
arr[i]=ch;
}while(ch!=„\n‟);
}
printf(“Your entered string is:\n%s”,arr);
}
Using gets function
char name[30];

gets(name);

//read a line of text and store in the character array „name‟


Printing character and strings

char ch=„A‟;
printf(“%c”, ch)

char name[30]=“Amit”;
printf(“%s”, name)
Using putchar and puts functions

char ch=„A‟;
putchar(ch);

char name[30]=“Amit”;
puts(name);
String Handling Functions

Header file to include:


#include<string.h>
Example-1
//copy one string to another

void main()
{
char str1[100], str2[100];
Output:
printf(“\Enter a String : "); Enter a String:
gets(str1); Hello

strcpy(str2,str1); Hello

puts(str2);
}
Example-2
// concatenate two strings

void main()
{
char str1[100], str2[100];
Output:
printf(“\Enter the First String : "); Enter the First String:
C
gets(str1);
Enter the Second String :
printf("Enter the Second String : "); Programming
gets(str2);
The string after concatenation is:
C Programming
strcat(str1,str2);

printf(“The string after concatenation is: %s”, str1);


}
Example-3
//Print the length of a strings

void main()
{
char str1[100];
int len;
Output:
printf(“\Enter a String : "); Enter a String:
gets(str1); Hello

len=strlen(str1);
6
printf(“%d”,len);
}
Example-4
// check two string are equal or not

void main()
{
char str1[100], str2[100];
int result;
printf(“\Enter the First String : ");
gets(str1);
printf("Enter the Second String : ");
gets(str2);
result=strcmp(str1,str2);

if(result== 0)
printf(“Strings are equal\n”);
else
printf(“strings are unequal”);
}
Null Character „\0‟ at the end position
of string
char str[6]=“Hello”;

0 1 2 3 4 5
H e l l o \0
Homework Questions

Write C programs for the following without using string library functions:

1. Find the length of the string


2. Copy one string to another
3. Concatenate two strings
Find the length of the string without
using strlen()
/*-----Logic------*/

//Enter a string in str

c=0;
for (i = 0; str[i] != '\0'; i++) {
c++;
}
//Print the value of c
Copy one string to another
main()
{
char s1[30], s2[30];
int i;
printf("Enter string s1: ");
scanf(“%s”, s1);

for (i = 0; s1[i] != '\0'; i++)


{
s2[i] = s1[i];
}

s2[i] = '\0';

printf("String s2: %s", s2);


}
Concatenate two strings
main(){
char s1[30], s2[30], s3[60];
int i, j=0;
printf("Enter 1st string : ");
scanf(“%s”,s1);
printf("Enter 2nd string : ");
scanf(“%s”,s2);

for (i = 0; s1[i] != '\0'; i++) {


s3[i] = s1[i];
}
for (j = 0; s2[j] != '\0'; j++,i++) {
s3[i] = s2[j];
}
s3[i] = '\0';
printf("String s2: %s", s3);

}
Concatenate two strings with a space in
main(){
between
char s1[30], s2[30], s3[60];
int i, j=0;
printf("Enter the 1st string : ");
scanf(“%s”,s1);
printf("Enter the 2nd string : ");
scanf(“%s”,s2);

for (i = 0; s1[i] != '\0'; i++) {


s3[i] = s1[i];
}
strcat(s3, “ ”);
for (j = 0; s2[j] != '\0'; j++,i++) {
s3[i] = s2[j];
}
s3[i] = '\0';
printf("String s2: %s", s3);
}
Convert to upper case
main()
{
char str[100];
int i;
printf("Enter a string : ");
scanf(“%s”,str);
for (i = 0; str[i]!='\0'; i++)
{
if(str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] -32;
}
}
printf("String in Upper Case = %s", str);
}
Module-4 (Part-I):
User Defined Functions

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
An Overview of the Structure of a C
Program
Introduction
 C functions can be classified into 2 categories:

 Library functions:
 Definitions are present in respective header files
 Examples: printf, scanf, sqrt, strcat, …….

 User defined functions:


 Definitions are required to be written at the time of writing the
program.
Need for User Defined Functions
 If a program is divided into functional parts, then each part may be
independently coded and later combined into a single unit.
 These independently coded programs are called subprograms
(referred to as functions) that are much easier to understand, debug
and test.

 There are situations, when certain type of operations or calculations


are repeated at many points throughout a program.
 Using a user defined function can save both time and space
 Exa: Finding factorial of different numbers.
 The program statement calculating factorial may be repeated
whenever needed
 Or a function may be designed that will calculate the factorial of a
number and use whenever needed.
Advantages of using User Defined Functions
 It facilitates top-down modular programming

Main
program

Function-1 Function-2 Function-3

 The length of the source program can be reduced by using


functions at appropriate places.

 It is easy to locate and isolate a faulty function for further


investigations.

 A function may be used by many other programmers.


What is a function?
 A function is a self contained block of code that performed a
particular task.

 Once a function is designed and packed, it can be treated as a


black box-that takes some data from the main program and returns
a value.

 The inner details of operations are invisible to the rest of the


program
Input Output
data Function result
Elements of User Defined Functions
 Function has 3 elements:
 Function Definition:
 An independent program module written to implement the
requirements of the function

 Function Call:
 In order to use a function we need to invoke it at a required
place in the program-known as function call

 Function Declaration:
 The calling program must declare any function that is to be
used later in the program
Function Definition
General format:
fucntion_type function_name(parameter_list) {
local variable declaration;
executable statements;
……
……
return statement;
}
Example:
int sum(int a, int b) {
int s;
s=a+b;
return s;
}
Example-1
#include<stdio.h>
int sum(int , int ); /*function declaration*/
void main() {
/*function call */
int res;
res=sum(10,20);
printf(“sum= %d\n”, res);
}
int sum(int a, int b)
{
int s;
s=a+b;
return s; /*function definition*/
}
Note: Use this format in the labs
Example-2: Alternative approach
#include>stdio.h>
int sum(int a, int b)
{
int s; /*function declaration/definition*/
s=a+b;
return s;
}
void main()
{ /* function call */
int res;
res=sum(10,20)
printf(“sum= %d\n”, res);
}
Note: Don’t use this format in the labs
Example-3
#include>stdio.h>
int sum(int , int );
void main() {
int n1,n2,res;
printf(“Enter two numbers:\n”);
scanf(“%d%d”,&n1,&n2);
res=sum(n1,n2);
printf(“the addition result of the numbers is %d\n”, res);
}
/* Include function definition for sum() present in example-1 */
Formal Arguments Vs. Actual Arguments
 Actual arguments are the values that are passed to a function when
it is called.

 Formal arguments are the variables declared in the function


header that are used to receive the values of the actual arguments
passed during function calls.

 The scope of formal arguments is within the function itself; they are
not accessible outside the function.

 Actual arguments can be variables or expressions from the calling


context.
Example
#include>stdio.h>
int sum(int , int );
void main() {
int n1=10,n2=20,res; n1 and n2 are actual arguments
res=sum(n1,n2);
printf(“the addition result of the numbers is %d\n”, res);
}
a and b are formal arguments that receives
int sum(int a, int b) a copy of n1 and n2 respectively
{
int sm; The variables a and b are only accessible to
sm=a+b; function sum
return sm;
}
Flow of Control in Function call

void main() {
…….
f1();
…….
}
void f1() {
……
…..

}
Example
//Find area of a circle
#include>stdio.h>
float area(float);
main() {
float res, rad;
//Enter the radius
res=area(rad);
printf(“the area of the circle is %f\n”, res);
}
float area(float r)
{
Note: user defined function name and
float a, pi=3.14;
variable names used in the program must
a=pi*r*r;
return a;
be different
}
Functions return types
 A function return type may be:
int, float, double, char

void: If the function don‟t return anything to the calling function.


Types of User defined functions
1. Functions with no argument and no return type

2. Functions with argument and no return type

3. Functions with argument and return type

4. Functions with no argument but return type

* Functions which returns multiple values


1. Functions with no argument and no return type
/* ------ Example: Print first 10 natural numbers ------ */

#include>stdio.h>
void print( );
void main() {
print(); A function that does not receive any
data from the calling function and also
} not returning any value to the calling
void print( ) function.
{
int i;
for(i=1;i<=10;i++)
printf(“%d\n”, i);
}
2. Functions with argument and no return type
#include>stdio.h>
void checkeven(int);
void main(){
A function that receives some data from
int n1; the calling function and not returning any
//enter a number value to the calling function
checkeven(n1);
}
void checkeven(int n)
{
if(n%2==0)
printf(“The entered number is an Even Number\n”);
else
printf(“The entered number is an Odd Number \n”);
}
3. Functions with argument and return type
#include>stdio.h>
int factorial(int);
A function that receives some data from
void main() { the calling function and also returning a
int res, num; value to the calling function
//Enter a number
res=factorial(num);
printf(“The factorial of the number is: %d\n”, res);
}
int factorial(int n) {
int i, fact=1;
for(i=1;i<=n; i++){
fact=fact*i;
}
return fact;
}
4. Functions with no argument but return type
#include>stdio.h>
A function that does not receive any data
float area(); from the calling function and returning a
main() { value to the calling function
float res;
res=area();
printf(“the area of the circle is %f\n”, res);
}
float area()
{
float r,a, pi=3.14;
//enter the radius
a=pi*r*r;
return a;
}
Example
/*Write a program to find addition and subtraction results of 2 number
using user defined function*/
#include>stdio.h>
int sum(int , int );
int sub(int , int );
void main() {
int a,b, res;
//enter the values of a and b
res=sum(a,b);
printf(“the addition result of the numbers is %d\n”, res);
res=sub(a,b);
printf(“the subtraction result of the numbers is %d\n”, res);
}
Cont…
int sum(int a, int b)
{
int sm;
sm=a+b;
return sm;
}
int sub(int a, int b)
{
int sb;
sb=a-b;
return sb;
}
void main() {
…….
f1();
Nesting of
……. Functions
}
void f1() {
int res;
…..
res=f2();
}
int f2()
{
…..
return r;
}
Example
/*create a function to check a number is even or odd. Use that function in
another function to printing all even numbers upto 10
#include>stdio.h>
void printeven();
int checkeven(int); int checkeven(int n)
void main() { {
printeven(); if(n%2==0)
} return 1;
void printeven() { else
int i,r; return 0;
for(i=1;i<=10;i++) { }
r=checkeven(i);
if(r==1)
printf(“%d\n”, i);
} }
Example:
Call by Value
//swapping values of 2 variables void swap(int a, int b) {
void swap(int , int); int c;
int main() c=a;
{ a=b;
int a,b; b=c;
a=10; }
b=20;
swap(a,b);
printf(“a=%d b=%d\n", a,b);
return 0; Output:
} a=10 b=20
Call by Value Formal arguments

void swap(int , int); void swap(int a, int b)


int main() { {
int a,b; Actual arguments int c;
a=10; c=a;
b=20; a=b;
swap(a,b); b=c;
return 0; printf(“a=%d b=%d”,a,b);
} }

Output:
a=20 b=10
Call by Value Formal arguments
void swap(int , int); void swap(int a, int b)
int main() {
{ int c;
int a,b; c=a;
a=10; a=b;
Actual arguments
b=20; b=c;
swap(a,b); printf(“inside swap function
printf(“inside main function a=%d a=%d b=%d”, a, b);
b=%d”, a, b); }
return 0; Output:
} inside swap function a=20 b=10
inside main function a=10 b=20

To swap the data of actual arguments through function, call by


refernce concept is needed (to be discussed in module-5)
Passing Array and Strings to User
Defined Functions
Example-1: Passing Array to function
int add (int [ ]); //int add (int x[ ] );
main()
{ int add(int x[ ])
int a[5]={5,9,7,3,1};
{
int s;
int i, sum=0;
s=add(a);
printf(“sum = %d”, s); for(i=0;i<5;i++)
} {
sum=sum+x[i];
}
return sum;
}
Rules
1. The function prototype must show that the argument is an array.
int add (int [ ], int n);
or
int add (int x[ ], int );

2. The function must be called by passing only the array name without
[] s=add (x, n);

3. In the function definition the parameter must be of an array type.


int add (int x[ ], int n)
{
.........
}
Example-2: Passing 2D Array to function

int add (int [ ][n], int m, int n); int add(int x[ ][n],int m, int n)
main() {
{ int i, j, sum=0;
int a[3][3]={11,22,33,44,55,66};
for(i=0;i<m;i++)
int s;
{
s=add(a, m, n);
printf(“sum = %d”, s); for(j=0;j<n;j++)
} {
sum=sum+x[i][j];
}
return sum;
}
Rules
1. The function must be called by passing only the 2D array name
without [ ]
s=add (x, m, n);

2. In the function definition the parameter must be of a 2D array type.

3. The size of the 2nd dimension must be specified


int add (int x[ ][n ], int m, int n)
{
.........
}
4. The function prototype declaration should be similar to function
header
Example-3: Passing Strings to Function
Pass by value:
void print (char [ ] ); //void print (char str1[ ] );
void main()
{
char str1[5]=“abc”;
print(str1);
}
void print(char str1[ ])
{
printf(“%s”, str1);
}
Recursion
Example
//Factorial function without recursion
int factorial(int n)
{
int i, fact=1;
for(i=1;i<=n; i++)
{
fact=fact*i;
}
return fact;
}
Recursion
 When a function calls itself its called a recursive function

 Recursion is made for solving problems that can be broken down into
smaller, repetitive problems.

Example: Let n=3,


n != 3 * 2* 1
=3* 2! //2!= 2* 1!

n!= n* (n-1)!

fact=factorial(n);
n* factorial(n-1);
Example:
Let n=5,
n != 5* 4* 3 * 2* 1
=5* 4! 4!= 4 * 3 * 2 * 1
4 * 3! 3!=3 * 2 * 1
=3 * 2! 2!=2 *1!
1!=1
Recursion Cont…
 Recursive function usually has a certain structure:

(1) a base case: which does not call the function itself;

(2) a recursive step: which calls the function itself and moves closer to
the base case.
Example-1
//Factorial function using recursion
int factorial(int n)
{
int fact;
if(n==1)
return 1;
else
fact=n * factorial(n-1);
return fact;
}
Example-2
// find sum of first n natural numbers using recursion
int sum(int n)
{
int s;
if(n==1)
return 1;
else
s=n + sum(n-1);
return s;
}
Logic for sum of digits of a number
int sum(int num)
{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
Scope, Visibility and Lifetime of
Variables
Scope, Visibility and Lifetime of
Variables
 Scope: determines over what regions the variable is available for use

 Longevity: refers to the period during which a variable retains a given


value

 Visibility: refers to the accessibility of a variable from memory

 In a basic C program a variable retains its value throughout the program.

 But this is not the case always, it depends on the storage class of a
variable.
 In C, the variables can have a storage class.
Storage Class
 A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C Program.

 They precede the type that they modify.

 There are four different storage classes in a C program:


 auto
 register
 static
 extern
auto
 The auto storage class is the default storage class for all local variables.

Example:
auto int month;

 „auto' can only be used within functions, i.e., local variables.

 They are created when the function is called and destroyed automatically
when the function is exited.

 Those variables are local to the function in which they are declared.
Example
void f1()
#include<stdio.h>
{
void f1();
int m=10
void f2();
printf(“m=%d”, m);
void main()
}
{
void f2()
int m=1000;
{
f2();
int m=100
printf(“m=%d”, m);
f1();
}
printf(“m=%d”, m);
}
Output:
10
100
1000
register
 The register storage class is used to define local variables that should be
stored in a register instead of RAM.

 The variable has a maximum size equal to the register size (usually one
word)

Example:
register int miles;

 The register should only be used for variables that require quick access
such as counters.

 Note: defining 'register' does not mean that the variable will be stored in
a register. (depends on the hardware and implementation restrictions)
static
 The static storage class instructs the compiler to keep a local variable in
existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope.

 Allows local variables to maintain their values between function calls.

 The static modifier may also be applied to global variables. When this is
done, it causes that variable's scope to be restricted to the file in which it
is declared.

Example:
static int month;
Example
#include<stdio.h>
void f1();
void main()
{
f1();
f1(); Output:
f1(); 1
} 1
void f1()
1
{
int count=0; //no „static‟ keyword used
count++;
printf("%d\n",count);
}
Example
#include<stdio.h>
void f1();
void main()
{
f1();
f1(); Output:
f1(); 1
} 2
void f1()
3
{
static int count=0; //‟static‟ keyword used
count++;
printf("%d\n",count);
}
extern
 The extern storage class is used to give a reference of a global variable
that is visible to all the program files.

 When you use 'extern', the variable cannot be initialized however, it


points the variable name at a storage location that has been previously
defined.

 Extern is used to declare a global variable or function in another file.

 The extern modifier is most commonly used when there are two or more
files sharing the same global variables or functions

Example:
extern int y;
Example
#include<stdio.h>
void f1();
void main()
{ Output:
int y; 0
printf("%d\n",y); 0
f1();
}
void f1()
{
int y;
printf("%d\n",y);
}
int y=10;
Example
#include<stdio.h>
void f1();
void main()
{ Output:
extern int y; 10
printf("%d\n",y); 10
f1();
}
void f1()
{
extern int y;
printf("%d\n",y);
}
int y=10;
Comparison
Module-4 (Part-II):
Structure & Unions

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Structure
 A Structure is a user defined data type in C

 Allows to combine data items of different types

 The „struct’ keyword is used to create a user defined data type.


Difference between Array and Structure
 An array is a derived data type where as a structure is a programmer
defined data type.

 An array is a collection of related data elements of same type whereas a


structure can have elements of different types.

Example of array declaration: Example of structure declaration:

int a[5] ; struct student{


int rollno;
char name[30];
float marks;
};
Defining a structure
struct student
{
int rollno;
char name[30];
float marks;
};

//It‟s a template definition not a variable


Declaring structure Variables
struct student{
int rollno;
char name[30];
float marks;
}s1;

Or

struct student s1;


Declaring Multiple Structure
Variables
struct student{
int rollno;
char name[30];
float marks;
}s1,s2;

Or

struct student s1,s2;


Type-Defining a structures
typedef struct student
{
int rollno;
char name[30];
float marks;
}std;

std s1,s2;
Accessing members of structure
//by the dot operator, also called member operator

Example:

s1.rollno
s1.name
s1.marks
Initializing values
Example:

s1.rollno=1;
strcpy(s1.name, “Ajay”);
s1.marks=98.5;

Or

struct student s1={1, “Ajay”, 98.5};

Note:
 The order of values enclosed in braces must match the order of members
in the structure
Runtime Initialization
Example:

scanf(“%d”,&s1.rollno);
scanf(“%s”,s1.name);
scanf(“%f”,&s1.marks);

Note: Compiler will also accept the below format:


scanf(“%d%s%f”, &s1.rollno, s1.name, &s1.marks);

However beginner programmers must avoid this format to avoid


confusions
Printing values
printf(“rollno=%d\n, s1.rollno);
printf(“name=%s\n, s1.name);
printf(“marks=%f\n, s1.marks);

Note: Compiler will also accept the below format:


printf(“rollno=%d\n name=%s\n marks=%f\n”, s1.rollno, s1.name,
s1.marks);

However beginner programmers must avoid this format to avoid


confusions
Example-1: Design a structure student with members as rollno, name, and
marks. Initialize values to the members and print the details.
#include<stdio.h>
struct student{
int rollno;
char name[30];
float marks;
}s1;
void main() {
s1.rollno=1;
strcpy(s1.name, “Ajay”);
s1.marks=98.5;
printf("The student details are: \n");
printf(“rollno=%d\n, s1.rollno);
printf(“name=%s\n, s1.name);
printf(“marks=%f\n, s1.marks);
}
Example-2: Design a structure student with members as rollno, name, and marks.
Enter details for a student and print the results.
#include<stdio.h>
struct student{
int rollno;
char name[30];
float marks;
}s1;
void main() {
printf("Enter roll no:\n");
printf("The student details are: \n");
scanf("%d",&s1.rollno);
printf(“rollno=%d\n, s1.rollno);
printf("Enter name:\n");
printf(“name=%s\n, s1.name);
scanf("%s",s1.name);
printf(“marks=%f\n, s1.marks);
printf("Enter marks:\n");
}
scanf(“%f",&s1.marks);
Example-3 Using typedef
#include<stdio.h>
typedef struct student{
int roll;
char name[30];
}std;
int main(){
std s1;
printf("Enter the roll and name:\n");
scanf("%d%s",&s1.roll,s1.name);
printf("The student details are:\n");
printf("Roll: %d\n Name: %s\n",s1.roll, s1.name);
return 0;
}
Points to note
 Individual members can‟t be initialized inside the structure template

 The order of values enclosed in braces must match the order of members
in the structure

 We can copy the data of structure variables


s2=s1; //copy s1 data to s2

 Can‟t apply logical operations on structure variables:


s2==s1 //wrong
s2!=s1 //wrong

 Can compare the member


s1.marks==s2.marks //correct
Example-4: Copying structure variables
#include<stdio.h>
struct student{
int rollno;
char name[30];
float marks;
}s1,s2;
void main() {
/*Enter student s1 data*/
s2=s1;
/*Print the entered student details for s1*/
printf("The copied student details are: \n");
printf(“rollno=%d\n, s2.rollno);
printf(“name=%s\n, s2.name);
printf(“marks=%f\n, s2.marks);
}
Example-5: Comparing structure variables
#include<stdio.h>
struct student{
int rollno;
char name[30];
float marks;
}s1,s2;
void main() {
/*Enter student details for s1 and s2*/
if(s1.marks>s2.marks)
printf(“first student secured highest mark”);
else
printf(“second student secure highest marks”);
}
Array of Structures
struct student{
int rollno;
char name[30];
float marks;
}s[3];

Or

struct student s[3];


Initializing values: Fixed Values
struct student s[3]={ {1, “Ajay”, 98.5},
{2, “Sumit”, 90.5},
{ 3, “Ajit”, 92.5}};
Runtime entry: Array of structures
Example:
struct student s[3];
printf(“Enter the student details\n”);
for(i=0;i<3;i++)
{
scanf(“%d”, &s[i].rollno);
scanf(“%s”, s[i].name);
scanf(“%f”, &s[i].marks);
}

Note: Compiler will also accept the below format:


scanf(“%d%s%f”, &s[i].rollno, s[i].name, &s[i].marks);
However beginner programmers must avoid this format to avoid
confusions
Printing Array of structures
Example:
printf("The student details are:\n");
printf("Roll:\tName: \t\t Marks:\n");
for(i=0; i<3; i++){
printf("%d\t",s[i].roll);
printf("%s\t\t",s[i].name);
printf("%f\n",s[i].marks);
}
Note:
Compiler will accept:
printf(“%d \t %s\t\t %f\n ”, s[i].rollno, s[i].name, s[i].marks);
However beginner programmers must avoid this format to avoid
confusions
Example
//print all students details those have secured marks>=90
Logic:

printf("The student details with marks >=90 are:\n");


printf("Roll:\tName: \t\t Marks:\n");
for(i=0; i<3; i++)
{
if(s[i].marks>=90)
{
printf("%d\t",s[i].roll);
printf("%s\t\t",s[i].name);
printf("%f\n",s[i].marks);
}
}
Example
//Count how many students secured marks>=90
Logic:

count=0;
for(i=0;i<5;i++)
{
if(s[i].marks>=90)
{
count++;
}
}
//print count
Passing structure to function
#include<stdio.h>

struct student
{
int roll;
char name[30];
float marks;
};

void display(struct student);


Cont…
void main()
{
struct student s1;
printf(“Enter the student details\n”);
scanf("%d%s%f",&s1.roll,s1.name,&s1.marks);
display(s1);
}

void display(struct student s1)


{
printf(“ rollno: %d\t name: %s\t marks:%f:",s1.roll,s1.name,s1.marks);
}
Example: distance between two points using function

#include <stdio.h>
#include <math.h>
struct point{
int x,y;
}p1,p2;
void distance(struct point p1,struct point p2){
int res;
res=sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y));
printf(“The distance between the points is: %d ",res);
}
int main(){
p1.x=10; p2.x=10; p1.y=8; p2.y=10;
distance(p1,p2);
return 0;
}
Example: Structure within Structure
struct student
{
int roll;
char name[30];
float tmarks;
struct dob
{
int dd;
int mm;
int yyyy;
}d1;
}s1;
Alternative Declaration
struct dob
{
int dd;
int mm;
int yyyy;
};
struct student
{
int roll;
char name[30];
float marks;
struct dob d1;
}s1;
Cont…
void main()
{
//read the details for rollno, name, total marks like previous examples
printf(“Enter the DOB:\n”);
scanf("%d%d%d”, &s1.d1.dd, &s1.d1.mm, &s1.d1.yyyy);

//print the details for rollno, name, marks like previous examples

printf(“DOB in DD MM YYYY format: %d-%d-%d",


s1.d1.dd,s1.d1.mm,s1.d1.yyyy);

}
Union
 A union is a special data type available in C that allows to store
different data types in the same memory location.

 You can define a union with many members, but only one member
can contain a value at any given time.

 Unions provide an efficient way of using the same memory


location for multiple-purpose.
Example Declaration
union student{
int rollno;
char name[30];
float marks;
};
void main()
Cont…
{
union student s1;
printf(“Enter the student details\n”);

scanf(“%d”,&s1.rollno);
scanf(“%s”,s1.name); Output:
scanf(“%f”,&s1.marks);  print only last variable data
correctly all other values
garbage
printf(“Student details:\n”);
printf(“rollno=%d\n, s1.rollno);
 As the same memory
printf(“name=%s\n, s1.name);
location is used by all
printf(“marks=%f\n, s1.marks); variable
}
Correction in code needed for union
void main()
{
union student s1;
printf(“Enter the student details\n”);

scanf(“%d”,&s1.rollno);
printf(“rollno=%d\n, s1.rollno);

scanf(“%s”,s1.name);
printf(“name=%s\n, s1.name);

scanf(“%f”,&s1.marks);
printf(“marks=%f\n, s1.marks);
Size of Structure and Union
Example
struct student
{
int roll;
char name[36];
float tmarks;
};
void main()
{
struct student s1; Output: 44

printf("%d",sizeof(s1));
}
Example
union student
{
int roll;
char name[36];
float tmarks;
};
void main()
Output: 36
{
union student s1;

printf("%d",sizeof(s1));
}
Difference between Structure and Union

 The struct keyword is used to  The union keyword is used to


define a structure. define union.

 When the variables are declared in  When the variable is declared in


a structure, the compiler allocates the union, the compiler allocates
memory to each variables member. memory to the largest size variable
member.

 The size of a structure is equal or  The size of a union is equal to the


greater to the sum of the sizes of size of its largest data member
each data member. size.
 Each variable member occupied a  Variables members share the
unique memory space. memory space of the largest size
variable.
Module-5 (Part-I):
Pointer

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Introduction
 A Pointer is a derived data type in C.

 It is built from one of the fundamental data types available in C.

 Pointers contains memory address as their values.

 Since those memory addresses are the locations in the computer


memory, where program instructions and data are stored,
 pointers can be used to access and manipulate data stored in
memory.
Benefits of pointers
 Pointers are more efficient in handling arrays and data tables.

 Pointers can be used to return multiple values from a function via


function arguments

 The use of pointer arrays to character strings results in saving of


data storage space in memory

 It allows C to support dynamic memory management

 It provides an efficient tool for manipulating dynamic data


structures such as structures, linked lists, queues, stacks and trees
Accessing Address of a Variable
int a;
a
a=10;
10
printf(“value of a=%d”, a); 4000
printf(“address of a=%u”, &a);

Note: %u is the format specifier for unsigned integer.


Address of a memory location is always an integer.
What is a Pointer?
 Pointer is a derived data type that can store the address of another
variable.

Declaring a pointer type variable:


Syntax: data_type *pointer_variablename;

Example: int *p;


a p
10 4000
Initializing pointer variable:
4000 5000
int a=10;
int *p; or int *p=&a;
p=&a;
Note: here p is pointing to address of an integer data type
Accessing a Variable through Pointer
 The indirection operator or * operator is used

a p
Example:
10 4000
int a=10;
4000 5000
int *p=&a; output:
printf(“%d\n”,a); 10

printf(“%u\n”,&a); 4000
printf(“%u\n”,p); 4000
printf(“%d\n”,*p); 10

printf(“%u\n”,&p); 5000
Chain of Pointers
 A pointer can point to another pointer, creating a chain of pointers.
 The value of variable can be accessed through multiple indirection.

Example:
a p q
int a, *p, **q;
10 4000 5000
a=10;
4000 5000 6000
p=&a;
q=&p; output:
printf(“%d\n”,*p); 10
printf(“%u\n”,q); 5000
printf(“%u\n”,*q); 4000
printf(“%d\n”,**q); 10
Pointer Expression
Example:
int a=20,b=30,sum;
int *p, *q;
p=&a;
q=&b;
sum=*p+*q;
printf(“%d”, sum);

Output: 50

Note: sum=a+b can be written using * operator as: sum=*p+*q


Pointer and Arrays
int a[5]={10, 20, 30, 40, 50};
0 1 2 3 4

a 10 20 30 40 50
Address of elements: 1000 1004 1008 1012 1016

Base
address

Note: Assuming a 64 bit compiler where int data type takes 4 bytes of
memory

int *p;
p=a or p=&a[0]
Pointer and Arrays

0 1 2 3 4

a 10 20 30 40 50
Address of elements: 1000 1004 1008 1012 1016

int *p; Base


address
p=a;
Accessing the other array elements:
p+1 a[1]
p+2 a[2]
p+3 a[3]
p+4 a[4]
Example-1: Accessing Array Elements
Using Pointer
//sum of all array elements
main()
{
int i, sum=0;
int a[5]={5,9,7,3,1};
int *p;
p=a; //p=a[0]; //initialize with base address of a
for(i=0;i<5;i++)
{
sum=sum+*p; //accessing array element
p++; //incrementing pointer
}
printf(“sum of all array elements=%d”, sum);
}
Example-2: Pointer to User Defined
Function
#include<stdio.h>
void add (int*);

main()
{
int a[5]={5,9,7,3,1};
int *p;
p=a;
add(p);
}
Cont…
//function Definition
void add (int *p)
{
int i, sum=0;
for(i=0;i<5;i++)
{
sum=sum+*p;
p++;
}
printf(“sum of all array elements=%d”, sum);
}
Call by Value Vs. Call by Reference
Example-1:
Swap the values of the variables:
Call by value
//pass by value
#include<stdio.h>
void swap (int , int);

main()
{ a=10 b=20
int a=10,b=20;
printf(“Before swapping a=%d \t b=%d\n”,a,b);
swap(a,b)
printf(“After swapping a=%d \t b=%d\n”,a,b); a=10 b=20
}
Cont…
//function Definition
void swap(int a, int b)
{
int temp;
temp=a;
a=b; a=20 b=10
b=temp;
//printf(“After swapping a=%d \t b=%d\n”,a,b);
}
Example-2:
Swap the values of the variables:
Call by Reference
//pass by reference

#include<stdio.h>
void swap (int *, int *);

main()
{ a=10 b=20
int a=10,b=20;
printf(“Before swapping a=%d \t b=%d\n”,a,b);
swap(&a,&b)
printf(“After swapping a=%d \t b=%d\n”,a,b); a=20 b=10
}
Cont…
//function Definition
void swap(int *p, int *q)
{
int temp;
temp=*p;
*p=*q; a=20 b=10
*q=temp;
//printf(“After swapping a=%d \t b=%d\n”,*p,*q);
}
Call by Value Vs. Call by Reference

Call by Value: Call by Reference:


 A copy of the value is passed to  Address of the value is passed to
the function the function
 Changes made to the values  Changes made to the values inside
inside the function are available the function are also available
to only that function outside the function
 i.e. the values of actual  i.e. the values of actual arguments
arguments do not change by change by changing the formal
changing the formal arguments. arguments.
 The actual and formal  The actual and formal arguments
arguments are created at are created at the same memory
different memory locations. locations.
Function Returning Pointer
int * max(int *,int *);
main()
{
int a=20,b=30;
int *p;
p=max(&a,&b);
printf(“%d”, *p);
}
int* max(int *x, int *y){
if(*x>*y)
return x;
else
return y;
}
Pointer and Character String
String declaration:
char str[6]=“Hello”; 0 1 2 3 4 5
str H e l l o \0

Using pointer string declaration:


char *str=“Hello”; 0 1 2 3 4 5

H e l l o \0

. str

 Here ‘str’ is a pointer to string and also the name of the string
Cont…
char *str;
str=“Hello”; //its not string copy as str is a pointer not a string

To print the data:


printf(“%s”, str);
or
puts(str);

 Indirection operator * is not required as it is also the name of the


character array
Example-1
//count the length of a string
char *str=“Hello”;
char *ptr;
ptr=str;
c=0;
while(*ptr!=„\0‟)
{
c++;
ptr++;
}
printf(“Length of the string=%d”, c)
Example-2
//count the length of a string
main( )
{
int i, c=0;
char *str=“Hello” ; //or use gets(str) to enter at runtime
char *ptr=str;
for(i=0;*ptr!=„\0‟;i++)
{
c++; //incrementing counter
ptr++; //incrementing pointer
}
printf(“number of characters = %d”, c);
}
Array of Pointers
Handling table of strings
char name[3][25];
// for 3 city names of maximum 25 characters each

Alternative declaration using pointer:


char *name[3]={“BBSR”, “CTK”,”RKL”};

Declares name to be an array of 3 pointers to character, each pointing


to a particular name

name[0] BBSR
name[1] CTK
name[2] RKL
Accessing the data
for(i=0;i<3;i++)
{
printf(“%s”\n”,name[i]);
}
Example: Pointer and Strings in User
Defined Function
#include<stdio.h>
void count (char *);
main( )
{
char *str=“Amit” ;
count (str);
}
Cont…

void count (char *ptr)


{
int i,c=0;
for(i=0;*ptr!=„\0‟;i++)
{
c++;
ptr++;//incrementing pointer
}
printf(“ string length=%d”,c);
}
Pointer to structure
struct product
{
char name[30];
int number;
float price;
}p[3],*ptr;

/* Here p is an array of 3 elements each of type product structure


ptr is a pointer to data object of type product */

Can also use the below syntax


struct product *ptr;
Cont…
Assigning address of structure to pointer variable:
ptr=p;

 This will assigns address of 0th element of p i.e. p[0] to ptr

 When ptr is incremented by one it made to point to next record


i.e. p[1], and so on.
Cont…
Accessing structure members:
 Members can be accessed using 
 Called arrow or member selection operator

Example:
ptr->name
ptr->number
ptr->price
Cont…
Reading structure data at runtime:

Example:
scanf(“%s”,ptr->name);
scanf(“%d”, &ptr->number);
scanf(“%f”, &ptr->price);
Example
#include<stdio.h>

struct product
{
char name[30];
int number;
float price;
}p[3],*ptr;
Cont…
void main() {
int i;
ptr=p;
printf("Enter the details for 3 products\n");
for(i=0;i<3;i++)
{
printf("Enter the product name\n");
scanf("%s",ptr->name);
printf("Enter the quantity \n");
scanf("%d",&ptr->number);
printf("Enter the price \n");
scanf("%f“,&ptr->price);
ptr++;
}
Cont…
ptr=p;
printf("The product details are\n");
printf("Name:\t Quantity:\t Amount:\n");
for(i=0;i<3;i++)
{
printf("%s \t %d \t %f \t", ptr->name, ptr->number, ptr->price);
ptr++;
}

} //end of main function


Output
Dynamic Memory Allocation
 The process of allocating memory at run time is known as
dynamic memory allocation.

 There are 4 library routines known as memory management


functions used in C Programming to use dynamic memory
allocation concept.
 malloc( )
 calloc( )
 realloc( )
 free( )

 Use header file:


#include<stdlib.h>
Cont…
malloc( ):
 Allocates requested size of bytes and returns a pointer to the first
byte of the allocated space

calloc( ):
 Allocates space for an array of elements, initialize them to zero
and then returns a pointer to the memory address

realloc( ):
 modifies the size of previously allocated space

free( ):
 Frees previously allocated space.
Allocating blocks of memory using
malloc
Syntax:
ptr=(cast_type *) malloc(byte_size);
 The malloc() returns a pointer to an area of memory with
size byte_size

Example:
int *p =(int *) malloc(100 * sizeof(int) );

 A memory space equivalent to “100 times the size of an int” bytes


is reserved and the address of the first byte of the memory
allocated is assigned to the pointer p
Example-1: Integer Array
main( )
{
int i, n,sum=0;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
int *p =(int *) malloc(n * sizeof(int) );
for(i=0; i<n; i++)
{
scanf(“%d”, p+i); //enter array elements
sum=sum+ *(p+i); //find sum of each entered numbers
}
printf(“sum of all array elements= %d”, sum);
free(p); //free allocated memory
}
Example-2: Strings
main( )
{
int i, n;
printf(“Enter the size of the string\n”);
scanf(“%d”,&n);
char *name =(char *) malloc(n * sizeof(char) );
gets(name);
printf (“entered name is= %s”, name);
free(name); //free allocated memory
}
Allocating blocks of memory using
calloc and reallocating memory
Syntax for calloc:
int *p =(int *) calloc(n, sizeof(int) );

Syntax for realloc:


//reallocate n block memory size to m (new size)

p=realloc (p, m);

free(p); //free allocated memory


Difference between malloc and calloc

Syntax:
int *p =(int *) malloc(n * sizeof(int));

int *p =(int *) calloc(n, sizeof(int) );

While malloc allocates a single block of storage space, calloc allocates


multiple blocks of storage, each of the same size and then sets all bytes
to zero.

You might also like