Module 1 PT 1 - Merged
Module 1 PT 1 - Merged
by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Contents
Introduction to Programming
Introduction to C programming
The instructions are entered into the computer and then 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
Implementation phase
implement the program in some programming 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.
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 ?
STOP
What is Programming ?
• Programs are set of instructions given to a computer to accomplish
a task.
…….
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
The compilation command converts the source code into a form that
is suitable for execution by the computer (known as object code).
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.
Multi-Line Comments
Multi-Line comments are represented by slash asterisk /* ... */.
Different forms of main()
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.
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
Example:
215.65 may be written as 2.1565e2 in exponential notation,
where e2 means multiply by 102
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
String constants
A sequence of characters enclosed in double quotes.
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);
#include<stdio.h>
main()
{ Output:
int a, b, sum; The sum of 2 numbers is: 30
a=10;
b=20;
sum=a+b;
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
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
Expression evaluation
type conversion
Operators and Expressions
An Operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
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.
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
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.
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:
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);
}
or
#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*/
#include<math.h>
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
Example:
x= a * b + c;
y= b / c – d;
Operator Precedence and
Associativity
Rules of Precedence and Associativity:
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.
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
#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 ;
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);
} }
#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);
} }
#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: 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
General Form:
Entry
True
Different Forms of if Statement
(i) Simple if statement
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”);
} }
True False
Test
Expression?
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-3
……
True False
Condition-
n
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
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:
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;
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
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.
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.
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.
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:
2. The do statement
{ 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
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
}
}
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++)
{
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++)
//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
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++)
{
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
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
}
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
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;
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;
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.
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.
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:
The idea is to store multiple items of the same type together with a
single name.
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.
At Compile time
At run time
Example: Compile time initialization
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
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
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
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];
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];
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];
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
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
{ 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
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
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
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:
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
0 1 2
0 a[0][1]
a 1
2 a[2][2]
a[0][0]
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
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.
Rule:
number of columns in the 1st matrix is equal to the rows in the 2nd matrix
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;
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”);
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 ”;
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);
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
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);
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:
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);
s2[i] = '\0';
}
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);
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, …….
Main
program
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.
The scope of formal arguments is within the function itself; they are
not accessible outside the function.
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
#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
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
2. The function must be called by passing only the array name without
[] s=add (x, n);
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);
Recursion is made for solving problems that can be broken down into
smaller, repetitive problems.
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
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.
Example:
auto int month;
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.
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.
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
Or
Or
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
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);
The order of values enclosed in braces must match the order of members
in the structure
Or
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;
};
#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
}
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.
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
by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon University, Odisha
Introduction
A Pointer is a derived data type in C.
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
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
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
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
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…
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++;
}
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) );
Syntax:
int *p =(int *) malloc(n * sizeof(int));