SlideShare a Scribd company logo
LABORATORY MANUAL
PROGRAMMING FOR PROBLEM SOLVING
(20ES1152)
I/IV B.TECH, FIRST SEMESTER
REGULATION: VR20
DEPARTMENT OF SCIENCE AND HUMANITIES
VELAGAPUDI RAMAKRISHNA SIDDHARTHA ENGINEERING COLLEGE
(AUTONOMOUS, ACCREDITED WITH ’A+’ GRADE BY NAAC)
List of Programs
1 Introduction to C Programming 4
1.1 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Print Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Escape Sequence and Format Specifiers . . . . . . . . . . . . . . . . . 10
1.4 Literal, Defined and Memory Constants . . . . . . . . . . . . . . . . . 12
1.5 ASCII to Text Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2 Data Types and Variable Declarations 16
2.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2 Swap Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3 Comparison of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4 Size and Range of C Data Types . . . . . . . . . . . . . . . . . . . . . . 26
3 Selection – Making Decisions 30
3.1 Even or Odd Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2 Biggest and Smallest Number . . . . . . . . . . . . . . . . . . . . . . . 33
3.3 Leap Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.4 Electricity Bill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4 Looping Constructs and Their Applications 42
4.1 Decimal to Binary Conversion . . . . . . . . . . . . . . . . . . . . . . . 42
4.2 Factorial of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3 Reverse of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.4 Strong Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.5 Armstrong Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.6 Fibonacci Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.7 Palindrome Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.8 Perfect Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.9 Print Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.10 Prime Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5 Unconditional Control Transfer Statements 72
5.1 Calculator Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.2 Sum of N Natural Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.3 Even Numbers not Divisible by 6 and 8 . . . . . . . . . . . . . . . . . . 77
6 Arrays and Their Applications 79
6.1 Minimum and Maximum Elements . . . . . . . . . . . . . . . . . . . . 79
6.2 Sorting of n numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
1
6.3 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.4 Insertion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.5 Remove Duplicate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.6 Matrix Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.7 Matrix Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.8 Matrix Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
7 Strings, String I/O and Manipulation Functions 106
7.1 String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.2 Reverse a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
7.3 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.4 String Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
8 Concepts of User Defined Functions 121
8.1 Swap Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.2 Factorial of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
8.3 Combination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
8.4 Mean and Standard Deviation . . . . . . . . . . . . . . . . . . . . . . . 134
9 Pointers and Their Applications 138
9.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.2 String Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
9.3 Largest Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
10 Structure, Union, and Enumeration 148
10.1 Student’s Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
10.2 Students’ Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
10.3 Days in a Week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
11 File Handling Operations 158
11.1 Count Number of Character, Spaces, Words and Lines . . . . . . . . . 158
11.2 Count Number of Alphabets, Digits, Punctuation Marks . . . . . . . 162
11.3 Merge Contents of Two Files . . . . . . . . . . . . . . . . . . . . . . . . 166
11.4 Compare Contents of Two Files . . . . . . . . . . . . . . . . . . . . . . 170
12 Command Line Arguments 174
12.1 Copy the Content of File . . . . . . . . . . . . . . . . . . . . . . . . . . 174
12.2 Minimum and Maximum Integers in a List . . . . . . . . . . . . . . . 178
12.3 Reverses Elements of an Array . . . . . . . . . . . . . . . . . . . . . . . 181
13 References 184
13.1 Text Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
2
13.2 Reference Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
13.3 e-Resources and Other Digital Materials . . . . . . . . . . . . . . . . . 185
About This
This manual is being offered to train first year first semester undergraduate students at
VRSEC – Vijayawada on the fundamentals of the ‘C’ programming language. The purpose
of it is to help students to understand basic programming concepts such as literals, data
types, and variable declaration, branching, looping, arrays, functions, string, pointer, file,
structure, enum, and command-line arguments execution.
3
1
WEEK
Introduction to C
Programming
1.1 Variable Declarations
Code the variable declarations for each of the following. a. a character variable named option
b. an integer variable sum, initialized to 0, c. a floating-point variable product, initialized to 1,
d. a short integer variable named code, e. a constant named sales_Tax initialized to 0.0825, f. a
floating-point named sum_of_size double initialized to 0.
1.1.1 Algorithm
1 Start
2 Declare variables option, sum and product.
3 Initialize sum to 0.
4 Initialize product to 1.
5 Declare code, sales_Tax and sum_of_size.
6 Initialize sales_Tax to 0.0825.
7 Initialize sum_of_size to 0.
8 Stop.
Algorithm 1: Variable declarations and initialization.
4
1.1.2 Flowchart
Figure 1: Variable declarations and initialization.
5
1.1.3 C Source Code
#include<stdio .h>
void main ( ) {
/ / a character variable named option .
char option ;
/ / an integer variable , sum, initialized to 0.
int sum = 0;
/ / a floating −point variable , product , initialized to 1.
float product = 1;
/ / a short integer variable named code .
short int code ;
/ / a constant named sales_Tax initialized to 0.0825.
const float sales_Tax = 0.0825;
/ / a floating −point named sum_of_size double initialized to 0.
float sum_of_size = 0;
}
1.1.4 Input and Output
Figure 2: Character, integer, floating-point variable declarations and initialization.
6
1.2 Print Patterns
Write C programs that uses four print statements to print the pattern of asterisks shown below.
1.2.1 Algorithm
1 Start
2 Display six ’*’ by giving a tab in between each ’*’.
3 Display six ’*’ by giving a tab in between each ’*’ in a new line.
4 Display six ’*’ by giving a tab in between each ’*’ in a new line.
5 Display six ’*’ by giving a tab in between each ’*’ in a new line.
6 Stop.
Algorithm 2: Rectangle star pattern.
1 Start
2 Display a ’*’.
3 Display two ’*’ by giving a tab in between each ’*’ in a new line.
4 Display three ’*’ by giving a tab in between each ’*’ in a new line.
5 Display four ’*’ by giving a tab in between each ’*’ in a new line.
6 Stop.
Algorithm 3: Right angle triangle star pattern.
7
1.2.2 Flowchart
Figure 3: Rectangle star pattern.
Figure 4: Right angle triangle star pattern.
8
1.2.3 C Source Code
I . #include<stdio .h>
void main ( ) {
printf ( "* t * t * t * t * t *n" ) ;
printf ( "* t * t * t * t * t *n" ) ;
printf ( "* t * t * t * t * t *n" ) ;
printf ( "* t * t * t * t * t *n" ) ;
}
II . #include<stdio .h>
void main ( ) {
printf ( "*n" ) ;
printf ( "* t *n" ) ;
printf ( "* t * t *n" ) ;
printf ( "* t * t * t *n" ) ;
}
1.2.4 Input and Output
Figure 5: Rectangle star pattern [4x6].
Figure 6: Right angle triangle star pattern.
9
1.3 Escape Sequence and Format Specifiers
Write a C program that defines five integer variables and initializes them to 1, 10, 100, 1000, and
10000. If then prints them on a single line separated by space characters using the decimal con-
version code (%d), and on the next line with the float conversion code (%f). Note the differences
between the results.
1.3.1 Algorithm
1 Start
2 Declare variables a, b, c, d and e.
3 Initialize a to 1, b to 10, c to 100, d to 1000 and e to 10000.
4 Display a, b, c, d and e values.
5 Map the a and b values to real numbers and display them.
6 Map the c, d and e values to real numbers and display them.
7 Stop.
Algorithm 4: Variable declarations and initialization.
1.3.2 Flowchart
Figure 7: Outcomes using escape sequence and format specifiers.
10
1.3.3 C Source Code
#include<stdio .h>
void main ( ) {
int a = 1 , b = 10 , c = 100, d = 1000, e = 10000;
printf ( "a : %d, b : %d, c : %d, d : %d, e : %d n" ,a ,b, c ,d, e ) ;
printf ( "a : %f , b : %f " , ( float )a , ( float )b ) ;
printf ( "c : %f , d : %f , e : %f n" , ( float )c , ( float )d , ( float )e ) ;
}
1.3.4 Input and Output
Figure 8: Outcomes using n escape sequence, %d and %f format specifiers.
11
1.4 Literal, Defined and Memory Constants
Write a C program that uses defined constants for the vowels in the alphabet and memory con-
stants for the even decimal digits (0, 2, 4, 6, 8). It then prints the following three lines using literal
constants for the odd digits.
1.4.1 Algorithm
1 Start
2 Define a to ’a’, b to ’e’, c to ’i’, d to ’o’ and e to ’u.
3 Declare i, j, k, l and m.
4 Initialize i to 0, j to 2, k to 4, l to 6 and m to 8.
5 Display a, b, c, d and e values.
6 Display i, j, k, l and m values.
7 Display 1, 3, 5, 7 and 9.
8 Stop.
Algorithm 5: Variable declarations and initialization.
1.4.2 Flowchart
Figure 9: Literal, defined and memory constants.
12
1.4.3 C Source Code
#include<stdio .h>
#define a ’a ’
#define b ’e ’
#define c ’ i ’
#define d ’o ’
#define e ’u ’
void main ( ) {
const int i = 0 , j = 2 , k = 4 , l = 6 , m = 8;
printf ( "%c  t %c  t %c  t %c  t %c n" , a , b, c , d, e ) ;
printf ( "%d  t %d  t %d  t %d  t %d n" , i , j , k , l , m) ;
printf ( "%d  t %d  t %d  t %d  t %d n" , 1 , 3 , 5 , 7 , 9);
}
1.4.4 Input and Output
Figure 10: Literal, defined and memory constants of vowels and single digit decimal numbers.
13
1.5 ASCII to Text Conversion
Write a C program that prompts the user to enter an integer and then prints the integer first as a
character, then as a decimal. Use separate print statements. A sample run is shown below.
The number as a character: K
The number as a decimal: 75
1.5.1 Algorithm
1 Start
2 Declare a variable k.
3 Store an integral value in k.
4 Display the corresponding character value of k.
5 Display the decimal value of k.
6 Stop.
Algorithm 6: Variable declarations and initialization.
1.5.2 Flowchart
Figure 11: ASCII to text conversion.
14
1.5.3 C Source Code
#include<stdio .h>
void main ( ) {
int k ;
printf ( "Enter the value of k n" ) ;
scanf ( "%d" , &k ) ;
printf ( "The number as a character : %c" , k ) ;
printf ( "The number as a decimal : %d" , k ) ;
}
1.5.4 Input and Output
Figure 12: ASCII value 75 to text conversion.
Objectives
To understand the basic building block of a C program.
To provide a glance on the C identifiers, data types, format specifiers, constants, and variables
declaration and initialization.
To write simple C programs using preprocessor commands and simple input and output state-
ments.
15
2
WEEK
Data Types and Variable
Declarations
2.1 Arithmetic Operations
Write a C program to perform simple arithmetic operations on two bool, character, integer and
floating point variables.
2.1.1 Algorithm
1 Start
2 Declare three integer variables a, b, x, y, i, j, l and m.
3 Get the boolean values for a and b.
4 Get the character values for x and y.
5 Get the integer values for i and j.
6 Get the real values for l and m.
7 Add a with b, subtract b from a and display the result.
8 Multiply a with b, divide a by b and display the product, quotient and reminder values.
9 Add i with j, subtract j from i and display the results.
10 Multiply i with j, divide i by j and display the product, quotient and reminder values.
11 Add l with m, subtract m from l and display the results.
12 Multiply l with m, divide l by m and display the product and quotient values.
13 Add x with y, subtract y from x and display the results.
14 Multiply x with y, divide x by y and display the product, quotient and reminder values.
15 Stop.
Algorithm 7: Arithmetic operations between different types of data.
16
2.1.2 Flowchart
Figure 13: Arithmetic operations between different types of data.
17
2.1.3 C Source Code
#include<stdio .h>
#include<stdbool .h>
void main()
{
bool a = false , b = true ;
char x , y ;
int i , j ;
float l , m;
printf ( "Enter the integer values of i and j : n" ) ;
scanf ( "%d %d" , &i , &j ) ;
printf ( "Enter the float values of l and m : n" ) ;
scanf ( "%f %f " , &l , &
m) ;
printf ( "Enter the character values of x and y : n" ) ;
scanf ( "%c %c" , &x , &y ) ;
printf ( "Arithmetic operations on boolean data : n" ) ;
printf ( "Addition : %d n Subtraction : %d n" , a+b, a−b ) ;
printf ( " Multiplication : %d n Division : %d n Modulus %d n" 
, a*b, a/b, a%b ) ;
printf ( "Arithmetic operations on integer data : n" ) ;
printf ( "Addition : %d n Subtraction : %d n" , i+j , i −j ) ;
printf ( " Multiplication : %d n Division : %d n Modulus : %d n" 
, i * j , i / j , i%j ) ;
printf ( "Arithmetic operations on float data : n" ) ;
printf ( "Addition : %f n Subtraction : %f n" , l+m, l −m) ;
printf ( " Multiplication : %f n Division : %f n" , l *m, l /m) ;
printf ( "Arithmetic operations on character data : n" ) ;
printf ( "Addition : %c n Subtraction : %c n" , x+y , x−y ) ;
printf ( " Multiplication : %c n Division : %c n Modulus : %c n" 
, x*y , x/y , x%y ) ;
}
18
2.1.4 Input and Output
Figure 14: Arithmetic operations between boolean, integer, float, and character data.
19
2.2 Swap Two Numbers
Write C programs to swap two integer numbers. a. With third variable, b. Without third variable.
2.2.1 Algorithm
1 Start
2 Declare three integer variables a, b and temp.
3 Get the values for a and b.
4 Store a’s value to temp. (temp := a)
5 Store b’s value to a. So, a has b’s value now. (a := b)
6 Store temp’s value (the value of the old a) in b.
7 Display a and b values.
8 stop.
Algorithm 8: Swap two integer numbers with third variable.
1 Start
2 Declare three integer variables a and b.
3 Get the values for a and b.
4 Store addition of a’s and b’s values to a. (a := a+b)
5 Subtract b from a, and store the result in b. (b := a-b)
6 Subtract b from a, and store the result in a (the value of the old a) in b. (a:= a-b)
7 Display the values of a and b.
8 stop.
Algorithm 9: Swap two integer numbers without third variable.
20
2.2.2 Flowchart
Figure 15: Swap two integer numbers with third variable.
Figure 16: Swap two integer numbers without third variable.
21
2.2.3 C Source Code
a . #include<stdio .h>
void main ( ) {
int a , b, temp;
printf ( "Enter two integer values : " ) ;
scanf ( "%d %d" , &a , &b ) ;
printf ( "a = %d, b = %d n" , a , b ) ;
temp = a ;
a = b;
b = temp;
printf ( " After swapping the values : n" ) ;
printf ( "a = %d, b = %d n" , a , b ) ;
}
b. #include<stdio .h>
void main ( ) {
int a , b;
printf ( "Enter two integer values : " ) ;
scanf ( "%d %d" , &a , &b ) ;
printf ( "a = %d, b = %d n" , a , b ) ;
a = a+b;
b = a−b;
a = a−b;
printf ( " After swapping the values : n" ) ;
printf ( "a = %d, b = %d n" , a , b ) ;
}
2.2.4 Input and Output
Figure 17: Swap a=5 and b=3 using third variable.
Figure 18: Swap a=5 and b=3 without third variable.
22
2.3 Comparison of Numbers
Write two C programs to find the greatest and smallest among three variables without using any
compound statements.
a. Using simple relational and logical operators.
b. Using the Ternary operator.
2.3.1 Algorithm
1 Start
2 Declare variable a, b, c, max, min.
3 Get the values for a, b and c.
4 Compute (a >= b && a >= c)*a + (b > a && b >= c)*b + (c > a && c > b)*c.
5 Store the result in max.
6 Compute (a <= b && a <= c)*a + (b < a && b <= c)*b + (c < a && c < b)*c.
7 Store the result in min.
8 Display max and min.
9 Stop.
Algorithm 10: The greatest and smallest among three variables using relational and logical
operators.
1 Start
2 Declare variables a, b, c, max, min.
3 Get the value of a, b and c.
4 If a > b go to step 5 Otherwise go to step 6.
5 If a > c, set max = a, otherwise max = c.
6 If b > c, set max = b, otherwise max = c.
7 If a < b go to step 8, otherwise go to step 9.
8 If a < c, set min = a, otherwise min = c.
9 If b < c, set min = b, otherwise min = c.
10 Display max and min.
11 Stop.
Algorithm 11: The greatest and smallest among three variables.
23
2.3.2 Flowchart
Figure 19: The greatest and smallest among three variables using relational and logical opera-
tors.
Figure 20: The greatest and smallest among three variables using the Ternary operators.
24
2.3.3 C Source Code
a . #include<stdio .h>
void main ( ) {
int a , b, c , max, min;
printf ( "Enter three integer values : " ) ;
scanf ( "%d %d %d" , &a , &b, &c ) ;
printf ( "a = %d, b = %d, c = %d n" , a , b, c ) ;
max = (a >= b && a >= c )* a + (b > a && b >=c )*b + ( c > a && c > b)* c ;
min = (a <= b && a <= c )* a + (b < a && b <=c )*b + ( c < a && c < b)* c ;
printf ( "Largest : %d n" , max) ;
printf ( "Smallest : %d" ,min) ;
}
b. #include<stdio .h>
void main ( ) {
int a , b, c , max, min;
printf ( "Enter three integer values : " ) ;
scanf ( "%d %d %d" , &a , &b, &c ) ;
printf ( "a = %d, b = %d, c = %d n" , a , b, c ) ;
max = (a>b ) ? ( ( a>c )? a : c ) : ( ( b>c )? b : c ) ;
min = (a<b ) ? ( ( a<c )? a : c ) : ( ( b<c )? b : c ) ;
printf ( "Largest : %d n" , max) ;
printf ( "Smallest : %d" ,min) ;
}
2.3.4 Input and Output
Figure 21: The greatest and smallest among a = 5, b = 7 and c = 2 using relational and logical
operators.
Figure 22: The greatest and smallest among a = 5, b = 7 and c = 2 using the Ternary operators.
25
2.4 Size and Range of C Data Types
Write a C program to display size and range of the below data types.
a. char
b. signed char
c. int
d. signed int
e. unsigned int
f. long int
g. long long int
h. intmax_t
i. size_t
j. float
k. double
l. long double
2.4.1 Algorithm
1 Start
2 Use the sizeof() operator to display the size of each datatype.
3 Display the size of char and signed char data types.
4 Display the size of int, signed int and unsigned int data types.
5 Display the size of long int and long long int data types.
6 Display the size of intmax_t and size_t data types.
7 Display the size of float, double and long double data types.
8 Use the stdio.h, stddef.h, stdint.h, limits.h and float.h header files to print the minimum
and maximum values of the data-types.
9 Display CHAR_MIN and CHAR_MAX.
10 Display SCHAR_MIN and SCHAR_MAX.
11 Display INT_MIN and INT_MAX.
12 Display UINT_MIN and UINT_MAX.
13 Display SHT_MIN and SHT_MAX.
14 Display LONG_MIN and LONG_MAX.
15 Display LLONG_MIN and LLONG_MAX.
16 Display INTMAX_MIN and INTMAX_MAX.
17 Display SIZE_MIN and SIZE_MAX.
18 Display FLT_MIN and FLT_MAX.
19 Display DBL_MIN and DBL_MAX.
20 Display LDBL_MIN and LDBL_MAX.
21 Stop.
Algorithm 12: The greatest and smallest among three variables using relational and logical
operators.
26
2.4.2 Flowchart
Figure 23: Data types’ ranges and sizes.
27
2.4.3 C Source Code
#include<stdio .h>
#include<stddef .h>
#include<stdint .h>
#include<limits .h>
#include<float .h>
#define UINT_MIN 0
#define SIZE_MIN 0
void main ( ) {
printf ( "char : %ld n" , sizeof (char ) ) ;
printf ( "signed char %ld n" , sizeof ( signed char ) ) ;
printf ( " int : %ld n" , sizeof ( int ) ) ;
printf ( "signed int : %ld n" , sizeof ( signed int ) ) ;
printf ( "unsigned int : %ld n" , sizeof (unsigned int ) ) ;
printf ( "long int : %ld n" , sizeof ( long int ) ) ;
printf ( "long long int : %ld n" , sizeof ( long long int ) ) ;
printf ( "intmax_t : %ld n" , sizeof ( intmax_t ) ) ;
printf ( " size_t : %ld n" , sizeof ( size_t ) ) ;
printf ( " float : %ld n" , sizeof ( float ) ) ;
printf ( "double : %ld n" , sizeof (double ) ) ;
printf ( "long double : %ld n" , sizeof ( long double ) ) ;
printf ( "The minimum value of CHAR is = %dn" , CHAR_MIN) ;
printf ( "The maximum value of CHAR is = %dn" , CHAR_MAX) ;
printf ( "The minimum value of Signed CHAR is = %dn" , SCHAR_MIN) ;
printf ( "The maximum value of Signed CHAR is = %dn" , SCHAR_MAX) ;
printf ( "The minimum value of INT is = %dn" , INT_MIN) ;
printf ( "The maximum value of INT is = %dn" , INT_MAX) ;
printf ( "The minimum value of signed INT is = %dn" , INT_MIN) ;
printf ( "The maximum value of signed INT is = %dn" , INT_MAX) ;
printf ( "The minimum value of Unsigned INT is = %un" , UINT_MIN) ;
printf ( "The maximum value of Unsigned INT is = %un" , UINT_MAX) ;
printf ( "The minimum value of Short INT is = %dn" , SHRT_MIN) ;
printf ( "The maximum value of Short INT is = %dn" , SHRT_MAX) ;
printf ( "The minimum value of LONG INT is = %ldn" , LONG_MIN) ;
printf ( "The maximum value of LONG INT is = %ldn" , LONG_MAX) ;
printf ( "The minimum value of LONG LONG INT is = %lld n" , LLONG_MIN) ;
printf ( "The maximum value of LONG LONG INT is = %lld n" , LLONG_MAX) ;
printf ( "The minimum value of INTMAX_T is = %lld n" , INTMAX_MIN) ;
printf ( "The maximum value of INTMAX_T is = %lld n" , INTMAX_MAX) ;
printf ( "The minimum value of SIZE_T is = %llu n" , SIZE_MIN ) ;
printf ( "The maximum value of SIZE_T is = %llu n" , SIZE_MAX ) ;
printf ( "The minimum value of float is = %.10en" , FLT_MIN) ;
printf ( "The maximum value of float is = %.10en" , FLT_MAX) ;
printf ( "The minimum value of Double is = %.10en" , DBL_MIN) ;
printf ( "The maximum value of Double is = %.10en" , DBL_MAX) ;
28
printf ( "The minimum value of LONG Double is = %.10Len" ,LDBL_MIN) ;
printf ( "The maximum value of LONG Double is = %.10Len" ,LDBL_MAX) ;
}
2.4.4 Input and Output
Figure 24: Size and range of C data types.
Objectives
To understand the roles of various of data types for performing different mathematical opera-
tions.
To provide a clear idea on variables and constants creation and their use in a C program.
To deliver a clear knowledge on void, integral and floating point data types and their use in dif-
ferent scenarios.
29
3
WEEK
Selection – Making Decisions
3.1 Even or Odd Number
Write a C program to check whether a given integer number is even or odd.
3.1.1 Algorithm
1 Start
2 Declare a variable num.
3 Get the value for num.
4 Perform num modulus 2 and check result if output is 0.
5 If true, display num is an even number.
6 If false, display num is an odd number.
7 Stop
Algorithm 13: Check a number is even or odd number.
30
3.1.2 Flowchart
Figure 25: Even or odd number.
31
3.1.3 C Source Code
#include<stdio .h>
void main ( ) {
int num;
printf ( "Enter an integer number : n" ) ;
scanf ( "%d" , &num) ;
i f (num % 2 == 0)
printf ( "%d is an even number" , num) ;
else
printf ( "%d is an odd number" , num) ;
}
3.1.4 Input and Output
Figure 26: Even or odd number.
32
3.2 Biggest and Smallest Number
Write a C program to find the biggest and smallest among the three numbers.
3.2.1 Algorithm
1 Start
2 Declare variables a, b and c.
3 Get the values of a, b and c.
4 If a > b go to step 5 Otherwise go to step 6.
5 If a > c display ’a is biggest’, otherwise ’c is biggest’.
6 If b > c display ’b is biggest’, otherwise ’c is biggest’.
7 Stop.
Algorithm 14: Biggest among three numbers.
1 Start
2 Declare variables a, b and c.
3 Get the values of a, b and c.
4 If a < b go to step 5 Otherwise go to step 6.
5 If a < c display ’a is smallest’, otherwise ’c is smallest’.
6 If b < c display ’b is smallest’, otherwise ’c is smallest’.
7 Stop.
Algorithm 15: Smallest among three numbers.
33
3.2.2 Flowchart
Figure 27: Biggest among three numbers.
Figure 28: Smallest among three numbers.
34
3.2.3 C Source Code
a . #include<stdio .h>
void main ( ) {
int a ,b, c ;
printf ( "Enter three integer numbers: n" ) ;
scanf ( "%d %d %d" , &a , &b, &c ) ;
i f (a>=b) {
i f (a>=c )
printf ( "%d is biggest n" , a ) ;
else
printf ( "%d is biggest n" , c ) ;
}
else {
i f (b>=c )
printf ( "%d is biggest n" , b ) ;
else
printf ( "%d is biggest n" , c ) ;
}
}
b. #include<stdio .h>
void main ( ) {
int a ,b, c ;
printf ( "Enter three integer numbers: n" ) ;
scanf ( "%d %d %d" , &a , &b, &c ) ;
i f (a<=b) {
i f (a<=c )
printf ( "%d is smallest n" , a ) ;
else
printf ( "%d is smallest n" , c ) ;
}
else {
i f (b<=c )
printf ( "%d is smallest n" , b ) ;
else
printf ( "%d is smallest n" , c ) ;
}
}
35
3.2.4 Input and Output
Figure 29: Largest among three numbers.
Figure 30: Smallest among three numbers.
36
3.3 Leap Year
Write a C program to check whether a year is a leap year or not.
3.3.1 Algorithm
1 Start
2 Take integer variable yr.
3 Assign value to the variable yr.
4 Check if yr is divisible by 100 and 400, display "yr is a leap year".
5 Check if yr is divisible by 4 but not 100, display "yr is a leap year".
6 Otherwise, display "yr is not leap year".
7 Stop.
Algorithm 16: Biggest among three numbers.
3.3.2 Flowchart
Figure 31: A year is a leap year or not.
37
3.3.3 C Source Code
#include<stdio .h>
void main ( ) {
int yr ;
printf ( "Enter a year to check leap yr . or not : " ) ;
scanf ( "%d" , &yr ) ;
i f ( yr%100 == 0 && yr%400 == 0)
printf ( "%d is a leap year" , yr ) ;
else i f ( yr%100 != 0 && yr%4 == 0)
printf ( "%d is a leap year" , yr ) ;
else
printf ( "%d is not a leap year" , yr ) ;
}
3.3.4 Input and Output
Figure 32: Verify year 1900 is a leap year or not.
38
3.4 Electricity Bill
Write a C program to print electricity bill with slabs.
Unit Charge/Unit
Up to 199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00
3.4.1 Algorithm
1 Start
2 Declare two variables units and ebill.
3 Enter total units consumed by the customer using the variable units.
4 If the units less than 200 units, calculates the ebill. [ebill := units*1.20].
5 If units between 200 to 400 units, calculates the ebill. [ebill := 199*1.20 +
(units-199)*1.50].
6 If units between 400 to 600 units ,calculates the ebill. [ebill := 199*1.20 + 200*1.50 +
(units-399)*1.80].
7 Else, calculates the ebill. [ebill := 199*1.20 +200*1.50 + 200*1.80 + (unit-599)*2.0].
8 Stop.
Algorithm 17: Compute electricity bill with slabs.
39
3.4.2 Flowchart
Figure 33: Compute electricity bill with slabs.
40
3.4.3 C Source Code
#include<stdio .h>
void main ( ) {
int units ;
float e b i l l ;
printf ( "Enter the amount of units consumed : n" ) ;
scanf ( "%d" , &units ) ;
i f ( units <200)
e b i l l = units * 1.20;
else i f ( units >= 200 && units < 400)
e b i l l = 199*1.20 + ( units −199)*1.50;
else i f ( units >= 400 && units < 600)
e b i l l = 199*1.20 + 200*1.50 + ( units −399)*1.80;
else
e b i l l = 199*1.20 + 200*1.50 + 200*1.80 + ( units −599)*2.0;
printf ( "The total e b i l l amount is %f " , e b i l l ) ;
}
3.4.4 Input and Output
Figure 34: Electricity bill calculation for the consumed units 260.
Objectives
To write programs using the if...else selection statements.
To understand the nested if...else statement and use it to solve problems that need multi-level
selection making decisions.
To write programs that use switch...case and else...if multi way statements to select one out of
several options.
41
4
WEEK
Looping Constructs and
Their Applications
4.1 Decimal to Binary Conversion
Write a C program to convert a decimal number to binary number using while loop.
4.1.1 Algorithm
1 Start
2 Declare four variables num, sum, rem and cnt.
3 Initialize sum and cnt to 0.
4 Get the decimal integer value for num.
5 Repeat step 6 to 8 until num == 0 is satisfied.
6 Divide num by 2 and store the reminder and quotient into rem and num.
7 Compute rem*10cnt
and it to the current sum.
8 Increment cnt by 1.
9 Display the value of sum.
10 Stop.
Algorithm 18: Decimal to binary conversion.
42
4.1.2 Flowchart
Figure 35: Decimal to binary conversion.
43
4.1.3 C Source Code
#include<stdio .h>
#include<math.h>
void main ( ) {
int num, rem, sum = 0 , cnt = 0;
printf ( "Enter a decimal number : " ) ;
scanf ( "%d" , &num) ;
while (num != 0){
rem = num % 2;
sum = rem * pow(10 , cnt ) + sum;
num = num/2;
cnt++;
}
printf ( "The binary no is %d" , sum) ;
}
4.1.4 Input and Output
Figure 36: Binary value of decimal number 10.
44
4.2 Factorial of a Number
Write a C program to find factorial of the given number using while loop.
4.2.1 Algorithm
1 Start
2 Declare two variables: num and fact, where fact is initialized to 1.
3 Get the decimal integer value for num.
4 Repeat step 5 and 6 until num == 0 is satisfied.
5 Multiply num to the current value of fact.
6 Decrement num by 1.
7 Display the value of fact.
8 Stop.
Algorithm 19: Factorial of a number.
4.2.2 Flowchart
Figure 37: Factorial of a number.
45
4.2.3 C Source Code
#include<stdio .h>
void main()
{
int num, fact = 1;
printf ( "Enter a integer number n" ) ;
scanf ( "%d" , &num) ;
while (num != 0){
fact = fact * num;
num−−;
}
printf ( " Factorial of a number is %d" , fact ) ;
}
4.2.4 Input and Output
Figure 38: Factorial of the number 6.
46
4.3 Reverse of a Number
Write a C program to print the reverse of a given number using while loop.
4.3.1 Algorithm
1 Start
2 Declare three variables num, sum and rem.
3 Initialize sum to 0.
4 Get the decimal integer value for num.
5 Repeat step 6 to 8 until num == 0 is satisfied.
6 Divide num by 2 and store the reminder and quotient into rem and num.
7 Multiply 10 to the already existing value of sum.
8 Add rem to the value of sum.
9 Display the value of sum.
10 Stop.
Algorithm 20: Reverse of a given number.
4.3.2 Flowchart
Figure 39: Reverse of a given number.
47
4.3.3 C Source Code
#include<stdio .h>
void main()
{
int num, rem, sum = 0;
printf ( "Enter a integer number n" ) ;
scanf ( "%d" , &num) ;
while (num != 0){
rem = num % 10;
sum = sum * 10 + rem;
num = num / 10;
}
printf ( "The reverse no is : %d" , sum) ;
}
4.3.4 Input and Output
Figure 40: Reverse of the given number 12345.
48
4.4 Strong Number
Write a C program to check whether the given number strong number or not.
4.4.1 Algorithm
1 Start
2 Declare six variables: i, j, fact, num, rem and sum.
3 Initialize sum to 0.
4 Get the decimal integer value for num.
5 Place num’s value into i.
6 Repeat step 7 to 13 until i == 0 is satisfied.
7 Divide i by 10 and store reminder and quotient in rem and i.
8 Initialize fact to 1.
9 Place rem’s value to j.
10 Repeat step 11 and 12 until j == 0 is satisfied.
11 Multiply j with current value of fact.
12 Decrement j by 1.
13 Add fact’s value to the current value of sum.
14 If sum is equal to num, then display "A strong number".
15 Else, display "Not a strong number".
16 Stop.
Algorithm 21: Verify a number is a strong number or not.
49
4.4.2 Flowchart
Figure 41: Verify a number is a strong number or not.
50
4.4.3 C Source Code
#include<stdio .h>
void main ( ) {
int num, i , j , rem, fact , sum = 0;
printf ( "Enter a integer number n" ) ;
scanf ( "%d" , &num) ;
for ( i = num; i != 0; i = i /10){
rem = i % 10;
fact = 1;
for ( j = rem; j != 0; j −−)
fact = fact * j ;
sum = sum + fact ;
}
i f (sum == num)
printf ( "%d is a strong number" , num) ;
else
printf ( "%d is not a strong number" , num) ;
}
4.4.4 Input and Output
Figure 42: Verify 145 is a strong number or not.
51
4.5 Armstrong Number
Write a C program to check whether the given number is an Armstrong number or not using the
do ...while loop.
4.5.1 Algorithm
1 Start
2 Declare five variables: sum, num, temp and num_size.
3 Initialize sum to 0.
4 Get the values for num_size and num.
5 Place num value into temp.
6 Divide temp by 10 and store the reminder and quotient into rem and temp.
7 Compute remnum_size
and add it to sum.
8 Repeat step 6 and 7 until temp == 0 is satisfied.
9 If num == sum then display "An Armstrong number".
10 Else, display "Not an Armstrong number".
11 Stop.
Algorithm 22: Verify a number is an Armstrong number or not.
52
4.5.2 Flowchart
Figure 43: Verify a number is an Armstrong number or not.
53
4.5.3 C Source Code
#include<stdio .h>
#include<math.h>
void main ( ) {
int num, temp, rem, size , sum = 0;
printf ( "Enter the size of a number n" ) ;
scanf ( "%d" , &size ) ;
printf ( "Enter a integer number n" ) ;
scanf ( "%d" , &num) ;
temp = num;
do{
rem = temp % 10;
sum = sum + pow(rem, size ) ;
temp = temp/10;
} while (temp != 0);
i f (num == sum)
printf ( "%d is an Armstrong number" , num) ;
else
printf ( "%d is not an Armstrong number" , num) ;
}
4.5.4 Input and Output
Figure 44: Verify 1634 is an Armstrong number or not.
54
4.6 Fibonacci Series
Write a program to generate Fibonacci series up to n number using do....while loop.
4.6.1 Algorithm
1 Start
2 Declare five variables: f1, f2, f3, cnt and steps.
3 Initialize f1 = 0, f2 = 1 and cnt = 0.
4 Read the step numbers into steps.
5 Display f1.
6 Add f1 with f2 and store the result into f3.
7 Place f2 value into f1.
8 Place f3 value into f2.
9 Increment cnt by 1.
10 Repeat step 5 to 9 till cnt <= steps is satisfied.
11 Stop.
Algorithm 23: Fibonacci series up to n number using do....while loop.
55
4.6.2 Flowchart
Figure 45: Fibonacci series up to step = steps.
56
4.6.3 C Source Code
#include<stdio .h>
void main()
{
int f1 = 0 , f2 = 1 , f3 , cnt = 0 , steps ;
printf ( "Enter the no. of steps to print fibonacci series : " ) ;
scanf ( "%d" , &steps ) ;
do
{
printf ( "%d n" , f1 ) ;
f3 = f1 + f2 ;
f1 = f2 ;
f2 = f3 ;
cnt++;
} while ( cnt < steps ) ;
}
4.6.4 Input and Output
Figure 46: Fibonacci series up to step 7.
57
4.7 Palindrome Number
Write a C program to check whether the given number is Palindrome or not using the for loop.
4.7.1 Algorithm
1 Start
2 Declare four variables: sum, num, rem and i.
3 Initialize sum to 0.
4 Get the value for num.
5 Place num’s value into i.
6 Repeat step 7 to 9 till i is not equal to zero is satisfied.
7 Divide i by 10 and store reminder and quotient in rem and i.
8 Multiply 10 to the current value of sum.
9 Add rem’s value to the already existing value of sum.
10 If sum == num then display "A Palindrome".
11 Else, display "Not a palindrome".
12 Stop.
Algorithm 24: Verify a number is a palindrome or not.
58
4.7.2 Flowchart
Figure 47: Verify a number is a palindrome or not.
59
4.7.3 C Source Code
#include<stdio .h>
void main ( ) {
int i , num, rem, sum = 0;
printf ( "Enter an integer number n" ) ;
scanf ( "%d" , & num) ;
for ( i = num; i != 0; i = i /10){
rem = i % 10;
sum = sum * 10 + rem;
}
i f (sum == num)
printf ( "%d is a palindrome" , num) ;
else
printf ( "%d is not a palindrome" , num) ;
}
4.7.4 Input and Output
Figure 48: Verify 12321 is a palindrome or not.
60
4.8 Perfect Number
Write a C program to check whether the given number is perfect or not using the for loop.
4.8.1 Algorithm
1 Start
2 Declare three variables: num, sum and i.
3 Initialize sum to 0.
4 Get the value for num.
5 Initialize i to 1.
6 Repeat step 7 and 8 till i is not equal to num satisfied.
7 If num is divisible by i, then add i’s value to sum.
8 Increment i by 1.
9 If sum == num then display "Perfect number".
10 Else, display "Not a Perfect number".
11 Stop.
Algorithm 25: Verify a number is a perfect number or not.
61
4.8.2 Flowchart
Figure 49: Verify a number is a perfect number or not.
62
4.8.3 C Source Code
#include<stdio .h>
void main ( ) {
int i , num, sum = 0;
printf ( "Enter a +ve integer number : " ) ;
scanf ( "%d" , &num) ;
for ( i = 1; i < num; i ++){
i f (num % i == 0)
sum = sum + i ;
}
i f (sum == num)
printf ( "%d is a perfect number" , num) ;
else
printf ( "%d is not a perfect number" , num) ;
}
4.8.4 Input and Output
Figure 50: Verify 28 is a perfect number or not.
63
4.9 Print Patterns
Write a C program to print * in right angle and equilateral triangle patterns using Nested for loop.
4.9.1 Algorithm
1 Start
2 Declare three variables: size, i and j.
3 Get the value for size.
4 Initialize i to 1.
5 Repeat step 6 to 11 until i is greater than size satisfied.
6 Initialize j to 1.
7 Repeat step 8 and 9 until j is greater than i satisfied.
8 Display ’*’.
9 Increment j by 1.
10 Create new line by printing ’n’ escape sequence.
11 Increment i by 1.
12 Stop.
Algorithm 26: * in right angle triangle pattern.
1 Start
2 Declare four variables: size, i, j and k.
3 Get the value for size, and Initialize i to 1.
4 Repeat step 5 to 12 until i is greater than size satisfied.
5 Initialize j to size-i.
6 Repeat step 7 until j is equal to 0 satisfied.
7 Print an empty space, and decrement j by 1.
8 Initialize k to 1.
9 Repeat step 12 and 13 until k is greater than i satisfied.
10 Display "* ", and increment k by 1.
11 Create new line by printing ’n’ escape sequence.
12 Increment i by 1.
13 Stop.
Algorithm 27: * in equilateral triangle pattern.
64
4.9.2 Flowchart
Figure 51: * in right angle triangle pattern.
65
.
Figure 52: * in equilateral triangle pattern.
66
4.9.3 C Source Code
a . #include<stdio .h>
void main()
{
int i , j , size ;
printf ( "Enter size of the lateral : " ) ;
scanf ( "%d" , &size ) ;
for ( i = 1; i <= size ; i ++)
{
for ( j = 1; j <= i ; j ++)
printf ( "*" ) ;
printf ( "n" ) ;
}
}
b. #include<stdio .h>
void main()
{
int i , j , k , size ;
printf ( "Enter size of the lateral : " ) ;
scanf ( "%d" , &size ) ;
for ( i = 1; i <= size ; i ++)
{
for ( j = size − i ; j != 0; j −−)
printf ( " " ) ;
for (k = 1; k <= i ; k++)
printf ( "* " ) ;
printf ( "n" ) ;
}
}
67
4.9.4 Input and Output
Figure 53: * in right angle triangle pattern of size = 5.
Figure 54: * in equilateral triangle pattern of size = 5.
68
4.10 Prime Numbers
Write a program to print the prime numbers between 1 to n using nested for loop.
4.10.1 Algorithm
1 Start
2 Declare four variables: num, i, j and flag.
3 Get the value for num.
4 Initialize i to 2.
5 Repeat step 6 to 12 until i is greater than num satisfied.
6 Initialize flag to 0.
7 Initialize j to 2.
8 Repeat step 9 and 10 until j is equal to i satisfied.
9 If i is divisible by j, set flag to 1 and go to step 12.
10 Increment j by 1.
11 If flag is equal to zero, display i value.
12 Increment i by 1.
13 Stop.
Algorithm 28: Prime numbers between 1 and n.
69
4.10.2 Flowchart
Figure 55: Prime numbers between 1 and n.
70
4.10.3 C Source Code
#include<stdio .h>
void main ( ) {
int i , j , num, flag ;
printf ( "Enter the n value : " ) ;
scanf ( "%d" , &num) ;
for ( i = 2; i <= num; i ++){
flag = 0;
for ( j = 2; j <= i −1; j ++){
i f ( i % j == 0){
flag = 1;
break ;
}
}
i f ( flag == 0)
printf ( "%d " , i ) ;
}
}
4.10.4 Input and Output
Figure 56: Prime numbers between 1 and 50.
Objectives
To have a clear idea on pretest and post-test loops.
To understand basic loop initialization, validation and updation.
To write programs using the while, for, or do...while loops.
To understand the logic and adopt best looping construct for different kinds of problems.
71
5
WEEK
Unconditional Control
Transfer Statements
5.1 Calculator Application
Write a C program to implement calculator application using switch...case...break.
5.1.1 Algorithm
1 Start
2 Take two numbers as input and store it in the variables a and b.
3 Take an input to let the user choose the operation that needs to be performed.
4 If choice is 1, then perform a+b and store it in c. go to step 10
5 If choice is 2, then perform a-b and store it in c. go to step 10
6 If choice is 3, then perform a*b and store it in c. go to step 10
7 If choice is 4, then perform a/b and store it in c. go to step 10
8 If choice is 5, then perform a%b and store it in c. go to step 10
9 Else, display "Invalid option", go to step 11.
10 Display the value of c.
11 Stop.
Algorithm 29: Calculator application to perform arithmetic operations.
72
5.1.2 Flowchart
Figure 57: Calculator application to perform arithmetic operations.
73
5.1.3 C Source Code
#include<stdio .h>
void main ( ) {
int a , b, c , i ;
printf ( "Enter two integer number : " ) ;
scanf ( "%d %d" , &a , &b ) ;
printf ( "Enter your choice : n" ) ;
printf ( " [1] Addition n[2] Subtraction n" ) ;
printf ( " [3] Multiplication n[4] Division n[5] Modulus n" ) ;
scanf ( "%d" , &i ) ;
switch ( i ) {
case 1: c = a + b;
printf ( "Addition : %d n" , c ) ;
break ;
case 2: c = a − b;
printf ( "Subtraction : %d n" , c ) ;
break ;
case 3: c = a * b;
printf ( " Multiplication : %d n" , c ) ;
break ;
case 4: c = a / b;
printf ( "Division : %d n" , c ) ;
break ;
case 5: c = a % b;
printf ( "Modulus : %d n" , c ) ;
break ;
default : printf ( " Invalid Option n" ) ;
}
}
5.1.4 Input and Output
Figure 58: Calculator application to perform arithmetic operations.
74
5.2 Sum of N Natural Numbers
Write a C program to find sum of 1 to n Natural numbers using goto statement.
5.2.1 Algorithm
1 Start
2 Declare three variables sum, n and i.
3 Get the value for n to add numbers from 1 to n.
4 Initialize sum to zero.
5 Initialize i to one.
6 Add i value to the current value of sum.
7 Increment i by 1.
8 if i is less than n, go to step 6, else go to next step.
9 Display the value of sum.
10 Stop.
Algorithm 30: Sum of 1 to n Natural numbers.
5.2.2 Flowchart
Figure 59: Sum of 1 to n Natural numbers.
75
5.2.3 C Source Code
#include<stdio .h>
void main ( ) {
int i = 1 , n, sum = 0;
printf ( "Enter the value of n : n" ) ;
scanf ( "%d" , &n ) ;
start :
sum += i ;
i ++;
i f ( i <= n)
goto start ;
printf ( "The sum is : %d n" , sum) ; }
5.2.4 Input and Output
Figure 60: Sum of 1 to 10 Natural numbers.
76
5.3 Even Numbers not Divisible by 6 and 8
Write a C program to print all the even numbers except the numbers, which are divisible by 6
and 8 using continue statement.
5.3.1 Algorithm
1 Start
2 Declare two variables n and i.
3 Get the value for n for printing even numbers between 1 and n.
4 Initialize i to zero.
5 Repeat step 5 to 8 until i is greater than n.
6 If is divisible by 6 and/or 8, go to step 8, else go to step 7.
7 Display the value of i.
8 Increment i by 2.
9 Stop.
Algorithm 31: Even numbers up to n except the numbers divisible by 6 and 8.
5.3.2 Flowchart
Figure 61: Even numbers up to n except the numbers divisible by 6 and 8.
77
5.3.3 C Source Code
#include<stdio .h>
void main ( ) {
int n, i ;
printf ( "Enter the value of n : n" ) ;
scanf ( "%d" , &n ) ;
for ( i = 0; i <= n; i +=2){
i f ( i%6 == 0 | | i%8 == 0)
continue ;
else
printf ( "%d n" , i ) ;
}
}
5.3.4 Input and Output
Figure 62: Even numbers up to 20 except the numbers divisible by 6 and 8.
Objectives
To understand the use of (break, continue, goto) unconditional control transfer statements in C
programs.
To understand the role of break and continue statements inside loop compound statements.
To use the goto statement to transfer the control from one part to another part of a program.
78
6
WEEK
Arrays and Their
Applications
6.1 Minimum and Maximum Elements
Write a C program to find maximum and minimum elements in the given array.
6.1.1 Algorithm
1 Start
2 Declare four variables min, max, i and an array arr.
3 Initialize i to 0.
4 Repeat step 5 and 6 until i is equal to size satisfied.
5 Get the value for arr[i].
6 Increment i by 1.
7 Place arr[0] value in min and max.
8 Initialize i to 1.
9 Repeat step 10 and 11 until i is equal to size satisfied.
10 If arr[i] is greater than max then store arr[i]’s value in max.
11 If arr[i] is smaller than min then store arr[i]’s value in min.
12 Increment i by 1.
13 Display max’s and min’s values.
14 Stop.
Algorithm 32: Maximum and minimum elements in an array.
79
6.1.2 Flowchart
Figure 63: Maximum and minimum elements in an array.
80
6.1.3 C Source Code
#include<stdio .h>
void main()
{
int arr [7] , min, max, i ;
printf ( "Enter the elements of an array : n" ) ;
for ( i = 0; i < 7; i ++)
scanf ( "%d" , &arr [ i ] ) ;
min = max = arr [ 0 ] ;
for ( i = 1; i < 7; i ++)
{
max = ( arr [ i ] > max)? arr [ i ] :max;
min = ( arr [ i ] < min)? arr [ i ] : min;
}
printf ( "The maximum is : %d and the minimum is : %d n" , max, min) ;
}
6.1.4 Input and Output
Figure 64: Maximum and minimum elements in the given array.
81
6.2 Sorting of n numbers
Write a C program to sort the elements is ascending order in the given array.
6.2.1 Algorithm
1 Start
2 Declare five variables min, temp, i, j and an array arr.
3 Initialize i to 0.
4 Repeat step 5 and 6 until i is equal to size satisfied.
5 Get the value for arr[i].
6 Increment i by 1.
7 Reinitialize i to 0.
8 Repeat step 9 and 17 until i is equal to size-1 satisfied.
9 Assign i’s value to min.
10 Initialize j to i+1.
11 Repeat step 12 and 13 until j is equal to size satisfied.
12 If arr[j] is less than arr[min] then assign j to min.
13 Increment j by 1.
14 Store arr[i]’s value in temp.
15 Store arr[min]’s value in arr[i].
16 Store temp’s value in arr[min].
17 Increment i by 1.
18 Reinitialize i to 0.
19 Repeat step 20 until i is equal to size satisfied.
20 Display the value for arr[i].
21 Stop.
Algorithm 33: Sort elements of the given array using Selection sort.
82
6.2.2 Flowchart
Figure 65: Sort elements of the given array using Selection sort.
83
6.2.3 C Source Code
#include<stdio .h>
void main ( ) {
int arr [7] , min, temp, i , j ;
printf ( "Enter the elements of an array : n" ) ;
for ( i = 0; i < 7; i ++)
scanf ( "%d" , &arr [ i ] ) ;
/ / Do the sorting [ selection sort ]
for ( i = 0; i < 6; i ++){
min = i ;
for ( j = i +1; j < 7; j ++)
min = ( arr [ j ] < arr [min] ) ? j :min;
temp = arr [ i ] ;
arr [ i ] = arr [min ] ;
arr [min] = temp; }
printf ( "the elements after the sorting : n" ) ;
for ( i = 0; i < 7; i ++)
printf ( "%d  t " , arr [ i ] ) ; }
6.2.4 Input and Output
Figure 66: Elements of the given array after sorting.
84
6.3 Searching
Write a C program to search an element in the given array.
6.3.1 Algorithm
1 Start
2 Declare five variables: i, num, index, flag and an array arr.
3 Store {a1, a2, a3, ..., aN} in arr.
4 Initialize flag and i to 0.
5 Get the value for num.
6 Repeat step 7 to 9 until i is equal to N satisfied.
7 If arr[i] is equal to num, then set flag to 1.
8 Assign i’s value to index go to step 11.
9 Increment i by 1.
10 If flag is one, display index’s value.
11 Else, display "Element is not present".
12 Stop.
Algorithm 34: Search an element in an array using linear search.
85
6.3.2 Flowchart
Figure 67: Search an element in an array using linear search.
86
6.3.3 C Source Code
#include<stdio .h>
#include<stdbool .h>
void main()
{
int i , num, index , arr [7] = {9 , 8 , 3 , 6 , 7 , 10 , 2};
bool flag = 0;
printf ( "Enter the element to be searched : n" ) ;
scanf ( "%d" , &num) ;
for ( i = 0; i < 7; i ++)
{
i f ( arr [ i ] == num)
{
flag = 1; index = i ;
break ;
}
}
i f ( flag )
printf ( "Element is found at %dth location . n" , index ) ;
else
printf ( "Element is not present in the array . n" ) ;
}
6.3.4 Input and Output
Figure 68: Search an element 3 in the given array.
87
6.4 Insertion
Write a C program to insert an element at a specified location in an array.
6.4.1 Algorithm
1 Start
2 Declare five variables: num, pos, i, last_index and an array arr of size 10.
3 Initialize i to 0.
4 Repeat step 5 and 6 until i is equal to 6 satisfied.
5 Get the value for arr[i].
6 Increment i by 1.
7 Initialize last_index to i-1.
8 Read values for num and pos.
9 If pos < 0 or pos > 9, then display "Not possible".
10 If pos > 6, assign num and i’s values to arr[i] and last_index, go to step 16.
11 Else, initialize j to i.
12 Repeat step 13 and 14 until j is equal to pos satisfied.
13 Assign arr[j-1]’s value to arr[j].
14 Decrement j by 1.
15 Assign num’s value to arr[pos] and i’s value to last_index.
16 Reinitialize j to 0.
17 Repeat step 18 and 19 until j is equal to last_index.
18 Display the value of arr[j].
19 Increment j by 1.
20 Stop.
Algorithm 35: Insert a number at a given location in an array.
88
6.4.2 Flowchart
Figure 69: Insert a number at a given location in an array.
89
6.4.3 C Source Code
#include<stdio .h>
void main ( ) {
int arr [10] , num, pos , i , last_index ;
printf ( "Enter the elements of an array : n" ) ;
for ( i = 0; i < 7; i ++)
scanf ( "%d" , &arr [ i ] ) ;
last_index = i −1;
printf ( "Enter the element and i t s position : n" ) ;
scanf ( "%d %d" , &num, &pos ) ;
i f (pos < 0 | | pos > 9)
printf ( " Insertion is not possible n" ) ;
else i f (pos > 6){
arr [ i ] = num;
last_index = i ;
}
else {
for ( int j = i ; j != pos ; j −−)
arr [ j ] = arr [ j −1];
arr [pos] = num;
last_index = i ;
}
printf ( " Print the updated array : n" ) ;
for ( int j = 0; j <= last_index ; j ++)
printf ( "%d  t " , arr [ j ] ) ;
}
6.4.4 Input and Output
Figure 70: Insert 4 at 3rd location in the given array.
90
6.5 Remove Duplicate
Write a C program to remove duplicate elements from the given array.
6.5.1 Algorithm
1 Start
2 Declare six variables:i, j, final_index, array A, array B and array flag.
3 Initialize final_index to 0 and flag[size] = {0}.
4 Initialize i to 0.
5 Repeat step 6 and 7 until i is equal to size satisfied.
6 Read value for A[i].
7 Increment i by 1.
8 Reinitialize i to 0.
9 Repeat step 10 to 17 until i is equal to size satisfied.
10 if flag == 0, go to next step else go to step 17.
11 Store A[i]’s value in B[final_index].
12 Increment final_index by 1.
13 Initialize j to i+1.
14 Repeat step 15 and 16 until j is equal to size satisfied.
15 If A[i] is equal to A[j], then store 1 in flag[j].
16 Increment j by 1.
17 Increment i by 1.
18 Reinitialize i to 0.
19 Repeat 20 and 21 until i is equal to final_index satisfied.
20 Display the value of B[i].
21 Increment i by 1.
22 Stop
Algorithm 36: Remove duplicate elements from an array.
91
6.5.2 Flowchart
Figure 71: Remove duplicate elements from an array.
92
6.5.3 C Source Code
#include<stdio .h>
void main ( ) {
int i , j , A[10] , B[10] , final_index = 0 , 
flag [10]={0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0};
printf ( "Enter the elements for array A : n" ) ;
for ( i = 0; i <= 9; i ++)
scanf ( "%d" , &A[ i ] ) ;
printf ( "A : " ) ;
for ( i = 0; i <= 9; i ++)
printf ( "%d  t " , A[ i ] ) ;
printf ( "n" ) ;
/ / remove duplicate elements
for ( i = 0; i <= 9; i ++){
i f ( flag [ i ] == 0){
B[ final_index ] = A[ i ] ;
final_index ++;
for ( j = i +1; j <= 9; j ++){
i f (A[ i ] == A[ j ] )
flag [ j ] = 1;
}
}
}
/ / print the output array
printf ( "B : " ) ;
for ( i = 0; i < final_index ; i ++)
printf ( "%d  t " , B[ i ] ) ;
}
6.5.4 Input and Output
Figure 72: Array elements before, and its elements after removal of duplicates.
93
6.6 Matrix Addition
Write a C program to find the sum of two matrices.
6.6.1 Algorithm
1 Start
2 Declare five variables: i, j, array A, array B and array C.
3 Initialize i to 0.
4 Repeat step 5 to 10 until i is equal to size satisfied.
5 Initialize j to 0.
6 Repeat step 7 to 9 until j is equal to size satisfied.
7 Read the value for A[i][j].
8 Read the value for B[i][j].
9 Increment j by 1.
10 Increment i by 1.
11 Reinitialize i to 0.
12 Repeat step 13 to 17 until i is equal to size satisfied.
13 Reinitialize j to 0.
14 Repeat step 15 and 16 until j is equal to size satisfied.
15 Add A[i][j]’s value with B[i][j]’s value and store the result in C[i][j].
16 Increment j by 1.
17 Increment i by 1.
18 Reinitialize i to 0.
19 Repeat step 20 to 24 until i is equal to size satisfied.
20 Reinitialize j to 0.
21 Repeat step 22 and 23 until j is equal to size satisfied.
22 Display the value of C[i][j].
23 Increment j by 1.
24 Increment i by 1.
25 Stop
Algorithm 37: Summation of two size * size matrices.
94
6.6.2 Flowchart
Figure 73: Summation of two size * size matrices.
95
6.6.3 C Source Code
#include<stdio .h>
void main ( ) {
int i , j , A[ 3 ] [ 3 ] , B[ 3 ] [ 3 ] , C[ 3 ] [ 3 ] ;
printf ( "Enter the elements for array A n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++){
printf ( "n[%d][%d] element of A is : " , i , j ) ;
scanf ( "%d" , &A[ i ] [ j ] ) ;
}
}
printf ( "Enter the elements for array B n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++){
printf ( "n[%d][%d] element of B is : " , i , j ) ;
scanf ( "%d" , &B[ i ] [ j ] ) ;
}
}
printf ( "A : n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++)
printf ( "%d t " , A[ i ] [ j ] ) ;
printf ( "n" ) ;
}
printf ( "B : n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++)
printf ( "%d t " , B[ i ] [ j ] ) ;
printf ( "n" ) ;
}
/ / perform matrix addition operation
for ( i = 0; i <= 2; i ++){
for ( j = 0; j <= 2; j ++){
C[ i ] [ j ] = A[ i ] [ j ] + B[ i ] [ j ] ;
}
}
/ / final output matrix
printf ( "C : n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j = 0; j <= 2; j ++)
printf ( "%d t " , C[ i ] [ j ] ) ;
printf ( "n" ) ;
}
}
96
6.6.4 Input and Output
Figure 74: Summation of two 3*3 matrices.
97
6.7 Matrix Multiplication
Write a C program to perform matrix multiplication between two matrices.
6.7.1 Algorithm
1 Start
2 Declare seven variables: i, j, k, sum, array A, array B and array C.
3 Initialize i to 0.
4 Repeat step 5 to 10 until i is equal to size satisfied.
5 Initialize j to 0.
6 Repeat step 7 to 9 until j is equal to size satisfied.
7 Read the value for A[i][j].
8 Read the value for B[i][j].
9 Increment j by 1.
10 Increment i by 1.
11 Reinitialize i to 0.
12 Repeat step 13 to 21 until i is equal to size satisfied.
13 Reinitialize j to 0.
14 Repeat step 15 to 20 until j is equal to size satisfied.
15 Initialize sum and k to 0.
16 Repeat step 17 and 18 until k is equal to size satisfied.
17 Multiply A[i][k] with B[k][j] and add it to the current of value of sum.
18 Increment k by 1.
19 Store sum’s value in C[i][j].
20 Increment j by 1.
21 Increment i by 1.
22 Reinitialize i to 0.
23 Repeat step 24 to 28 until i is equal to size satisfied.
24 Reinitialize j to 0.
25 Repeat step 26 and 27 until j is equal to size satisfied.
26 Display the value of C[i][j].
27 Increment j by 1.
28 Increment i by 1.
29 Stop
Algorithm 38: Multiplication of two size*size matrices.
98
6.7.2 Flowchart
Figure 75: Multiplication of two size*size matrices.
99
6.7.3 C Source Code
#include<stdio .h>
void main()
{
int i , j , k , A[ 3 ] [ 3 ] , B[ 3 ] [ 3 ] , C[ 3 ] [ 3 ] , sum;
printf ( "Enter the elements for array A n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++){
printf ( "n[%d][%d] element of A is : " , i , j ) ;
scanf ( "%d" , &A[ i ] [ j ] ) ;
}
}
printf ( "Enter the elements for array B n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++){
printf ( "n[%d][%d] element of B is : " , i , j ) ;
scanf ( "%d" , &B[ i ] [ j ] ) ;
}
}
printf ( "A : n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++)
printf ( "%d t " , A[ i ] [ j ] ) ;
printf ( "n" ) ;
}
printf ( "B : n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j =0; j <=2; j ++)
printf ( "%d t " , B[ i ] [ j ] ) ;
printf ( "n" ) ;
}
/ / matrix multiplication operation
for ( i = 0; i <= 2; i ++){
for ( j = 0; j <= 2; j ++){
sum = 0;
for (k = 0; k <=2; k++)
sum = sum + A[ i ] [ k] * B[k ] [ j ] ;
C[ i ] [ j ] = sum;
}
}
/ / final output matrix
printf ( "C : n" ) ;
for ( i = 0; i <= 2; i ++){
for ( j = 0; j <= 2; j ++)
printf ( "%d t " , C[ i ] [ j ] ) ;
100
printf ( "n" ) ;
}
}
6.7.4 Input and Output
Figure 76: Multiplication of two 3*3 matrices.
101
6.8 Matrix Transpose
Write a C program to find the transpose of a matrix.
6.8.1 Algorithm
1 Start
2 Declare four variables: i, j, array A and array B.
3 Initialize i to 0.
4 Repeat step 5 to 9 until i is equal to size satisfied.
5 Initialize j to 0.
6 Repeat step 7 and 8 until j is equal to size satisfied.
7 Read the value for A[i][j].
8 Increment j by 1.
9 Increment i by 1.
10 Reinitialize i to 0.
11 Repeat step 12 to 18 until i is equal to size satisfied.
12 Reinitialize j to 0.
13 Repeat step 14 and 15 until j is equal to size satisfied.
14 Place A[j][i]’s value in B[i][j].
15 Increment j by 1.
16 Increment i by 1.
17 Reinitialize i to 0.
18 Repeat step 19 to 23 until i is equal to size satisfied.
19 Initialize j to 0.
20 Repeat step 21 and 22 until j is equal to size satisfied.
21 Display the value B[i][j].
22 Increment j by 1.
23 Increment i by 1.
24 Stop
Algorithm 39: Transpose of a size*size matrix.
102
6.8.2 Flowchart
Figure 77: Transpose of a size*size matrix.
103
6.8.3 C Source Code
#include<stdio .h>
void main()
{
int i , j , A[ 3 ] [ 3 ] , B[ 3 ] [ 3 ] ;
printf ( "Enter the elements for array A n" ) ;
for ( i = 0; i <= 2; i ++)
{
for ( j =0; j <= 2; j ++)
{
printf ( "n[%d][%d] element of A is : " , i , j ) ;
scanf ( "%d" , &A[ i ] [ j ] ) ;
}
}
printf ( "A : n" ) ;
for ( i = 0; i <= 2; i ++)
{
for ( j = 0; j <= 2; j ++)
printf ( "%d t " , A[ i ] [ j ] ) ;
printf ( "n" ) ;
}
/ / Transpose of matrix
for ( i = 0; i <= 2; i ++){
for ( j =0; j <= 2; j ++)
B[ i ] [ j ] = A[ j ] [ i ] ;
}
/ / Output matrix
printf ( "B : n" ) ;
for ( i = 0; i <= 2; i ++)
{
for ( j = 0; j <= 2; j ++)
printf ( "%d t " , B[ i ] [ j ] ) ;
printf ( "n" ) ;
}
}
104
6.8.4 Input and Output
Figure 78: Transpose of a 3*3 matrix.
Objectives
To utilize one dimensional and multi-dimensional arrays to solve problems that use set(s) of
similar type input data.
To have a clear idea on passing an complete array or array element as an argument to a function.
To write programs that perform multiple classical operations like searching, sorting, updation,
or deletion on array elements.
105
7
WEEK
Strings, String I/O and
Manipulation Functions
7.1 String Length
Write a C program to find length of a string with and without using string handling functions.
7.1.1 Algorithm
1 Start
2 Declare two variables: size and an array str.
3 Read the string into str.
4 Call the string length function strlen(str) and assign length to size.
5 Display the value of size.
6 Stop
Algorithm 40: Length of a string using string handling functions.
1 Start
2 Declare three variables: i, cnt and an array str.
3 Initialize the values of cnt and i to 0.
4 Read the string into str.
5 Repeat the step 6 and 7 until str[i] != ’0’ is satisfied.
6 Increment the value of cnt by 1.
7 Increment the value of i by 1.
8 Display the value of cnt that is the length of the string.
9 Stop
Algorithm 41: Length of a string without using string handling functions.
106
7.1.2 Flowchart
Figure 79: Length of a string using string handling functions.
Figure 80: Length of a string without using string handling functions.
107
7.1.3 C Source Code
a . #include<stdio .h>
#include<string .h>
void main()
{
char str [30];
printf ( "enter the string value n" ) ;
gets ( str ) ;
printf ( "The size of the ’%s ’ is : %lu n" , str , strlen ( str ) ) ;
}
b. #include<stdio .h>
void main()
{
char str [30];
int cnt = 0;
printf ( "enter the string value : n" ) ;
gets ( str ) ;
/ / Count the size of the string
while ( str [ cnt ] != ’ 0 ’ )
cnt++;
printf ( "The size of the ’%s ’ is : %d n" , str , cnt ) ;
}
7.1.4 Input and Output
Figure 81: Length of "S&H, VRSEC, Vijayawada" using string handling functions.
Figure 82: Length of "VRSEC, Vijayawada" without using string handling functions.
108
7.2 Reverse a String
Write a C program to reverse a string with and without using string handling functions.
7.2.1 Algorithm
1 Start
2 Declare an array str and read the string into it.
3 Call the string reverse function strrev(str) and result is stored in str.
4 Display the value of str.
5 Stop
Algorithm 42: Reverse a string using string handling function.
1 Start
2 Declare four variables: i, cnt, character arrays str and revstr.
3 Initialize the value of cnt to 0.
4 Read the string into str.
5 Repeat the step 6 until str[cnt]!=’0’ is satisfied.
6 Increment the value of cnt by 1.
7 Initialize the value of i to 0.
8 Repeat the step 9 and 10 till i < cnt is satisfied.
9 Place str[cnt-1-i]’s value in revstr[i].
10 Increment the value of i by 1.
11 Store ’0’ in revstr[i].
12 Display the value of str.
13 Stop
Algorithm 43: Reverse a string without using string handling function.
7.2.2 Flowchart
Figure 83: Reverse a string using string handling function.
109
.
Figure 84: Reverse a string without using string handling function.
110
7.2.3 C Source Code
a . #include<stdio .h>
#include<string .h>
void main ( ) {
char str [30];
printf ( "enter the string value n" ) ;
gets ( str ) ;
printf ( "Reverse of ’%s ’ is ’%s ’ " , str , strrev ( str ) ) ;
}
b. #include<stdio .h>
void main ( ) {
char str [30] , revstr [30];
int i , cnt = 0;
printf ( "enter the string value n" ) ;
gets ( str ) ;
/ / Count the size of the string
while ( str [ cnt ] != ’ 0 ’ )
cnt++;
/ / Store the string in reverse order
for ( i = 0; i < cnt ; i ++)
revstr [ i ] = str [ cnt−1− i ] ;
revstr [ i ] = ’ 0 ’ ;
printf ( "The reverse of ’%s ’ is ’%s ’ n" , str , revstr ) ;
}
7.2.4 Input and Output
Figure 85: Reverse a "S&H, VRSE, Vijayawada" using string handling function.
Figure 86: Reverse "VRSEC, Vijayawada" without using string handling function.
111
7.3 String Concatenation
Write a C program to concatenate two strings with and without using string handling functions.
7.3.1 Algorithm
1 Start
2 Declare two array variables: str1 and str2.
3 Read two strings into str1 and str2.
4 Call the string concatenation function strcat(str1, str2), it concatenates str2 to str1.
5 Display the value of str1.
6 Stop
Algorithm 44: String concatenation using string handling function.
1 Start
2 Declare six variables: cnt1, cnt2, cnt3, array str1, array str2 and array str3.
3 Initialize the values of cnt1, cnt2 and cnt3 to 0.
4 Read two strings into str1 and str2.
5 Repeat the step 6 and 7 until str1[cnt1]!=’0’ is satisfied.
6 Place str1[cnt1]’s value in str3[cnt3].
7 Increment the values of cnt1 and cnt3 by 1.
8 Repeat the step 9 and 10 until str2[cnt2]!=’0’ is satisfied.
9 Place str2[cnt2]’s value in str3[cnt3].
10 Increment the values of cnt2 and cnt3 by 1.
11 Store ’0’ in str3[cnt3].
12 Display the value of str3.
13 Stop
Algorithm 45: String concatenation without using string handling function.
7.3.2 Flowchart
Figure 87: String concatenation using string handling function.
112
.
Figure 88: String concatenation without using string handling function.
113
7.3.3 C Source Code
a . #include<stdio .h>
#include<string .h>
void main()
{
char str1 [30] , str2 [30];
printf ( "enter the string value for str1 : n" ) ;
gets ( str1 ) ;
printf ( "enter the string value for str2 : n" ) ;
gets ( str2 ) ;
printf ( "The str1+str2 is ’%s ’n" , strcat ( str1 , str2 ) ) ;
}
b. #include<stdio .h>
#include<string .h>
void main()
{
char str1 [30] , str2 [30] , str3 [60];
int cnt1 = 0 , cnt2 = 0 , cnt3 = 0;
printf ( "enter the string value for str1 : n" ) ;
gets ( str1 ) ;
printf ( "enter the string value for str2 : n" ) ;
gets ( str2 ) ;
while ( str1 [ cnt1 ] != ’ 0 ’ )
{
str3 [ cnt3 ] = str1 [ cnt1 ] ;
cnt1++;
cnt3++;
}
while ( str2 [ cnt2 ] != ’ 0 ’ )
{
str3 [ cnt3 ] = str2 [ cnt2 ] ;
cnt2++;
cnt3++;
}
str3 [ cnt3 ] = ’ 0 ’ ;
printf ( "The str1+str2 is ’%s ’n" , str3 ) ;
}
114
7.3.4 Input and Output
Figure 89: Concatenation of "S&H, VRSEC," and "Vijayawada" using string handling function.
Figure 90: Concatenation of "S&H, VRSEC" and "Vijayawada" without using string handling
function.
115
7.4 String Comparison
Write a C program to compare two strings with and without using string handling functions.
7.4.1 Algorithm
1 Start
2 Declare three variables: n, array str1 and array str2.
3 Read two strings into str1 and str2.
4 Call the string comparison function strcmp(str1, str2) and store the return value in n.
5 Display the value of n.
6 Stop
Algorithm 46: String comparison using string handling function.
1 Start
2 Declare six variables: cnt1, cnt2, i, flag and array str1 and array str2.
3 Initialize the values of cnt1 and cnt2 to 0.
4 Initialize the value of flag to 1.
5 Read two strings into str1 and str2.
6 Repeat the step 7 until str1[cnt1]!=’0’ is satisfied.
7 Increment the value of cnt1 by 1.
8 Repeat the step 9 until str2[cnt2]!=’0’ is satisfied.
9 Increment the value of cnt1 by 1.
10 If cnt1 is not equal to cnt2, then go to step 14.
11 Initialize the value of i to 0.
12 Repeat the step 13 to 15 till i < cnt1 is satisfied.
13 If str1[i]!=str2[i], go to next step, else go to 15.
14 Store zero in flag, go to step 16.
15 Increment i by 1.
16 If flag is 1, display ’Both the strings are equal’.
17 Else, display ’Both the strings are different’.
18 Stop
Algorithm 47: String comparison without using string handling function.
116
7.4.2 Flowchart
Figure 91: String comparison using string handling function.
117
.
Figure 92: String comparison without using string handling function.
118
7.4.3 C Source Code
a . #include<stdio .h>
#include<string .h>
void main ( ) {
char str1 [30] , str2 [30];
int cnt1 = 0 , cnt2 = 0;
int i , flag = 1;
printf ( "enter the string value for str1 : n" ) ;
gets ( str1 ) ;
printf ( "enter the string value for str2 : n" ) ;
gets ( str2 ) ;
while ( str1 [ cnt1 ] != ’ 0 ’ )
cnt1++;
while ( str2 [ cnt2 ] != ’ 0 ’ )
cnt2++;
i f ( cnt1 != cnt2 )
flag = 0;
else {
for ( i = 0; i < cnt1 ; i ++){
i f ( str1 [ i ] != str2 [ i ] ) {
flag = 0;
break ;
}
}
}
i f ( flag )
printf ( "Both the strings are equal . n" ) ;
else
printf ( "Both the strings are different . n" ) ;
}
b. #include<stdio .h>
#include<string .h>
void main ( ) {
char str1 [30] , str2 [30];
printf ( "enter the string value for str1 : n" ) ;
gets ( str1 ) ;
printf ( "enter the string value for str2 : n" ) ;
gets ( str2 ) ;
i f ( ! strcmp( str1 , str2 ))
printf ( "Both the strings are equal . n" ) ;
else
printf ( "Both the strings are different . n" ) ;
}
119
7.4.4 Input and Output
Figure 93: Compare "VRSEC" and "vrsec" without using string handling function.
Figure 94: Compare "VRSEC" and "VRsec" using string handling function.
Objectives
To write programs that work on read, write and manipulate fixed length and variable-length
strings and/or arrays of strings.
To write programs that use predefined string I/O functions.
To write programs that use string manipulation functions from the string library.
120
8
WEEK
Concepts of User Defined
Functions
8.1 Swap Two Numbers
Write a C program to swap two numbers using call by value and call by reference.
8.1.1 Algorithm
1 Start
2 Declare two variables: a and b.
3 Read the value for a and b.
4 Call swap(a, b) function.
5 Stop
1 function swap(a, b)
2 Declare a variable temp.
3 Place a’s value in temp.
4 Place b’s value in a.
5 Place temp’s value in b.
6 Display a’s and b’s values.
Algorithm 48: Swap two numbers using call by values.
121
1 Start
2 Declare two variables: a and b.
3 Read the values for a and b.
4 Call swap(&a, &b) function, where &a and &b are addresses of a and b variables.
5 Display a’s and b’s values.
6 Stop
1 function swap(*a, *b)
2 Declare a variable temp.
3 Place *a’s value in temp, where a is a pointer variable
4 Place *b’s value in *a, where b is a pointer variable
5 Place temp’s value in *b.
Algorithm 49: Swap two numbers using call by reference.
8.1.2 Flowchart
Figure 95: Swap two numbers using call by values.
122
.
Figure 96: Swap two numbers using call by reference.
123
8.1.3 C Source Code
a . #include<stdio .h>
void swap( int a , int b ) ;
void main()
{
int a , b;
printf ( "Enter the value of a and b : n" ) ;
scanf ( "%d %d" , &a , &b ) ;
swap(a , b ) ;
}
void swap( int a , int b)
{
int temp;
temp = a ;
a = b;
b = temp;
printf ( "The a and b values after swapping are %d and %d n" , a , b ) ;
}
b. #include<stdio .h>
void swap( int * a , int * b ) ;
void main()
{
int a , b;
printf ( "Enter the value of a and b : n" ) ;
scanf ( "%d %d" , &a , &b ) ;
swap(&a , &b ) ;
printf ( "The a and b values after swapping are %d and %d. n" , a , b ) ;
}
void swap( int * a , int * b)
{
int temp;
temp = *a ;
*a = *b;
*b = temp;
}
124
8.1.4 Input and Output
Figure 97: Swap 5 and 3 using call by values.
Figure 98: Swap two numbers using call by reference.
125
8.2 Factorial of a Number
Write a C program to find the factorial of the given number using and without using recursion.
8.2.1 Algorithm
1 Start
2 Declare a variable n.
3 Read the value for n.
4 Call factorial(n).
5 Display the return value of factorial(n).
6 Stop
1 function factorial(n)
2 If n == 1 then return 1.
3 Else, return n*factorial(n-1).
Algorithm 50: factorial of a +ve number using recursion.
1 Start
2 Declare a variable n.
3 Read the value for n.
4 Call factorial(n).
5 Display the return value of factorial(n).
6 Stop
1 function factorial(n)
2 Declare variables i and mult.
3 Initialize mult to 1.
4 Initialize i to n.
5 Repeat step 6 and 7 till i>0 is satisfied.
6 Multiply i value to current value of mult.
7 Decrement i value by 1.
8 Return mult’s value.
Algorithm 51: factorial of a +ve number without using recursion.
126
8.2.2 Flowchart
Figure 99: factorial of a +ve number using recursion.
127
.
Figure 100: factorial of a +ve number without using recursion.
128
8.2.3 C Source Code
a . #include<stdio .h>
int fact ( int n ) ;
void main()
{
int n;
printf ( "Enter an +ve integer number : n" ) ;
scanf ( "%d" , &n ) ;
printf ( "The factorial of %d is : %d. n" , n, fact (n ) ) ;
}
int fact ( int n)
{
int i , mult = 1;
for ( i = n; i > 0; i −−)
mult = mult * i ;
return mult ;
}
b. #include<stdio .h>
int fact ( int n ) ;
void main()
{
int n;
printf ( "Enter an +ve integer number : n" ) ;
scanf ( "%d" , &n ) ;
printf ( "The factorial of %d is : %d. n" , n, fact (n ) ) ;
}
int fact ( int n)
{
i f (n == 1)
return 1;
else
return n * fact (n−1);
}
129
8.2.4 Input and Output
Figure 101: factorial of 6 without using recursion.
Figure 102: factorial of 5 using recursion.
130
8.3 Combination
Write a C program to find n
Cr using functions.
8.3.1 Algorithm
1 Start
2 Declare two variables n and r.
3 Read the value for n and r.
4 If n >= r then call nCr(n, r) function.
5 Display the return value of nCr(n, r).
6 Stop
1 function nCr(n, r)
2 Call fact(n), fact(r) and fact(n-r) functions.
3 Divide return value of fact(n) by product of fact(r)’s and fact(n-r)’s return values.
4 Return the result.
1 function fact(n)
2 If n == 1 then return 1.
3 Else return n*fact(n-1).
Algorithm 52: Compute nCr for given n and r.
131
8.3.2 Flowchart
Figure 103: Compute nCr for given n and r.
132
8.3.3 C Source Code
#include<stdio .h>
int nCr( int n, int r ) ;
int fact ( int n ) ;
void main()
{
int n, r ;
printf ( "Enter the value of n and r : n" ) ;
scanf ( "%d %d" , &n, &r ) ;
i f (n >= r )
printf ( "The nCr is %d. n" , nCr(n, r ) ) ;
else
printf ( "You have entered wrong values . n" ) ;
}
int nCr( int n, int r )
{
return fact (n)/( fact ( r ) * fact (n−r ) ) ;
}
int fact ( int n)
{
i f (n==1)
return 1;
else
return n * fact (n−1);
}
8.3.4 Input and Output
Figure 104: Compute nCr for n = 6 and r = 2.
133
8.4 Mean and Standard Deviation
Write a C program to find mean and standard deviation of a given set of numbers. (Define func-
tions for mean and standard deviation).
8.4.1 Algorithm
1 Start
2 Declare three variables: i, mn and arr[N], where N is a constant.
3 Initialize i to 1.
4 Repeat step 5 until i is equal to N satisfied.
5 Get the value for arr[i], i is the current index position in arr.
6 Call mean (arr, N) function and store the return value in mn.
7 Display mn’s and mean’s values of the given N numbers.
8 Call stddev (arr, mn, N) and display its return value.
9 Stop
1 function mean (*arr, n)
2 Declare two variables: i and mn.
3 Initialize m to 0.0 and i to 0.
4 Repeat step 5 till i<n is satisfied.
5 Add arr[i]’s value to the current value of m.
6 Divide mn by n and store the value into mn.
7 Return mn.
1 function stddev (*arr, mn, n)
2 Declare two variables: i and dev.
3 Initialize dev to 0.0 and i to 0.
4 Repeat step 5 and 6 till i<n is satisfied.
5 Calculate square of the difference between arr[i] and mn.
6 Add result to the current value of dev.
7 Divide dev by n and store square root of the resulted value in dev.
8 Return dev’s value.
Algorithm 53: Mean and standard deviation of a set of numbers.
134
8.4.2 Flowchart
Figure 105: Mean and standard deviation of a set of numbers.
135
8.4.3 C Source Code
#include<stdio .h>
#include<math.h>
#define N 7
float mean( float * arr , int n ) ;
float stddev ( float * arr , float mn, int n ) ;
void main()
{
int i ;
float mn, arr [N] ;
printf ( "Enter the value of the array : n" ) ;
for ( i = 0; i < N; i ++){
scanf ( "%f " , &arr [ i ] ) ;
}
mn = mean(&arr [0] , N) ;
printf ( "mean value of arr is %f . n" , mn) ;
printf ( "stddev of arr is %f . n" , stddev(&arr [0] , mn, N) ) ;
}
float mean( float * arr , int n)
{
int i ;
float mn = 0.0;
for ( i = 0; i < n; i ++)
mn = mn + *( arr+i ) ;
mn /= n;
return mn;
}
float stddev ( float * arr , float mn, int n)
{
int i ;
float dev = 0.0;
for ( i = 0; i < n; i ++)
dev = dev + pow( * ( arr+i )−mn, 2);
dev = sqrt (dev/n ) ;
return dev ;
}
136
8.4.4 Input and Output
Figure 106: Mean and standard deviation of the given set of numbers.
Objectives
Have a clear idea on function declaration, call, and definition.
To write a program using more than one function with or without parameters and function re-
turn type.
To understand the global and local scope, and implement inter function communication for
various problems.
137
9
WEEK
Pointers and Their
Applications
9.1 Arithmetic Operations
Write a C program to implement arithmetic operations on integers using pointers.
9.1.1 Algorithm
1 Start
2 Declare two variables (a and b) and two pointer variables (p and q).
3 Get the integer values for a and b.
4 Assign the address of a to pointer p.
5 Assign the address of b to pointer q.
6 Add the dereferenced values of p and q and display the result.
7 Subtract q’s dereferenced value from p’s dereferenced value and display the result.
8 Multiply the dereferenced values of p and q and display the result.
9 Divide p’s derefrenced value by q’s derefrenced value and display the result.
10 Stop.
Algorithm 54: Arithmetic operations on integers using pointers.
138
9.1.2 Flowchart
Figure 107: Arithmetic operations on integers using pointers.
139
9.1.3 C Source Code
#include<stdio .h>
void main ( ) {
int a , b;
int *p = &a , *q = &b;
printf ( "Enter the value of a and b : n" ) ;
scanf ( "%d %d" , p, q ) ;
printf ( "%d + %d is %d n" , *p, *q, *p + *q ) ;
printf ( "%d − %d is %d n" , *p, *q, *p − *q ) ;
printf ( "%d * %d is %d n" , *p, *q, *p * *q ) ;
printf ( "%d / %d is %d n" , *p, *q, *p / *q ) ;
}
9.1.4 Input and Output
Figure 108: Arithmetic operations on 5 and 3 using pointers.
140
9.2 String Sorting
Write a C program to sort names in ascending order using functions and pointers.
9.2.1 Algorithm
1 Start
2 Declare two variables: i and a 2D character array name.
3 Initialize i to 0.
4 Repeat step 5 until i is equal to size satisfied, where size is a constant.
5 Get the value for name[i].
6 Call sort(name) function.
7 Reinitialize i to 0.
8 Repeat step 9 until i is equal to size satisfied, where size is a constant.
9 Display name[i]’s value.
10 Stop.
1 function sort(*name)
2 Declare a character array temp.
3 Declare three variables i, j and min.
4 Initialize i to 0.
5 Repeat step 6 to 12 until i == size is satisfied.
6 Place the i’s value in min.
7 Initialize j to i+1.
8 Repeat step 9 until j == size is satisfied.
9 If name[min] is greater than name[j], then min = j.
10 Assign name[i]’s value to temp.
11 Assign name[min]’s value to name[i].
12 Assign temp’s value to name[min].
Algorithm 55: Sort names in ascending order using functions and pointers.
141
9.2.2 Flowchart
Figure 109: Sort names in ascending order using functions and pointers.
142
9.2.3 C Source Code
#include<stdio .h>
#include<string .h>
#define size 7
void sort (char *name) ;
void main()
{
int i ;
char name[ size ] [ 2 0 ] ;
printf ( "Enter the input : n" ) ;
for ( i = 0; i < size ; i ++)
gets(&name[ i ] ) ;
printf ( " print the array before sorting : n" ) ;
for ( i = 0; i < size ; i ++)
printf ( "%s n" , name[ i ] ) ;
sort(&name[ 0 ] [ 0 ] ) ;
printf ( " print the array after sorting : n" ) ;
for ( i = 0; i < size ; i ++)
printf ( "%s n" , name[ i ] ) ;
}
void sort (char *name)
{
char temp[20];
int i , j , min;
for ( i = 0; i < size ; i ++)
{
min = i ;
for ( j = i +1; j < size ; j ++)
{
i f (strcmp(name[min] , name[ j ] ) > 0)
min = j ;
}
strcpy (temp, name[ i ] ) ;
strcpy (name[ i ] , name[min ] ) ;
strcpy (name[min] , temp ) ;
}
}
143
9.2.4 Input and Output
Figure 110: Sort city names in ascending order using functions and pointers.
144
9.3 Largest Element
Write a C program to find the largest element in an integer array using an user-defined function
and dynamic memory allocation.
9.3.1 Algorithm
1 Start
2 Declare two variables (i and max) and one pointer variable p.
3 Call malloc(sizeof(int)*7) function using p to allocate memory at runtime.
4 Initialize i to 0.
5 Repeat step 6 until i is equal to 7 satisfied.
6 Get the value for p[i].
7 Call maximum(p) function and store its return value in max.
8 Display max’s value.
9 Stop.
1 function maximum(*l)
2 Declare two variables: i and max.
3 Assign l[0] to max.
4 Initialize i to 1.
5 Repeat step 6 until i is equal to 7 satisfied.
6 if l[i] is larger than max, then max = l[i].
7 Return the value of max.
Algorithm 56: Largest element in an integer array using user-defined function and DMA.
145
9.3.2 Flowchart
Figure 111: Largest element in an integer array using user-defined function and DMA.
146
9.3.3 C Source Code
#include<stdio .h>
#include<stdlib .h>
int maximum( int * ) ;
void main( ) {
int i , *p, max;
p = ( int *) malloc ( sizeof ( int ) * 7 ) ;
printf ( "Enter the value of array p : n" ) ;
for ( i = 0; i < 7; i ++)
scanf ( "%d" , p+i ) ;
max = maximum(p ) ;
printf ( "The maximum is %d" , max) ;
}
int maximum( int * l ) {
int i , max = * l ;
for ( i = 1; i < 7; i ++){
i f ( * ( l+i ) > max)
max = *( l +i ) ;
}
return max;
}
9.3.4 Input and Output
Figure 112: Largest element in the given array using user-defined function and DMA.
Objectives
To understand the concept of pointers and have a clear idea on pointers declaration, definition,
and initialization.
To use pointers to access data in programs and also use them as parameters and return types for
user defined functions.
To understand the correlation between pointers and arrays, and use pointers to perform all kinds
of mathematical operations.
To write programs using static and dynamic memory allocation.
147
10
WEEK
Structure, Union, and
Enumeration
10.1 Student’s Details
Write a C program to read name of a student, roll number and marks obtained in subjects from
keyboard, and print name of the student, roll number, marks in 3 subjects, and total marks by
using structures concept.
10.1.1 Algorithm
1 Start
2 Define a structure student of total and three arrays name, roll and marks as members.
3 Declare two variables: i and s1; s1 is a student type variable.
4 Initialize s1.total and i to 0.
5 Get the values for s1.name and s1.roll.
6 Repeat step 7 to 9 until i is equal to 3 satisfied.
7 Get the values for s1.marks[i].
8 Add s1.marks[i] value to the current value of s1.total.
9 Increment i by 1.
10 Display s1.name’s and s1.roll’s values.
11 Repeat step 12 until i is equal to 3 satisfied.
12 Display s1.marks[i]’s value.
13 Display s1.total’s value.
14 Stop.
Algorithm 57: Print student’s details.
148
10.1.2 Flowchart
Figure 113: Print student’s details.
149
10.1.3 C Source Code
#include<stdio .h>
struct student {
char name[20];
char r o l l [15];
float marks [ 3 ] ;
float total ;
} ;
void main ( ) {
struct student s1 ;
int i ;
s1 . total = 0;
printf ( "Enter name of the student : n" ) ;
gets ( s1 .name) ;
printf ( "Enter r o l l no. of the student : n" ) ;
gets ( s1 . r o l l ) ;
for ( i = 0; i < 3; i ++){
printf ( "Enter the sub %d marks : " , i +1);
scanf ( "%f " , &s1 . marks[ i ] ) ;
s1 . total = s1 . total + s1 . marks[ i ] ;
}
printf ( "Name of the student : %s n" , s1 .name) ;
printf ( " Roll no of the student : %s n" , s1 . r o l l ) ;
for ( i = 0; i < 3; i ++)
printf ( "The sub %d marks : %f n" , i +1, s1 . marks[ i ] ) ;
printf ( "Total mark : %f n" , s1 . total ) ;
}
10.1.4 Input and Output
Figure 114: Student’s name, roll number, marks in 3 subjects, and total mark.
150
10.2 Students’ Details
Write a C program to read name of the students, roll number and marks obtained in subjects
from keyboard and print name of the students, roll number, marks in 3 subjects, and total marks
by using array of structures concept.
10.2.1 Algorithm
1 Start
2 Define a structure student of total and three arrays name, roll and marks as members.
3 Declare three variables i, j and s[N]; s is a student type array and N is a constant.
4 Initialize i to 0.
5 Repeat step 6 to 13 until i is equal to N satisfied.
6 Get the values for s[i].name and s[i].roll.
7 Initialize s[i].total to 0.
8 Initialize j to 0.
9 Repeat step 10 to 12 until j is equal to 3 satisfied.
10 get the value for s[i].marks[j].
11 Add s[i].marks[j]’s values to s[i].total.
12 Increment j by 1.
13 Increment i by 1.
14 Initialize i to 0.
15 Repeat step 16 to 22 until i is equal to N satisfied.
16 Display s[i].name’s and s[i].roll’s values.
17 Initialize j to 0.
18 Repeat step 19 and 20 until j is equal to 3 satisfied.
19 Display s[i].marks[j]’s value.
20 Increment j by 1.
21 Display s[i].total’s value.
22 Increment i by 1.
23 Stop.
Algorithm 58: Print students’ details.
151
10.2.2 Flowchart
Figure 115: Print students’ details.
152
10.2.3 C Source Code
#include<stdio .h>
#include<string .h>
struct student {
char name[15];
char r o l l [15];
float marks [ 3 ] ;
float total ;
} ;
void main()
{
struct student s [ 3 ] ;
int i , j ;
for ( i= 0; i <= 2; i ++)
{
printf ( "Enter name of the student %d : " , i +1);
gets ( s [ i ] .name) ;
}
for ( i= 0; i <= 2; i ++)
{
printf ( "Enter r o l l no. of the student %d : " , i +1);
gets ( s [ i ] . r o l l ) ;
}
for ( i= 0; i <= 2; i ++)
{
s [ i ] . total = 0;
for ( j = 0; j < 3; j ++)
{
printf ( "Enter the sub %d mark of student %d : " , j +1, i +1);
scanf ( "%f " , &s [ i ] . marks[ j ] ) ;
s [ i ] . total = s [ i ] . total + s [ i ] . marks[ j ] ;
}
}
for ( i= 0; i <= 2; i ++)
{
printf ( "Name of the student %d : %s n" , i +1, s [ i ] .name) ;
printf ( " Roll no. of the student %d : %s n" , i +1, s [ i ] . r o l l ) ;
for ( j = 0; j < 3; j ++)
printf ( "The sub %d mark of student %d : %f n" , j +1, 
i +1, s [ i ] . marks[ j ] ) ;
printf ( "Total mark of student %d : %f n" , i +1, s [ i ] . total ) ;
}
}
153
10.2.4 Input and Output
Figure 116: Students’ names, roll numbers, marks in 3 subjects, and total marks.
154
10.3 Days in a Week
Write a C program to print a day in a week using Enumeration.
10.3.1 Algorithm
1 Start
2 Define a enum week of {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday} as enum constants.
3 Declare a enum week variable day and get the value for it in between 0 and 6 .
4 If day is Sunday then display ’Sunday’ and go to step 12.
5 If day is Monday then display ’Monday’ and go to step 12.
6 If day is Tuesday then display ’Tuesday’ and go to step 12.
7 If day is Wednesday then display ’Wednesday’ and go to step 12.
8 If day is Thursday then display ’Thursday’ and go to step 12.
9 If day is Friday then display ’Friday’ and go to step 12.
10 If day is Saturday then display ’Saturday’ and go to step 12.
11 Stop.
Algorithm 59: Print a day in a week.
155
10.3.2 Flow Chart
Figure 117: Print a day in a week.
156
10.3.3 C Source Code
#include<stdio .h>
enum week {Sunday , Monday, Tuesday , Wednesday, Thursday , Friday , 
Saturday } ;
void main ( ) {
enum week day ;
printf ( "Enter a day between 0 and 6 : n" ) ;
scanf ( "%d" , &day ) ;
switch (day ) {
case Sunday : printf ( " I t is Sunday n" ) ;
break ;
case Monday: printf ( " I t is Monday n" ) ;
break ;
case Tuesday : printf ( " I t is Tuesday n" ) ;
break ;
case Wednesday: printf ( " I t is Wednesday n" ) ;
break ;
case Thursday : printf ( " I t is Thursday n" ) ;
break ;
case Friday : printf ( " I t is Friday n" ) ;
break ;
case Saturday : printf ( " I t is Saturday n" ) ;
}
}
10.3.4 Input and Output
Figure 118: Display a day in a week using Enumeration.
Objectives
To instigate about the structure, union, and enumerated types derived data types.
To use structure or union data types to address elements of multiple instances present in prob-
lems.
To write C programs using enumeration data types, an easiest way of mapping symbolic names
to integer values.
157
11
WEEK
File Handling Operations
11.1 Count Number of Character, Spaces, Words and Lines
Write a C program to count number of character, spaces, words and lines in a file.
11.1.1 Algorithm
1 Start
2 Declare pre_ch, ch, character, line, space, words, char arr in_name and file * in_file.
3 Initialize character, line, space and words to 0.
4 Read a file name into in_name.
5 Call fopen(in_name, "r") function using in_file to open the file in read mode.
6 if in_file == NULL then display "Unable to open the file" and go to step 18.
7 Call fgetc(in_file) to read a character from the file and store it in ch.
8 Repeat the step 9 to 14 until ch is equal to EOF satisfied.
9 Increment character by 1.
10 If ch is equal to ’ ’, then space by 1.
11 If ch is equal to ’n’, then increment line by 1.
12 If ch is equal to ’ ’, ’t’, ’n’ or ’0’, then increment word by 1.
13 Assign ch value to pre_ch.
14 Call fgetc(in_file) to read the next character from the file and store it in ch.
15 If ch is not equal to ’ ’, ’t’, ’n’ and ’0’, then increment word and line by 1.
16 Call fclose(in_file) function to close the file input stream.
17 Display the values of character, line, space and words.
18 Stop.
Algorithm 60: Count number of character, spaces, words and lines in a file.
158
11.1.2 Flowchart
Figure 119: Count number of character, spaces, words and lines in a file.
159
11.1.3 C Source Code
#include<stdio .h>
void main( void )
{
char in_name [80];
FILE * i n_fi l e ;
int pre_ch , ch , character = 0 , line = 0 , space = 0 , words = 0;
printf ( "Enter f i l e name : " ) ;
scanf ( "%s" , in_name ) ;
i n_fi l e = fopen(in_name , "r" ) ;
i f ( i n_ fi l e == NULL)
printf ( "Can ’ t open %s for reading .n" , in_name ) ;
else {
while (( ch = fgetc ( i n_ fil e )) != EOF)
{
character ++;
i f (ch == ’ ’ )
space++;
i f (ch == ’ n ’ )
line ++;
i f (ch == ’ ’ | | ch == ’  t ’ | | ch == ’ n ’ | | ch == ’ 0 ’ )
words++;
pre_ch = ch ;
}
i f ( pre_ch != ’ ’ && pre_ch != ’  t ’ && pre_ch != ’ n ’ 
&& pre_ch != ’ 0 ’ )
{
words++;
line ++;
}
fclose ( i n_ fi l e ) ;
printf ( "nNumber of characters = %d. n" , character ) ;
printf ( "nNumber of spaces = %d. n" , space ) ;
printf ( "nNumber of words = %d. n" , words ) ;
printf ( "nNumber of lines = %d. n" , line ) ;
}
}
160
11.1.4 Input and Output
Figure 120: Count number of character, spaces, words and lines in 123.txt.
Figure 121: Number of Character, Spaces, Words and Lines in 123.txt.
161
11.2 Count Number of Alphabets, Digits, Punctuation Marks
Write a C program that will read a text file and count the number of alphabetic characters, dig-
its,punctuation characters in a file.
11.2.1 Algorithm
1 Start
2 Declare seven variables: ch, alp, digit, splch, k, an array in_name and file pointer in_file.
3 Initialize alp, digit and splch to 0.
4 Read a file name into in_name.
5 Call fopen(in_name, "r") function using in_file to open the file in read mode.
6 If in_file == NULL then display "Unable to open the file" and go to step 16.
7 Call fgetc(in_file) to read a character from the file and store it in ch.
8 Repeat the step 9 to 13 until ch is equal to EOF satisfied.
9 If ch is a character from [a-zA-Z], then increment alp by 1.
10 If ch is a character from [0-9], then increment digit by 1.
11 Call ispunct(ch) function and store the return value in k.
12 If k is equal to 1, then increment splch by 1.
13 Call fgetc(in_file) to read the next character from the file and store it in ch.
14 Call fclose(in_file) function to close the file input stream.
15 Display alp’s, digit’s and splch’s values.
16 Stop.
Algorithm 61: Count number of alphabetic characters, digits and punctuation characters in
a file.
162
11.2.2 Flowchart
Figure 122: Count number of alphabetic characters, digits and punctuation characters in a file.
163
11.2.3 C Source Code
#include<stdio .h>
#include<ctype .h>
void main( void )
{
char in_name [80];
FILE * i n_fi l e ;
int ch , alp , digit , splch ;
alp = digit = splch = 0;
printf ( "Count total number of alphabets , digits and " ) ;
printf ( "Punctuation characters : n" ) ;
printf ( "Enter f i l e name : n" ) ;
scanf ( "%s" , in_name ) ;
i n_fi l e = fopen(in_name , "r" ) ;
i f ( i n_ fi l e == NULL)
printf ( "Can ’ t open %s for reading .n" , in_name ) ;
else
{
while (( ch = fgetc ( i n_ fil e )) != EOF)
{
i f (( ch >= ’a ’ && ch <= ’z ’ ) | | (ch >= ’A ’ && ch <= ’Z ’ ))
alp ++;
else i f (ch >= ’0 ’ && ch <= ’9 ’ )
digit ++;
else i f ( ispunct (ch ))
splch ++;
}
fclose ( i n_ fi l e ) ;
printf ( "Number of Alphabets : %d" , alp ) ;
printf ( "nNumber of Digits : %d" , digit ) ;
printf ( "nNumber of Punctuation Characters : %d" , splch ) ;
}
}
164
11.2.4 Input and Output
Figure 123: Contents of 123.txt.
Figure 124: Number of alphabetic characters, digits and punctuation characters in 123.txt.
165
11.3 Merge Contents of Two Files
Write a program in C to merge contents of two files and write it in a new file.
11.3.1 Algorithm
1 Start
2 Declare three file pointers fs1, fs2 and ft.
3 Declare a character variable ch and three character arrays file1, file2 and file3.
4 Read file names into file1, file2 and file3.
5 Call fopen(file1, "r") function using fs1 to open the file in read mode.
6 Call fopen(file2, "r") function using fs2 to open the file in read mode.
7 Call fopen(file3, "w") function using ft to open the file in write mode.
8 If fs1, fs2 and ft are equal to NULL, display "error" and go to step 20.
9 Call fgetc(fs1) function to read a character from the file1 and store it in ch.
10 Repeat the step 11 and 12 until ch is equal to EOF satisfied.
11 Call fputc(ch, ft) function to write ch value to file3.
12 Call fgetc(fs1) function to read next character from the file1 and store it in ch.
13 Call fgetc(fs2) function to read a character from the file2 and store it in ch.
14 Repeat the step 15 and 16 until ch is equal to EOF satisfied.
15 Call fputc(ch, ft) function to write ch value to file3.
16 Call fgetc(fs2) function to read next character from the file2 and store it in ch.
17 Display "Merged successfully".
18 Call fclose(fs1) function to close the file input stream linked to file1.
19 Call fclose(fs2) function to close the file input stream linked to file2.
20 Call fclose(ft) function to close the file output stream linked to file3.
21 Stop.
Algorithm 62: Merge contents of two files and write it in a new file.
166
11.3.2 Flowchart
Figure 125: Merge contents of two files and write it in a new file.
167
11.3.3 C Source Code
#include <stdio .h>
#include <stdlib .h>
void main()
{
FILE * fs1 , * fs2 , * f t ;
char ch , f i l e 1 [20] , f i l e 2 [20] , f i l e 3 [20];
printf ( "Enter name of f i r s t f i l e : n" ) ;
gets ( f i l e 1 ) ;
printf ( "Enter name of second f i l e : n" ) ;
gets ( f i l e 2 ) ;
printf ( "Enter name of f i l e to store contents of the two f i l e s : n" ) ;
gets ( f i l e 3 ) ;
fs1 = fopen ( file1 , " r" ) ;
fs2 = fopen ( file2 , " r" ) ;
i f ( fs1 == NULL | | fs2 == NULL)
{
perror ( "Error" ) ;
printf ( "Press any key to exit . . .  n" ) ;
exit (EXIT_FAILURE ) ;
}
f t = fopen( file3 , "w" ) ;
i f ( f t == NULL)
{
perror ( "Error" ) ;
printf ( "Press any key to exit . . .  n" ) ;
exit (EXIT_FAILURE ) ;
}
while (( ch = fgetc ( fs1 )) != EOF)
fputc (ch , f t ) ;
while (( ch = fgetc ( fs2 )) != EOF)
fputc (ch , f t ) ;
printf ( "The two f i l e s were merged into %s f i l e .n" , f i l e 3 ) ;
fclose ( fs1 ) ;
fclose ( fs2 ) ;
fclose ( f t ) ;
}
168
11.3.4 Input and Output
Figure 126: Contents of 123.txt.
Figure 127: Contents of 124.txt.
Figure 128: Contents of 125.txt after merging the contents of 123.txt and 124.txt.
Figure 129: Contents of 125.txt.
169
11.4 Compare Contents of Two Files
Write a C program to compare the contents of two files. If both are same, print the contents of
one file else print the contents of both files.
11.4.1 Algorithm
1 Start
2 Declare two file pointers fptr1 and fptr2.
3 Declare s, flag, two character arrays path1 and path2.
4 Read file names into path1 and path2.
5 Call fopen(path1, "r") function using fptr1 to open the file1 in read mode.
6 Call fopen(path2, "r") function using fptr2 to open the file2 in read mode.
7 If fptr1 and fptr2 are equal to NULL, display "error" and go to step 22.
8 Call compareFile(fptr1, fptr2) function to compare the contents of two files.
9 If the return value is -1, then set flag to 2.
10 Else, set flag to 1.
11 Call fgetc(fptr1) function to read a character from the file1 and store it in s.
12 Repeat step 13 and 14 until s is equal to EOF satisfied.
13 Display the value of s.
14 Call fgetc(fptr1) function to read the next character from the file1 and store it in s.
15 If flag is equal to 1, then go to step 22.
16 Call fgetc(fptr2) function to read a character from the file2 and store it in s.
17 Repeat step 18 and 19 until s is equal to EOF satisfied.
18 Display the value of s.
19 Call fgetc(fptr2) function to read the next character from the file2 and store it in s.
20 Call fclose(fptr1) function to close the file input stream linked to file1.
21 Call fclose(fptr2) function to close the file input stream linked to file2.
22 Stop.
1 function compareFile(*fptr1, *fptr2)
2 Declare two variables ch1 and ch2.
3 Call fgetc(fptr1) function to read a character from the file1 and store it in ch.
4 Call fgetc(fptr2) function to read a character from the file2 and store it in ch.
5 If ch1 is not equal to ch2, then return -1.
6 Repeat step 3 to 5 till ch1 and ch2 are not equal to EOF.
7 If ch1 and ch2 are equal to EOF, then return 0.
8 Else, return -1.
Algorithm 63: Compare the contents of two files and print the output.
170
11.4.2 Flowchart
Figure 130: Compare the contents of two files and print the output.
171
11.4.3 C Source Code
#include <stdio .h>
#include <stdlib .h>
int compareFile (FILE * fPtr1 , FILE * fPtr2 ) ;
void main( void ) {
FILE * fPtr1 ;
FILE * fPtr2 ;
char path1 [100];
char path2 [100];
char s ;
int diff , flag ;
printf ( "Enter path of f i r s t f i l e : n" ) ;
scanf ( "%s" , path1 ) ;
printf ( "Enter path of second f i l e : n" ) ;
scanf ( "%s" , path2 ) ;
fPtr1 = fopen(path1 , "r " ) ;
fPtr2 = fopen(path2 , "r " ) ;
i f ( fPtr1 == NULL | | fPtr2 == NULL) {
printf ( "nUnable to open f i l e .n" ) ;
exit (EXIT_FAILURE ) ;
}
d i f f = compareFile ( fPtr1 , fPtr2 ) ;
i f ( d i f f == 0)
flag =1;
else
flag =2;
i f ( flag == 1){
while (( s = fgetc ( fPtr1 )) != EOF)
printf ( "%c" , s ) ;
}
i f ( flag == 2){
while (( s = fgetc ( fPtr1 )) != EOF) ;
printf ( "%c" , s ) ;
printf ( "n" ) ;
while (( s = fgetc ( fPtr2 )) != EOF)
printf ( "%c" , s ) ;
}
fclose ( fPtr1 ) ;
fclose ( fPtr2 ) ;
}
int compareFile ( FILE * fPtr1 , FILE * fPtr2 ) {
char ch1 , ch2 ;
do{
ch1 = fgetc ( fPtr1 ) ;
ch2 = fgetc ( fPtr2 ) ;
172
i f (ch1 != ch2)
return −1;
} while (ch1 != EOF && ch2 != EOF) ;
i f (ch1 == EOF && ch2 == EOF)
return 0;
else
return −1;
}
11.4.4 Input and Output
Figure 131: Contents of 123.txt.
Figure 132: Contents of 126.txt.
Figure 133: Output after comparing 123.txt and 126.txt files contents.
Objectives
To understand the use of file I/O commands using streams. Have a clear knowledge on read,
write, append and update modes while performing any file operations.
To write programs that execute read and write files using the formatting I/O and character I/O
functions.
To understand and apply file positioning, status and system commands based on a problem
requirements.
173
12
WEEK
Command Line Arguments
12.1 Copy the Content of File
Write a C program to copy the content of one file into another file using command line argu-
ments.
12.1.1 Algorithm
1 Start
2 Call main(3, "w12_1.exe", "123.txt", "124.txt") function.
3 Stop.
1 function main(argc, **argv)
2 Declare one character variable ch and two file pointers fs and ft.
3 If argc != 3 then display "Invalid no. of arguments" and return.
4 Call fopen(argv[1], "r") function using fs to open 123.txt file in read mode.
5 Call fopen(argv[2], "w") function using ft to open 124.txt file in write mode.
6 If fs == NULL or ft == NULL then display "Unable to open file(s) and return.
7 Read a character from 123.txt using fs and store it into ch.
8 Repeat step till ch == EOF is satisfied.
9 Write ch value to 124.txt using fp.
10 Read a character from 123.txt using fs and store it into ch.
11 Call fclose(fs) function to close the file input stream linked to 123.txt.
12 Call fclose(ft) function to close the file output stream linked to 124.txt.
13 Display "Successfully updated".
Algorithm 64: Copy the content of one file into another file.
174
12.1.2 Flow Chart
Figure 134: Copy the content of one file into another file.
175
12.1.3 C Source Code
#include<stdio .h>
#include<stdlib .h>
void main( int argc , char* argv [ ] )
{
FILE * fs , * f t ;
int ch ;
i f ( argc !=3)
{
printf ( " Invalid numbers of arguments .n" ) ;
exit (EXIT_FAILURE ) ;
}
fs = fopen( argv [1] , "r " ) ;
f t = fopen( argv [2] , "w" ) ;
i f ( fs == NULL | | f t == NULL)
{
perror ( "Error" ) ;
printf ( "Press any key to exit . . . n" ) ;
exit (EXIT_FAILURE ) ;
}
while (( ch = fgetc ( fs )) != EOF)
fputc (ch , f t ) ;
printf ( " Successfully updated n" ) ;
fclose ( fs ) ;
fclose ( f t ) ;
}
176
12.1.4 Input and Output
Figure 135: Contents of 123.txt.
Figure 136: Command line arguments for copying a file contents.
Figure 137: Contents of 124.txt after copy operation.
177
12.2 Minimum and Maximum Integers in a List
Write a C program that reads integer data from the standard input unit and prints the minimum
integer read, maximum integer read, and the average of the list. Test your program with the data
shown below. Use command line arguments to take the inputs. The set of integer numbers are
{24, 7, 31, -5, 64, 0, 57, -23, 7, 63, 31, 15, 7, -3, 2, 4, 6}
12.2.1 Algorithm
1 Start
2 Call main(18, "w12_2.exe", "24", "7", "31", "-5", ..., "2", "4", "6") function.
3 Stop.
1 function main(argc, **argv)
2 Declare i, min, max, sum and an array arr.
3 Initialize sum to 0.
4 If argc != 18 then display "Invalid no. of arguments" and return.
5 Initialize i to 1.
6 Repeat step 7 and 8 until i > 17 is satisfied
7 Convert argv[i] to integer and store it into arr[i-1].
8 Increment i by 1.
9 Initialize min and max to arr[0]
10 Reinitialize i to 0
11 Repeat step 12 to 14 until i is equal to 17 satisfied
12 If max is smaller than arr[i] then store arr[i] value in max
13 If min is greater than arr[i] then store arr[i]’s value in min.
14 Add arr[i]’s value to sum.
15 Display the of max, min and sum/argc.
Algorithm 65: Maximum, minimum and average of a list of elements.
178
12.2.2 Flowchart
Figure 138: Maximum, minimum and average of a list of elements.
179
12.2.3 C Source Code
#include<stdio .h>
#include<stdlib .h>
void main( int argc , char* argv [ ] )
{
int i , min, max, arr [17] , sum = 0;
float avg ;
i f ( argc != 18)
{
printf ( " Invalid numbers of arguments . n" ) ;
exit (EXIT_FAILURE ) ;
}
for ( i = 1; i <= 17; i ++)
arr [ i −1] = atoi ( argv [ i ] ) ;
max = min = arr [ 0 ] ;
for ( i = 0; i < 17; i ++)
{
i f (max < arr [ i ] )
max = arr [ i ] ;
i f (min > arr [ i ] )
min = arr [ i ] ;
sum = sum + arr [ i ] ;
}
printf ( "The maximum is : %dn" , max) ;
printf ( "The minimum is : %dn" , min) ;
printf ( "The average is : %f n" , ( float )sum/argc ) ;
}
12.2.4 Input and Output
Figure 139: Maximum, minimum and average of the given list of elements.
180
12.3 Reverses Elements of an Array
Write a C program using the command line arguments. Write a function that reverses the ele-
ments of an array so that the last element becomes the first, the second from the last becomes
the second, and so forth. The function is to reverse the elements in place-that is, without using
another array. (It is permissible to use a variable to hold an element temporarily.) Test the pro-
gram twice, once with an even number of elements in the array and once with an odd number
of elements in the array.
12.3.1 Algorithm
1 Start
2 Call main(n+1, "w12_3.exe", "a1", "a2", ..., "an") function.
3 Stop.
1 function main(argc, **argv)
2 Declare i and an array arr of size n.
3 If argc < 2 then display "Less arguments" and return.
4 Initialize i to 1.
5 Repeat step 6 and 7 until i == argc is satisfied
6 Convert argv[i] to integer and store it into arr[i-1].
7 Increment i by 1.
8 Call reverse(arr, argc-1) function.
1 function reverse(*p, n)
2 Declare three variables: i, temp and mid.
3 Calculate middle index of array and store it into mid. (mid := (n-1)/2)
4 Initialize i to 0.
5 Repeat step 6 to 9 till i <= mid is satisfied.
6 Assign p[i] value to temp.
7 Assign p[n-1-i] value to p[i].
8 Assign temp’s value to p[n-1-i].
9 Increment i by 1.
10 Reinitialize i to 0.
11 Repeat step 12 and 13 till i < n is satisfied.
12 Display p[i]’s value.
13 Increment i by 1.
Algorithm 66: Reverse elements of an odd and even sized arrays.
181
12.3.2 Flowchart
Figure 140: Reverse elements of an odd and even sized arrays.
182
12.3.3 C Source Code
#include<stdio .h>
#include<stdlib .h>
void reverse ( int *p, int n ) ;
void main( int argc , char * argv [ ] ) {
int i , arr [20];
i f ( argc < 2){
printf ( " Invalid numbers of arguments . n" ) ;
exit (EXIT_FAILURE ) ;
}
for ( i = 1; i < argc ; i ++)
arr [ i −1] = atoi ( argv [ i ] ) ;
reverse ( arr , argc −1);
}
void reverse ( int *p, int n) {
char temp;
int i , mid = (n−1)/2;
for ( i = 0; i <= mid; i ++){
temp = p[ i ] ;
p[ i ] = p[n−1− i ] ;
p[n−1− i ] = temp;
}
for ( i = 0; i < n; i ++)
printf ( "%d t " , p[ i ] ) ;
}
12.3.4 Input and Output
Figure 141: Reverse elements of the given arrays.
Objectives
To use command line arguments to pass inputs in a single line while executing a program
through the DOS command prompt or Linux terminal.
To use atoi function to convert a default string value argument to an integer value inside the
main function in a program.
To use atof function to convert a default string value argument to a float value inside the main
function in a program.
183
13
WEEK
References
13.1 Text Books
1. Programming and Problem Solving Through "C" Language By HarshaPriya, R. Ranjeet
Firewall media 2006.
2. Behrouz A. Forouzan and Richard F. Gilberg, "Computer Science A Structured Program-
ming Approach Using C", CENGAGE Learning, Third Edition.
13.2 Reference Books
1. Anil B. Chaudhuri, "Flowchart and Algorithm Basics: The Art of Programming", Mercury
Learning Information, 2020.
2. R.G. Dromey, "How to Solve it By Computer", Prentice-Hall International Series in Com-
puter Science,1982.
3. YashwantKanetkar, "Let us C", BPB Publications, 16th Edition 2017.
4. Kernighan and Ritchie, "The C programming language", The (Ansi C Version), PHI, second
edition.
5. Paul J. Dietel and Harvey M. Deitel, "C: How to Program", Prentice Hall, 8th edition (Jan
19.2021).
6. K.R.Venugopal, Sundeep R. Prasad, "Mastering C", McGraw Hill, 2nd Edition, 2015.
184
13.3 e-Resources and Other Digital Materials
1. Computer Science and Engineering - Noc:problem Solving Through Programming in C.
[online] https://nptel.ac.in/courses/106/105/106105171/
2. Computer Science and Engineering Noc:introduction To Programming in C. [online]
https://nptel.ac.in/courses/106/104/106104128/
3. C For Everyone: Structured Programming. [online] https://www.coursera.org/
learn/c-structured-programming
4. Advanced C Programming CourseTim Academy-Jason Fedin. [online] https://www.
udemy.com/course/advanced-c-programming-course/
185

More Related Content

PDF
Algorithmic Problem Solving with Python.pdf
PDF
python learn basic tutorial learn easy..
PDF
0802 python-tutorial
PDF
Python everthing
PDF
0802 python-tutorial
PDF
Tutorial edit
PDF
Best Python tutorial (release 3.7.0)
PDF
452042223-Modern-Fortran-in-practice-pdf.pdf
Algorithmic Problem Solving with Python.pdf
python learn basic tutorial learn easy..
0802 python-tutorial
Python everthing
0802 python-tutorial
Tutorial edit
Best Python tutorial (release 3.7.0)
452042223-Modern-Fortran-in-practice-pdf.pdf

Similar to 20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf (20)

PDF
C++ For Quantitative Finance
PDF
An Introduction to Computer Science - python
PDF
numpyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DOCX
Think JavaHow to Think Like a Computer ScientistVersio.docx
PDF
C++ annotations version
PDF
Reading Materials for Operational Research
PDF
PDF
Thats How We C
PDF
Applied_Data_Science__17203210230123.pdf
PDF
Francois fleuret -_c++_lecture_notes
PDF
Mat power manual
PDF
Mastering Modern C++: C++11, C++14, C++17, C++20, C++23
PDF
Isoiec 148822011 Information Technology Programming Languages C 3rd Edition Iso
PDF
Introduction to Programming Using Java v. 7 - David J Eck - Inglês
PDF
Matrix Theory And Linear Algebra First Peter Selinger
PDF
Matrix Theory And Linear Algebra First Peter Selinger
PDF
An Introduction to Computational Networks and the Computational Network Toolk...
PDF
Tinyos programming
PDF
Advanced Calculus and Analysis MA1002 - CiteSeer ( PDFDrive ).pdf
C++ For Quantitative Finance
An Introduction to Computer Science - python
numpyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Think JavaHow to Think Like a Computer ScientistVersio.docx
C++ annotations version
Reading Materials for Operational Research
Thats How We C
Applied_Data_Science__17203210230123.pdf
Francois fleuret -_c++_lecture_notes
Mat power manual
Mastering Modern C++: C++11, C++14, C++17, C++20, C++23
Isoiec 148822011 Information Technology Programming Languages C 3rd Edition Iso
Introduction to Programming Using Java v. 7 - David J Eck - Inglês
Matrix Theory And Linear Algebra First Peter Selinger
Matrix Theory And Linear Algebra First Peter Selinger
An Introduction to Computational Networks and the Computational Network Toolk...
Tinyos programming
Advanced Calculus and Analysis MA1002 - CiteSeer ( PDFDrive ).pdf
Ad

More from Ashutosh Satapathy (12)

PDF
Visual Aids for Exploratory Data Analysis.pdf
PDF
Linked List Data Structures .
PDF
The Value of Business Intelligence .
PDF
Business Intelligence and Information Exploitation.pdf
PDF
Introduction to Data Structures .
PDF
Searching and Sorting Algorithms
PDF
Multidimensional Data
PDF
Time and Space Complexity
PDF
Algorithm Specification and Data Abstraction
PDF
Secure Multi-Party Computation
Visual Aids for Exploratory Data Analysis.pdf
Linked List Data Structures .
The Value of Business Intelligence .
Business Intelligence and Information Exploitation.pdf
Introduction to Data Structures .
Searching and Sorting Algorithms
Multidimensional Data
Time and Space Complexity
Algorithm Specification and Data Abstraction
Secure Multi-Party Computation
Ad

Recently uploaded (20)

PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT
Mechanical Engineering MATERIALS Selection
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
composite construction of structures.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
web development for engineering and engineering
PPTX
Welding lecture in detail for understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
PPT on Performance Review to get promotions
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Construction Project Organization Group 2.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
DOCX
573137875-Attendance-Management-System-original
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Mechanical Engineering MATERIALS Selection
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
composite construction of structures.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
web development for engineering and engineering
Welding lecture in detail for understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPT on Performance Review to get promotions
Foundation to blockchain - A guide to Blockchain Tech
bas. eng. economics group 4 presentation 1.pptx
Internet of Things (IOT) - A guide to understanding
Construction Project Organization Group 2.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
573137875-Attendance-Management-System-original

20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf

  • 1. LABORATORY MANUAL PROGRAMMING FOR PROBLEM SOLVING (20ES1152) I/IV B.TECH, FIRST SEMESTER REGULATION: VR20 DEPARTMENT OF SCIENCE AND HUMANITIES VELAGAPUDI RAMAKRISHNA SIDDHARTHA ENGINEERING COLLEGE (AUTONOMOUS, ACCREDITED WITH ’A+’ GRADE BY NAAC)
  • 2. List of Programs 1 Introduction to C Programming 4 1.1 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 Print Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.3 Escape Sequence and Format Specifiers . . . . . . . . . . . . . . . . . 10 1.4 Literal, Defined and Memory Constants . . . . . . . . . . . . . . . . . 12 1.5 ASCII to Text Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2 Data Types and Variable Declarations 16 2.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.2 Swap Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.3 Comparison of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.4 Size and Range of C Data Types . . . . . . . . . . . . . . . . . . . . . . 26 3 Selection – Making Decisions 30 3.1 Even or Odd Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 3.2 Biggest and Smallest Number . . . . . . . . . . . . . . . . . . . . . . . 33 3.3 Leap Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.4 Electricity Bill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4 Looping Constructs and Their Applications 42 4.1 Decimal to Binary Conversion . . . . . . . . . . . . . . . . . . . . . . . 42 4.2 Factorial of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.3 Reverse of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.4 Strong Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.5 Armstrong Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.6 Fibonacci Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.7 Palindrome Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.8 Perfect Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.9 Print Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 4.10 Prime Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5 Unconditional Control Transfer Statements 72 5.1 Calculator Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 5.2 Sum of N Natural Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.3 Even Numbers not Divisible by 6 and 8 . . . . . . . . . . . . . . . . . . 77 6 Arrays and Their Applications 79 6.1 Minimum and Maximum Elements . . . . . . . . . . . . . . . . . . . . 79 6.2 Sorting of n numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 1
  • 3. 6.3 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 6.4 Insertion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 6.5 Remove Duplicate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 6.6 Matrix Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 6.7 Matrix Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 6.8 Matrix Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 7 Strings, String I/O and Manipulation Functions 106 7.1 String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 7.2 Reverse a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7.3 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7.4 String Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 8 Concepts of User Defined Functions 121 8.1 Swap Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.2 Factorial of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 8.3 Combination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 8.4 Mean and Standard Deviation . . . . . . . . . . . . . . . . . . . . . . . 134 9 Pointers and Their Applications 138 9.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 9.2 String Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 9.3 Largest Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 10 Structure, Union, and Enumeration 148 10.1 Student’s Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 10.2 Students’ Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 10.3 Days in a Week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 11 File Handling Operations 158 11.1 Count Number of Character, Spaces, Words and Lines . . . . . . . . . 158 11.2 Count Number of Alphabets, Digits, Punctuation Marks . . . . . . . 162 11.3 Merge Contents of Two Files . . . . . . . . . . . . . . . . . . . . . . . . 166 11.4 Compare Contents of Two Files . . . . . . . . . . . . . . . . . . . . . . 170 12 Command Line Arguments 174 12.1 Copy the Content of File . . . . . . . . . . . . . . . . . . . . . . . . . . 174 12.2 Minimum and Maximum Integers in a List . . . . . . . . . . . . . . . 178 12.3 Reverses Elements of an Array . . . . . . . . . . . . . . . . . . . . . . . 181 13 References 184 13.1 Text Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 2
  • 4. 13.2 Reference Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 13.3 e-Resources and Other Digital Materials . . . . . . . . . . . . . . . . . 185 About This This manual is being offered to train first year first semester undergraduate students at VRSEC – Vijayawada on the fundamentals of the ‘C’ programming language. The purpose of it is to help students to understand basic programming concepts such as literals, data types, and variable declaration, branching, looping, arrays, functions, string, pointer, file, structure, enum, and command-line arguments execution. 3
  • 5. 1 WEEK Introduction to C Programming 1.1 Variable Declarations Code the variable declarations for each of the following. a. a character variable named option b. an integer variable sum, initialized to 0, c. a floating-point variable product, initialized to 1, d. a short integer variable named code, e. a constant named sales_Tax initialized to 0.0825, f. a floating-point named sum_of_size double initialized to 0. 1.1.1 Algorithm 1 Start 2 Declare variables option, sum and product. 3 Initialize sum to 0. 4 Initialize product to 1. 5 Declare code, sales_Tax and sum_of_size. 6 Initialize sales_Tax to 0.0825. 7 Initialize sum_of_size to 0. 8 Stop. Algorithm 1: Variable declarations and initialization. 4
  • 6. 1.1.2 Flowchart Figure 1: Variable declarations and initialization. 5
  • 7. 1.1.3 C Source Code #include<stdio .h> void main ( ) { / / a character variable named option . char option ; / / an integer variable , sum, initialized to 0. int sum = 0; / / a floating −point variable , product , initialized to 1. float product = 1; / / a short integer variable named code . short int code ; / / a constant named sales_Tax initialized to 0.0825. const float sales_Tax = 0.0825; / / a floating −point named sum_of_size double initialized to 0. float sum_of_size = 0; } 1.1.4 Input and Output Figure 2: Character, integer, floating-point variable declarations and initialization. 6
  • 8. 1.2 Print Patterns Write C programs that uses four print statements to print the pattern of asterisks shown below. 1.2.1 Algorithm 1 Start 2 Display six ’*’ by giving a tab in between each ’*’. 3 Display six ’*’ by giving a tab in between each ’*’ in a new line. 4 Display six ’*’ by giving a tab in between each ’*’ in a new line. 5 Display six ’*’ by giving a tab in between each ’*’ in a new line. 6 Stop. Algorithm 2: Rectangle star pattern. 1 Start 2 Display a ’*’. 3 Display two ’*’ by giving a tab in between each ’*’ in a new line. 4 Display three ’*’ by giving a tab in between each ’*’ in a new line. 5 Display four ’*’ by giving a tab in between each ’*’ in a new line. 6 Stop. Algorithm 3: Right angle triangle star pattern. 7
  • 9. 1.2.2 Flowchart Figure 3: Rectangle star pattern. Figure 4: Right angle triangle star pattern. 8
  • 10. 1.2.3 C Source Code I . #include<stdio .h> void main ( ) { printf ( "* t * t * t * t * t *n" ) ; printf ( "* t * t * t * t * t *n" ) ; printf ( "* t * t * t * t * t *n" ) ; printf ( "* t * t * t * t * t *n" ) ; } II . #include<stdio .h> void main ( ) { printf ( "*n" ) ; printf ( "* t *n" ) ; printf ( "* t * t *n" ) ; printf ( "* t * t * t *n" ) ; } 1.2.4 Input and Output Figure 5: Rectangle star pattern [4x6]. Figure 6: Right angle triangle star pattern. 9
  • 11. 1.3 Escape Sequence and Format Specifiers Write a C program that defines five integer variables and initializes them to 1, 10, 100, 1000, and 10000. If then prints them on a single line separated by space characters using the decimal con- version code (%d), and on the next line with the float conversion code (%f). Note the differences between the results. 1.3.1 Algorithm 1 Start 2 Declare variables a, b, c, d and e. 3 Initialize a to 1, b to 10, c to 100, d to 1000 and e to 10000. 4 Display a, b, c, d and e values. 5 Map the a and b values to real numbers and display them. 6 Map the c, d and e values to real numbers and display them. 7 Stop. Algorithm 4: Variable declarations and initialization. 1.3.2 Flowchart Figure 7: Outcomes using escape sequence and format specifiers. 10
  • 12. 1.3.3 C Source Code #include<stdio .h> void main ( ) { int a = 1 , b = 10 , c = 100, d = 1000, e = 10000; printf ( "a : %d, b : %d, c : %d, d : %d, e : %d n" ,a ,b, c ,d, e ) ; printf ( "a : %f , b : %f " , ( float )a , ( float )b ) ; printf ( "c : %f , d : %f , e : %f n" , ( float )c , ( float )d , ( float )e ) ; } 1.3.4 Input and Output Figure 8: Outcomes using n escape sequence, %d and %f format specifiers. 11
  • 13. 1.4 Literal, Defined and Memory Constants Write a C program that uses defined constants for the vowels in the alphabet and memory con- stants for the even decimal digits (0, 2, 4, 6, 8). It then prints the following three lines using literal constants for the odd digits. 1.4.1 Algorithm 1 Start 2 Define a to ’a’, b to ’e’, c to ’i’, d to ’o’ and e to ’u. 3 Declare i, j, k, l and m. 4 Initialize i to 0, j to 2, k to 4, l to 6 and m to 8. 5 Display a, b, c, d and e values. 6 Display i, j, k, l and m values. 7 Display 1, 3, 5, 7 and 9. 8 Stop. Algorithm 5: Variable declarations and initialization. 1.4.2 Flowchart Figure 9: Literal, defined and memory constants. 12
  • 14. 1.4.3 C Source Code #include<stdio .h> #define a ’a ’ #define b ’e ’ #define c ’ i ’ #define d ’o ’ #define e ’u ’ void main ( ) { const int i = 0 , j = 2 , k = 4 , l = 6 , m = 8; printf ( "%c t %c t %c t %c t %c n" , a , b, c , d, e ) ; printf ( "%d t %d t %d t %d t %d n" , i , j , k , l , m) ; printf ( "%d t %d t %d t %d t %d n" , 1 , 3 , 5 , 7 , 9); } 1.4.4 Input and Output Figure 10: Literal, defined and memory constants of vowels and single digit decimal numbers. 13
  • 15. 1.5 ASCII to Text Conversion Write a C program that prompts the user to enter an integer and then prints the integer first as a character, then as a decimal. Use separate print statements. A sample run is shown below. The number as a character: K The number as a decimal: 75 1.5.1 Algorithm 1 Start 2 Declare a variable k. 3 Store an integral value in k. 4 Display the corresponding character value of k. 5 Display the decimal value of k. 6 Stop. Algorithm 6: Variable declarations and initialization. 1.5.2 Flowchart Figure 11: ASCII to text conversion. 14
  • 16. 1.5.3 C Source Code #include<stdio .h> void main ( ) { int k ; printf ( "Enter the value of k n" ) ; scanf ( "%d" , &k ) ; printf ( "The number as a character : %c" , k ) ; printf ( "The number as a decimal : %d" , k ) ; } 1.5.4 Input and Output Figure 12: ASCII value 75 to text conversion. Objectives To understand the basic building block of a C program. To provide a glance on the C identifiers, data types, format specifiers, constants, and variables declaration and initialization. To write simple C programs using preprocessor commands and simple input and output state- ments. 15
  • 17. 2 WEEK Data Types and Variable Declarations 2.1 Arithmetic Operations Write a C program to perform simple arithmetic operations on two bool, character, integer and floating point variables. 2.1.1 Algorithm 1 Start 2 Declare three integer variables a, b, x, y, i, j, l and m. 3 Get the boolean values for a and b. 4 Get the character values for x and y. 5 Get the integer values for i and j. 6 Get the real values for l and m. 7 Add a with b, subtract b from a and display the result. 8 Multiply a with b, divide a by b and display the product, quotient and reminder values. 9 Add i with j, subtract j from i and display the results. 10 Multiply i with j, divide i by j and display the product, quotient and reminder values. 11 Add l with m, subtract m from l and display the results. 12 Multiply l with m, divide l by m and display the product and quotient values. 13 Add x with y, subtract y from x and display the results. 14 Multiply x with y, divide x by y and display the product, quotient and reminder values. 15 Stop. Algorithm 7: Arithmetic operations between different types of data. 16
  • 18. 2.1.2 Flowchart Figure 13: Arithmetic operations between different types of data. 17
  • 19. 2.1.3 C Source Code #include<stdio .h> #include<stdbool .h> void main() { bool a = false , b = true ; char x , y ; int i , j ; float l , m; printf ( "Enter the integer values of i and j : n" ) ; scanf ( "%d %d" , &i , &j ) ; printf ( "Enter the float values of l and m : n" ) ; scanf ( "%f %f " , &l , & m) ; printf ( "Enter the character values of x and y : n" ) ; scanf ( "%c %c" , &x , &y ) ; printf ( "Arithmetic operations on boolean data : n" ) ; printf ( "Addition : %d n Subtraction : %d n" , a+b, a−b ) ; printf ( " Multiplication : %d n Division : %d n Modulus %d n" , a*b, a/b, a%b ) ; printf ( "Arithmetic operations on integer data : n" ) ; printf ( "Addition : %d n Subtraction : %d n" , i+j , i −j ) ; printf ( " Multiplication : %d n Division : %d n Modulus : %d n" , i * j , i / j , i%j ) ; printf ( "Arithmetic operations on float data : n" ) ; printf ( "Addition : %f n Subtraction : %f n" , l+m, l −m) ; printf ( " Multiplication : %f n Division : %f n" , l *m, l /m) ; printf ( "Arithmetic operations on character data : n" ) ; printf ( "Addition : %c n Subtraction : %c n" , x+y , x−y ) ; printf ( " Multiplication : %c n Division : %c n Modulus : %c n" , x*y , x/y , x%y ) ; } 18
  • 20. 2.1.4 Input and Output Figure 14: Arithmetic operations between boolean, integer, float, and character data. 19
  • 21. 2.2 Swap Two Numbers Write C programs to swap two integer numbers. a. With third variable, b. Without third variable. 2.2.1 Algorithm 1 Start 2 Declare three integer variables a, b and temp. 3 Get the values for a and b. 4 Store a’s value to temp. (temp := a) 5 Store b’s value to a. So, a has b’s value now. (a := b) 6 Store temp’s value (the value of the old a) in b. 7 Display a and b values. 8 stop. Algorithm 8: Swap two integer numbers with third variable. 1 Start 2 Declare three integer variables a and b. 3 Get the values for a and b. 4 Store addition of a’s and b’s values to a. (a := a+b) 5 Subtract b from a, and store the result in b. (b := a-b) 6 Subtract b from a, and store the result in a (the value of the old a) in b. (a:= a-b) 7 Display the values of a and b. 8 stop. Algorithm 9: Swap two integer numbers without third variable. 20
  • 22. 2.2.2 Flowchart Figure 15: Swap two integer numbers with third variable. Figure 16: Swap two integer numbers without third variable. 21
  • 23. 2.2.3 C Source Code a . #include<stdio .h> void main ( ) { int a , b, temp; printf ( "Enter two integer values : " ) ; scanf ( "%d %d" , &a , &b ) ; printf ( "a = %d, b = %d n" , a , b ) ; temp = a ; a = b; b = temp; printf ( " After swapping the values : n" ) ; printf ( "a = %d, b = %d n" , a , b ) ; } b. #include<stdio .h> void main ( ) { int a , b; printf ( "Enter two integer values : " ) ; scanf ( "%d %d" , &a , &b ) ; printf ( "a = %d, b = %d n" , a , b ) ; a = a+b; b = a−b; a = a−b; printf ( " After swapping the values : n" ) ; printf ( "a = %d, b = %d n" , a , b ) ; } 2.2.4 Input and Output Figure 17: Swap a=5 and b=3 using third variable. Figure 18: Swap a=5 and b=3 without third variable. 22
  • 24. 2.3 Comparison of Numbers Write two C programs to find the greatest and smallest among three variables without using any compound statements. a. Using simple relational and logical operators. b. Using the Ternary operator. 2.3.1 Algorithm 1 Start 2 Declare variable a, b, c, max, min. 3 Get the values for a, b and c. 4 Compute (a >= b && a >= c)*a + (b > a && b >= c)*b + (c > a && c > b)*c. 5 Store the result in max. 6 Compute (a <= b && a <= c)*a + (b < a && b <= c)*b + (c < a && c < b)*c. 7 Store the result in min. 8 Display max and min. 9 Stop. Algorithm 10: The greatest and smallest among three variables using relational and logical operators. 1 Start 2 Declare variables a, b, c, max, min. 3 Get the value of a, b and c. 4 If a > b go to step 5 Otherwise go to step 6. 5 If a > c, set max = a, otherwise max = c. 6 If b > c, set max = b, otherwise max = c. 7 If a < b go to step 8, otherwise go to step 9. 8 If a < c, set min = a, otherwise min = c. 9 If b < c, set min = b, otherwise min = c. 10 Display max and min. 11 Stop. Algorithm 11: The greatest and smallest among three variables. 23
  • 25. 2.3.2 Flowchart Figure 19: The greatest and smallest among three variables using relational and logical opera- tors. Figure 20: The greatest and smallest among three variables using the Ternary operators. 24
  • 26. 2.3.3 C Source Code a . #include<stdio .h> void main ( ) { int a , b, c , max, min; printf ( "Enter three integer values : " ) ; scanf ( "%d %d %d" , &a , &b, &c ) ; printf ( "a = %d, b = %d, c = %d n" , a , b, c ) ; max = (a >= b && a >= c )* a + (b > a && b >=c )*b + ( c > a && c > b)* c ; min = (a <= b && a <= c )* a + (b < a && b <=c )*b + ( c < a && c < b)* c ; printf ( "Largest : %d n" , max) ; printf ( "Smallest : %d" ,min) ; } b. #include<stdio .h> void main ( ) { int a , b, c , max, min; printf ( "Enter three integer values : " ) ; scanf ( "%d %d %d" , &a , &b, &c ) ; printf ( "a = %d, b = %d, c = %d n" , a , b, c ) ; max = (a>b ) ? ( ( a>c )? a : c ) : ( ( b>c )? b : c ) ; min = (a<b ) ? ( ( a<c )? a : c ) : ( ( b<c )? b : c ) ; printf ( "Largest : %d n" , max) ; printf ( "Smallest : %d" ,min) ; } 2.3.4 Input and Output Figure 21: The greatest and smallest among a = 5, b = 7 and c = 2 using relational and logical operators. Figure 22: The greatest and smallest among a = 5, b = 7 and c = 2 using the Ternary operators. 25
  • 27. 2.4 Size and Range of C Data Types Write a C program to display size and range of the below data types. a. char b. signed char c. int d. signed int e. unsigned int f. long int g. long long int h. intmax_t i. size_t j. float k. double l. long double 2.4.1 Algorithm 1 Start 2 Use the sizeof() operator to display the size of each datatype. 3 Display the size of char and signed char data types. 4 Display the size of int, signed int and unsigned int data types. 5 Display the size of long int and long long int data types. 6 Display the size of intmax_t and size_t data types. 7 Display the size of float, double and long double data types. 8 Use the stdio.h, stddef.h, stdint.h, limits.h and float.h header files to print the minimum and maximum values of the data-types. 9 Display CHAR_MIN and CHAR_MAX. 10 Display SCHAR_MIN and SCHAR_MAX. 11 Display INT_MIN and INT_MAX. 12 Display UINT_MIN and UINT_MAX. 13 Display SHT_MIN and SHT_MAX. 14 Display LONG_MIN and LONG_MAX. 15 Display LLONG_MIN and LLONG_MAX. 16 Display INTMAX_MIN and INTMAX_MAX. 17 Display SIZE_MIN and SIZE_MAX. 18 Display FLT_MIN and FLT_MAX. 19 Display DBL_MIN and DBL_MAX. 20 Display LDBL_MIN and LDBL_MAX. 21 Stop. Algorithm 12: The greatest and smallest among three variables using relational and logical operators. 26
  • 28. 2.4.2 Flowchart Figure 23: Data types’ ranges and sizes. 27
  • 29. 2.4.3 C Source Code #include<stdio .h> #include<stddef .h> #include<stdint .h> #include<limits .h> #include<float .h> #define UINT_MIN 0 #define SIZE_MIN 0 void main ( ) { printf ( "char : %ld n" , sizeof (char ) ) ; printf ( "signed char %ld n" , sizeof ( signed char ) ) ; printf ( " int : %ld n" , sizeof ( int ) ) ; printf ( "signed int : %ld n" , sizeof ( signed int ) ) ; printf ( "unsigned int : %ld n" , sizeof (unsigned int ) ) ; printf ( "long int : %ld n" , sizeof ( long int ) ) ; printf ( "long long int : %ld n" , sizeof ( long long int ) ) ; printf ( "intmax_t : %ld n" , sizeof ( intmax_t ) ) ; printf ( " size_t : %ld n" , sizeof ( size_t ) ) ; printf ( " float : %ld n" , sizeof ( float ) ) ; printf ( "double : %ld n" , sizeof (double ) ) ; printf ( "long double : %ld n" , sizeof ( long double ) ) ; printf ( "The minimum value of CHAR is = %dn" , CHAR_MIN) ; printf ( "The maximum value of CHAR is = %dn" , CHAR_MAX) ; printf ( "The minimum value of Signed CHAR is = %dn" , SCHAR_MIN) ; printf ( "The maximum value of Signed CHAR is = %dn" , SCHAR_MAX) ; printf ( "The minimum value of INT is = %dn" , INT_MIN) ; printf ( "The maximum value of INT is = %dn" , INT_MAX) ; printf ( "The minimum value of signed INT is = %dn" , INT_MIN) ; printf ( "The maximum value of signed INT is = %dn" , INT_MAX) ; printf ( "The minimum value of Unsigned INT is = %un" , UINT_MIN) ; printf ( "The maximum value of Unsigned INT is = %un" , UINT_MAX) ; printf ( "The minimum value of Short INT is = %dn" , SHRT_MIN) ; printf ( "The maximum value of Short INT is = %dn" , SHRT_MAX) ; printf ( "The minimum value of LONG INT is = %ldn" , LONG_MIN) ; printf ( "The maximum value of LONG INT is = %ldn" , LONG_MAX) ; printf ( "The minimum value of LONG LONG INT is = %lld n" , LLONG_MIN) ; printf ( "The maximum value of LONG LONG INT is = %lld n" , LLONG_MAX) ; printf ( "The minimum value of INTMAX_T is = %lld n" , INTMAX_MIN) ; printf ( "The maximum value of INTMAX_T is = %lld n" , INTMAX_MAX) ; printf ( "The minimum value of SIZE_T is = %llu n" , SIZE_MIN ) ; printf ( "The maximum value of SIZE_T is = %llu n" , SIZE_MAX ) ; printf ( "The minimum value of float is = %.10en" , FLT_MIN) ; printf ( "The maximum value of float is = %.10en" , FLT_MAX) ; printf ( "The minimum value of Double is = %.10en" , DBL_MIN) ; printf ( "The maximum value of Double is = %.10en" , DBL_MAX) ; 28
  • 30. printf ( "The minimum value of LONG Double is = %.10Len" ,LDBL_MIN) ; printf ( "The maximum value of LONG Double is = %.10Len" ,LDBL_MAX) ; } 2.4.4 Input and Output Figure 24: Size and range of C data types. Objectives To understand the roles of various of data types for performing different mathematical opera- tions. To provide a clear idea on variables and constants creation and their use in a C program. To deliver a clear knowledge on void, integral and floating point data types and their use in dif- ferent scenarios. 29
  • 31. 3 WEEK Selection – Making Decisions 3.1 Even or Odd Number Write a C program to check whether a given integer number is even or odd. 3.1.1 Algorithm 1 Start 2 Declare a variable num. 3 Get the value for num. 4 Perform num modulus 2 and check result if output is 0. 5 If true, display num is an even number. 6 If false, display num is an odd number. 7 Stop Algorithm 13: Check a number is even or odd number. 30
  • 32. 3.1.2 Flowchart Figure 25: Even or odd number. 31
  • 33. 3.1.3 C Source Code #include<stdio .h> void main ( ) { int num; printf ( "Enter an integer number : n" ) ; scanf ( "%d" , &num) ; i f (num % 2 == 0) printf ( "%d is an even number" , num) ; else printf ( "%d is an odd number" , num) ; } 3.1.4 Input and Output Figure 26: Even or odd number. 32
  • 34. 3.2 Biggest and Smallest Number Write a C program to find the biggest and smallest among the three numbers. 3.2.1 Algorithm 1 Start 2 Declare variables a, b and c. 3 Get the values of a, b and c. 4 If a > b go to step 5 Otherwise go to step 6. 5 If a > c display ’a is biggest’, otherwise ’c is biggest’. 6 If b > c display ’b is biggest’, otherwise ’c is biggest’. 7 Stop. Algorithm 14: Biggest among three numbers. 1 Start 2 Declare variables a, b and c. 3 Get the values of a, b and c. 4 If a < b go to step 5 Otherwise go to step 6. 5 If a < c display ’a is smallest’, otherwise ’c is smallest’. 6 If b < c display ’b is smallest’, otherwise ’c is smallest’. 7 Stop. Algorithm 15: Smallest among three numbers. 33
  • 35. 3.2.2 Flowchart Figure 27: Biggest among three numbers. Figure 28: Smallest among three numbers. 34
  • 36. 3.2.3 C Source Code a . #include<stdio .h> void main ( ) { int a ,b, c ; printf ( "Enter three integer numbers: n" ) ; scanf ( "%d %d %d" , &a , &b, &c ) ; i f (a>=b) { i f (a>=c ) printf ( "%d is biggest n" , a ) ; else printf ( "%d is biggest n" , c ) ; } else { i f (b>=c ) printf ( "%d is biggest n" , b ) ; else printf ( "%d is biggest n" , c ) ; } } b. #include<stdio .h> void main ( ) { int a ,b, c ; printf ( "Enter three integer numbers: n" ) ; scanf ( "%d %d %d" , &a , &b, &c ) ; i f (a<=b) { i f (a<=c ) printf ( "%d is smallest n" , a ) ; else printf ( "%d is smallest n" , c ) ; } else { i f (b<=c ) printf ( "%d is smallest n" , b ) ; else printf ( "%d is smallest n" , c ) ; } } 35
  • 37. 3.2.4 Input and Output Figure 29: Largest among three numbers. Figure 30: Smallest among three numbers. 36
  • 38. 3.3 Leap Year Write a C program to check whether a year is a leap year or not. 3.3.1 Algorithm 1 Start 2 Take integer variable yr. 3 Assign value to the variable yr. 4 Check if yr is divisible by 100 and 400, display "yr is a leap year". 5 Check if yr is divisible by 4 but not 100, display "yr is a leap year". 6 Otherwise, display "yr is not leap year". 7 Stop. Algorithm 16: Biggest among three numbers. 3.3.2 Flowchart Figure 31: A year is a leap year or not. 37
  • 39. 3.3.3 C Source Code #include<stdio .h> void main ( ) { int yr ; printf ( "Enter a year to check leap yr . or not : " ) ; scanf ( "%d" , &yr ) ; i f ( yr%100 == 0 && yr%400 == 0) printf ( "%d is a leap year" , yr ) ; else i f ( yr%100 != 0 && yr%4 == 0) printf ( "%d is a leap year" , yr ) ; else printf ( "%d is not a leap year" , yr ) ; } 3.3.4 Input and Output Figure 32: Verify year 1900 is a leap year or not. 38
  • 40. 3.4 Electricity Bill Write a C program to print electricity bill with slabs. Unit Charge/Unit Up to 199 @1.20 200 and above but less than 400 @1.50 400 and above but less than 600 @1.80 600 and above @2.00 3.4.1 Algorithm 1 Start 2 Declare two variables units and ebill. 3 Enter total units consumed by the customer using the variable units. 4 If the units less than 200 units, calculates the ebill. [ebill := units*1.20]. 5 If units between 200 to 400 units, calculates the ebill. [ebill := 199*1.20 + (units-199)*1.50]. 6 If units between 400 to 600 units ,calculates the ebill. [ebill := 199*1.20 + 200*1.50 + (units-399)*1.80]. 7 Else, calculates the ebill. [ebill := 199*1.20 +200*1.50 + 200*1.80 + (unit-599)*2.0]. 8 Stop. Algorithm 17: Compute electricity bill with slabs. 39
  • 41. 3.4.2 Flowchart Figure 33: Compute electricity bill with slabs. 40
  • 42. 3.4.3 C Source Code #include<stdio .h> void main ( ) { int units ; float e b i l l ; printf ( "Enter the amount of units consumed : n" ) ; scanf ( "%d" , &units ) ; i f ( units <200) e b i l l = units * 1.20; else i f ( units >= 200 && units < 400) e b i l l = 199*1.20 + ( units −199)*1.50; else i f ( units >= 400 && units < 600) e b i l l = 199*1.20 + 200*1.50 + ( units −399)*1.80; else e b i l l = 199*1.20 + 200*1.50 + 200*1.80 + ( units −599)*2.0; printf ( "The total e b i l l amount is %f " , e b i l l ) ; } 3.4.4 Input and Output Figure 34: Electricity bill calculation for the consumed units 260. Objectives To write programs using the if...else selection statements. To understand the nested if...else statement and use it to solve problems that need multi-level selection making decisions. To write programs that use switch...case and else...if multi way statements to select one out of several options. 41
  • 43. 4 WEEK Looping Constructs and Their Applications 4.1 Decimal to Binary Conversion Write a C program to convert a decimal number to binary number using while loop. 4.1.1 Algorithm 1 Start 2 Declare four variables num, sum, rem and cnt. 3 Initialize sum and cnt to 0. 4 Get the decimal integer value for num. 5 Repeat step 6 to 8 until num == 0 is satisfied. 6 Divide num by 2 and store the reminder and quotient into rem and num. 7 Compute rem*10cnt and it to the current sum. 8 Increment cnt by 1. 9 Display the value of sum. 10 Stop. Algorithm 18: Decimal to binary conversion. 42
  • 44. 4.1.2 Flowchart Figure 35: Decimal to binary conversion. 43
  • 45. 4.1.3 C Source Code #include<stdio .h> #include<math.h> void main ( ) { int num, rem, sum = 0 , cnt = 0; printf ( "Enter a decimal number : " ) ; scanf ( "%d" , &num) ; while (num != 0){ rem = num % 2; sum = rem * pow(10 , cnt ) + sum; num = num/2; cnt++; } printf ( "The binary no is %d" , sum) ; } 4.1.4 Input and Output Figure 36: Binary value of decimal number 10. 44
  • 46. 4.2 Factorial of a Number Write a C program to find factorial of the given number using while loop. 4.2.1 Algorithm 1 Start 2 Declare two variables: num and fact, where fact is initialized to 1. 3 Get the decimal integer value for num. 4 Repeat step 5 and 6 until num == 0 is satisfied. 5 Multiply num to the current value of fact. 6 Decrement num by 1. 7 Display the value of fact. 8 Stop. Algorithm 19: Factorial of a number. 4.2.2 Flowchart Figure 37: Factorial of a number. 45
  • 47. 4.2.3 C Source Code #include<stdio .h> void main() { int num, fact = 1; printf ( "Enter a integer number n" ) ; scanf ( "%d" , &num) ; while (num != 0){ fact = fact * num; num−−; } printf ( " Factorial of a number is %d" , fact ) ; } 4.2.4 Input and Output Figure 38: Factorial of the number 6. 46
  • 48. 4.3 Reverse of a Number Write a C program to print the reverse of a given number using while loop. 4.3.1 Algorithm 1 Start 2 Declare three variables num, sum and rem. 3 Initialize sum to 0. 4 Get the decimal integer value for num. 5 Repeat step 6 to 8 until num == 0 is satisfied. 6 Divide num by 2 and store the reminder and quotient into rem and num. 7 Multiply 10 to the already existing value of sum. 8 Add rem to the value of sum. 9 Display the value of sum. 10 Stop. Algorithm 20: Reverse of a given number. 4.3.2 Flowchart Figure 39: Reverse of a given number. 47
  • 49. 4.3.3 C Source Code #include<stdio .h> void main() { int num, rem, sum = 0; printf ( "Enter a integer number n" ) ; scanf ( "%d" , &num) ; while (num != 0){ rem = num % 10; sum = sum * 10 + rem; num = num / 10; } printf ( "The reverse no is : %d" , sum) ; } 4.3.4 Input and Output Figure 40: Reverse of the given number 12345. 48
  • 50. 4.4 Strong Number Write a C program to check whether the given number strong number or not. 4.4.1 Algorithm 1 Start 2 Declare six variables: i, j, fact, num, rem and sum. 3 Initialize sum to 0. 4 Get the decimal integer value for num. 5 Place num’s value into i. 6 Repeat step 7 to 13 until i == 0 is satisfied. 7 Divide i by 10 and store reminder and quotient in rem and i. 8 Initialize fact to 1. 9 Place rem’s value to j. 10 Repeat step 11 and 12 until j == 0 is satisfied. 11 Multiply j with current value of fact. 12 Decrement j by 1. 13 Add fact’s value to the current value of sum. 14 If sum is equal to num, then display "A strong number". 15 Else, display "Not a strong number". 16 Stop. Algorithm 21: Verify a number is a strong number or not. 49
  • 51. 4.4.2 Flowchart Figure 41: Verify a number is a strong number or not. 50
  • 52. 4.4.3 C Source Code #include<stdio .h> void main ( ) { int num, i , j , rem, fact , sum = 0; printf ( "Enter a integer number n" ) ; scanf ( "%d" , &num) ; for ( i = num; i != 0; i = i /10){ rem = i % 10; fact = 1; for ( j = rem; j != 0; j −−) fact = fact * j ; sum = sum + fact ; } i f (sum == num) printf ( "%d is a strong number" , num) ; else printf ( "%d is not a strong number" , num) ; } 4.4.4 Input and Output Figure 42: Verify 145 is a strong number or not. 51
  • 53. 4.5 Armstrong Number Write a C program to check whether the given number is an Armstrong number or not using the do ...while loop. 4.5.1 Algorithm 1 Start 2 Declare five variables: sum, num, temp and num_size. 3 Initialize sum to 0. 4 Get the values for num_size and num. 5 Place num value into temp. 6 Divide temp by 10 and store the reminder and quotient into rem and temp. 7 Compute remnum_size and add it to sum. 8 Repeat step 6 and 7 until temp == 0 is satisfied. 9 If num == sum then display "An Armstrong number". 10 Else, display "Not an Armstrong number". 11 Stop. Algorithm 22: Verify a number is an Armstrong number or not. 52
  • 54. 4.5.2 Flowchart Figure 43: Verify a number is an Armstrong number or not. 53
  • 55. 4.5.3 C Source Code #include<stdio .h> #include<math.h> void main ( ) { int num, temp, rem, size , sum = 0; printf ( "Enter the size of a number n" ) ; scanf ( "%d" , &size ) ; printf ( "Enter a integer number n" ) ; scanf ( "%d" , &num) ; temp = num; do{ rem = temp % 10; sum = sum + pow(rem, size ) ; temp = temp/10; } while (temp != 0); i f (num == sum) printf ( "%d is an Armstrong number" , num) ; else printf ( "%d is not an Armstrong number" , num) ; } 4.5.4 Input and Output Figure 44: Verify 1634 is an Armstrong number or not. 54
  • 56. 4.6 Fibonacci Series Write a program to generate Fibonacci series up to n number using do....while loop. 4.6.1 Algorithm 1 Start 2 Declare five variables: f1, f2, f3, cnt and steps. 3 Initialize f1 = 0, f2 = 1 and cnt = 0. 4 Read the step numbers into steps. 5 Display f1. 6 Add f1 with f2 and store the result into f3. 7 Place f2 value into f1. 8 Place f3 value into f2. 9 Increment cnt by 1. 10 Repeat step 5 to 9 till cnt <= steps is satisfied. 11 Stop. Algorithm 23: Fibonacci series up to n number using do....while loop. 55
  • 57. 4.6.2 Flowchart Figure 45: Fibonacci series up to step = steps. 56
  • 58. 4.6.3 C Source Code #include<stdio .h> void main() { int f1 = 0 , f2 = 1 , f3 , cnt = 0 , steps ; printf ( "Enter the no. of steps to print fibonacci series : " ) ; scanf ( "%d" , &steps ) ; do { printf ( "%d n" , f1 ) ; f3 = f1 + f2 ; f1 = f2 ; f2 = f3 ; cnt++; } while ( cnt < steps ) ; } 4.6.4 Input and Output Figure 46: Fibonacci series up to step 7. 57
  • 59. 4.7 Palindrome Number Write a C program to check whether the given number is Palindrome or not using the for loop. 4.7.1 Algorithm 1 Start 2 Declare four variables: sum, num, rem and i. 3 Initialize sum to 0. 4 Get the value for num. 5 Place num’s value into i. 6 Repeat step 7 to 9 till i is not equal to zero is satisfied. 7 Divide i by 10 and store reminder and quotient in rem and i. 8 Multiply 10 to the current value of sum. 9 Add rem’s value to the already existing value of sum. 10 If sum == num then display "A Palindrome". 11 Else, display "Not a palindrome". 12 Stop. Algorithm 24: Verify a number is a palindrome or not. 58
  • 60. 4.7.2 Flowchart Figure 47: Verify a number is a palindrome or not. 59
  • 61. 4.7.3 C Source Code #include<stdio .h> void main ( ) { int i , num, rem, sum = 0; printf ( "Enter an integer number n" ) ; scanf ( "%d" , & num) ; for ( i = num; i != 0; i = i /10){ rem = i % 10; sum = sum * 10 + rem; } i f (sum == num) printf ( "%d is a palindrome" , num) ; else printf ( "%d is not a palindrome" , num) ; } 4.7.4 Input and Output Figure 48: Verify 12321 is a palindrome or not. 60
  • 62. 4.8 Perfect Number Write a C program to check whether the given number is perfect or not using the for loop. 4.8.1 Algorithm 1 Start 2 Declare three variables: num, sum and i. 3 Initialize sum to 0. 4 Get the value for num. 5 Initialize i to 1. 6 Repeat step 7 and 8 till i is not equal to num satisfied. 7 If num is divisible by i, then add i’s value to sum. 8 Increment i by 1. 9 If sum == num then display "Perfect number". 10 Else, display "Not a Perfect number". 11 Stop. Algorithm 25: Verify a number is a perfect number or not. 61
  • 63. 4.8.2 Flowchart Figure 49: Verify a number is a perfect number or not. 62
  • 64. 4.8.3 C Source Code #include<stdio .h> void main ( ) { int i , num, sum = 0; printf ( "Enter a +ve integer number : " ) ; scanf ( "%d" , &num) ; for ( i = 1; i < num; i ++){ i f (num % i == 0) sum = sum + i ; } i f (sum == num) printf ( "%d is a perfect number" , num) ; else printf ( "%d is not a perfect number" , num) ; } 4.8.4 Input and Output Figure 50: Verify 28 is a perfect number or not. 63
  • 65. 4.9 Print Patterns Write a C program to print * in right angle and equilateral triangle patterns using Nested for loop. 4.9.1 Algorithm 1 Start 2 Declare three variables: size, i and j. 3 Get the value for size. 4 Initialize i to 1. 5 Repeat step 6 to 11 until i is greater than size satisfied. 6 Initialize j to 1. 7 Repeat step 8 and 9 until j is greater than i satisfied. 8 Display ’*’. 9 Increment j by 1. 10 Create new line by printing ’n’ escape sequence. 11 Increment i by 1. 12 Stop. Algorithm 26: * in right angle triangle pattern. 1 Start 2 Declare four variables: size, i, j and k. 3 Get the value for size, and Initialize i to 1. 4 Repeat step 5 to 12 until i is greater than size satisfied. 5 Initialize j to size-i. 6 Repeat step 7 until j is equal to 0 satisfied. 7 Print an empty space, and decrement j by 1. 8 Initialize k to 1. 9 Repeat step 12 and 13 until k is greater than i satisfied. 10 Display "* ", and increment k by 1. 11 Create new line by printing ’n’ escape sequence. 12 Increment i by 1. 13 Stop. Algorithm 27: * in equilateral triangle pattern. 64
  • 66. 4.9.2 Flowchart Figure 51: * in right angle triangle pattern. 65
  • 67. . Figure 52: * in equilateral triangle pattern. 66
  • 68. 4.9.3 C Source Code a . #include<stdio .h> void main() { int i , j , size ; printf ( "Enter size of the lateral : " ) ; scanf ( "%d" , &size ) ; for ( i = 1; i <= size ; i ++) { for ( j = 1; j <= i ; j ++) printf ( "*" ) ; printf ( "n" ) ; } } b. #include<stdio .h> void main() { int i , j , k , size ; printf ( "Enter size of the lateral : " ) ; scanf ( "%d" , &size ) ; for ( i = 1; i <= size ; i ++) { for ( j = size − i ; j != 0; j −−) printf ( " " ) ; for (k = 1; k <= i ; k++) printf ( "* " ) ; printf ( "n" ) ; } } 67
  • 69. 4.9.4 Input and Output Figure 53: * in right angle triangle pattern of size = 5. Figure 54: * in equilateral triangle pattern of size = 5. 68
  • 70. 4.10 Prime Numbers Write a program to print the prime numbers between 1 to n using nested for loop. 4.10.1 Algorithm 1 Start 2 Declare four variables: num, i, j and flag. 3 Get the value for num. 4 Initialize i to 2. 5 Repeat step 6 to 12 until i is greater than num satisfied. 6 Initialize flag to 0. 7 Initialize j to 2. 8 Repeat step 9 and 10 until j is equal to i satisfied. 9 If i is divisible by j, set flag to 1 and go to step 12. 10 Increment j by 1. 11 If flag is equal to zero, display i value. 12 Increment i by 1. 13 Stop. Algorithm 28: Prime numbers between 1 and n. 69
  • 71. 4.10.2 Flowchart Figure 55: Prime numbers between 1 and n. 70
  • 72. 4.10.3 C Source Code #include<stdio .h> void main ( ) { int i , j , num, flag ; printf ( "Enter the n value : " ) ; scanf ( "%d" , &num) ; for ( i = 2; i <= num; i ++){ flag = 0; for ( j = 2; j <= i −1; j ++){ i f ( i % j == 0){ flag = 1; break ; } } i f ( flag == 0) printf ( "%d " , i ) ; } } 4.10.4 Input and Output Figure 56: Prime numbers between 1 and 50. Objectives To have a clear idea on pretest and post-test loops. To understand basic loop initialization, validation and updation. To write programs using the while, for, or do...while loops. To understand the logic and adopt best looping construct for different kinds of problems. 71
  • 73. 5 WEEK Unconditional Control Transfer Statements 5.1 Calculator Application Write a C program to implement calculator application using switch...case...break. 5.1.1 Algorithm 1 Start 2 Take two numbers as input and store it in the variables a and b. 3 Take an input to let the user choose the operation that needs to be performed. 4 If choice is 1, then perform a+b and store it in c. go to step 10 5 If choice is 2, then perform a-b and store it in c. go to step 10 6 If choice is 3, then perform a*b and store it in c. go to step 10 7 If choice is 4, then perform a/b and store it in c. go to step 10 8 If choice is 5, then perform a%b and store it in c. go to step 10 9 Else, display "Invalid option", go to step 11. 10 Display the value of c. 11 Stop. Algorithm 29: Calculator application to perform arithmetic operations. 72
  • 74. 5.1.2 Flowchart Figure 57: Calculator application to perform arithmetic operations. 73
  • 75. 5.1.3 C Source Code #include<stdio .h> void main ( ) { int a , b, c , i ; printf ( "Enter two integer number : " ) ; scanf ( "%d %d" , &a , &b ) ; printf ( "Enter your choice : n" ) ; printf ( " [1] Addition n[2] Subtraction n" ) ; printf ( " [3] Multiplication n[4] Division n[5] Modulus n" ) ; scanf ( "%d" , &i ) ; switch ( i ) { case 1: c = a + b; printf ( "Addition : %d n" , c ) ; break ; case 2: c = a − b; printf ( "Subtraction : %d n" , c ) ; break ; case 3: c = a * b; printf ( " Multiplication : %d n" , c ) ; break ; case 4: c = a / b; printf ( "Division : %d n" , c ) ; break ; case 5: c = a % b; printf ( "Modulus : %d n" , c ) ; break ; default : printf ( " Invalid Option n" ) ; } } 5.1.4 Input and Output Figure 58: Calculator application to perform arithmetic operations. 74
  • 76. 5.2 Sum of N Natural Numbers Write a C program to find sum of 1 to n Natural numbers using goto statement. 5.2.1 Algorithm 1 Start 2 Declare three variables sum, n and i. 3 Get the value for n to add numbers from 1 to n. 4 Initialize sum to zero. 5 Initialize i to one. 6 Add i value to the current value of sum. 7 Increment i by 1. 8 if i is less than n, go to step 6, else go to next step. 9 Display the value of sum. 10 Stop. Algorithm 30: Sum of 1 to n Natural numbers. 5.2.2 Flowchart Figure 59: Sum of 1 to n Natural numbers. 75
  • 77. 5.2.3 C Source Code #include<stdio .h> void main ( ) { int i = 1 , n, sum = 0; printf ( "Enter the value of n : n" ) ; scanf ( "%d" , &n ) ; start : sum += i ; i ++; i f ( i <= n) goto start ; printf ( "The sum is : %d n" , sum) ; } 5.2.4 Input and Output Figure 60: Sum of 1 to 10 Natural numbers. 76
  • 78. 5.3 Even Numbers not Divisible by 6 and 8 Write a C program to print all the even numbers except the numbers, which are divisible by 6 and 8 using continue statement. 5.3.1 Algorithm 1 Start 2 Declare two variables n and i. 3 Get the value for n for printing even numbers between 1 and n. 4 Initialize i to zero. 5 Repeat step 5 to 8 until i is greater than n. 6 If is divisible by 6 and/or 8, go to step 8, else go to step 7. 7 Display the value of i. 8 Increment i by 2. 9 Stop. Algorithm 31: Even numbers up to n except the numbers divisible by 6 and 8. 5.3.2 Flowchart Figure 61: Even numbers up to n except the numbers divisible by 6 and 8. 77
  • 79. 5.3.3 C Source Code #include<stdio .h> void main ( ) { int n, i ; printf ( "Enter the value of n : n" ) ; scanf ( "%d" , &n ) ; for ( i = 0; i <= n; i +=2){ i f ( i%6 == 0 | | i%8 == 0) continue ; else printf ( "%d n" , i ) ; } } 5.3.4 Input and Output Figure 62: Even numbers up to 20 except the numbers divisible by 6 and 8. Objectives To understand the use of (break, continue, goto) unconditional control transfer statements in C programs. To understand the role of break and continue statements inside loop compound statements. To use the goto statement to transfer the control from one part to another part of a program. 78
  • 80. 6 WEEK Arrays and Their Applications 6.1 Minimum and Maximum Elements Write a C program to find maximum and minimum elements in the given array. 6.1.1 Algorithm 1 Start 2 Declare four variables min, max, i and an array arr. 3 Initialize i to 0. 4 Repeat step 5 and 6 until i is equal to size satisfied. 5 Get the value for arr[i]. 6 Increment i by 1. 7 Place arr[0] value in min and max. 8 Initialize i to 1. 9 Repeat step 10 and 11 until i is equal to size satisfied. 10 If arr[i] is greater than max then store arr[i]’s value in max. 11 If arr[i] is smaller than min then store arr[i]’s value in min. 12 Increment i by 1. 13 Display max’s and min’s values. 14 Stop. Algorithm 32: Maximum and minimum elements in an array. 79
  • 81. 6.1.2 Flowchart Figure 63: Maximum and minimum elements in an array. 80
  • 82. 6.1.3 C Source Code #include<stdio .h> void main() { int arr [7] , min, max, i ; printf ( "Enter the elements of an array : n" ) ; for ( i = 0; i < 7; i ++) scanf ( "%d" , &arr [ i ] ) ; min = max = arr [ 0 ] ; for ( i = 1; i < 7; i ++) { max = ( arr [ i ] > max)? arr [ i ] :max; min = ( arr [ i ] < min)? arr [ i ] : min; } printf ( "The maximum is : %d and the minimum is : %d n" , max, min) ; } 6.1.4 Input and Output Figure 64: Maximum and minimum elements in the given array. 81
  • 83. 6.2 Sorting of n numbers Write a C program to sort the elements is ascending order in the given array. 6.2.1 Algorithm 1 Start 2 Declare five variables min, temp, i, j and an array arr. 3 Initialize i to 0. 4 Repeat step 5 and 6 until i is equal to size satisfied. 5 Get the value for arr[i]. 6 Increment i by 1. 7 Reinitialize i to 0. 8 Repeat step 9 and 17 until i is equal to size-1 satisfied. 9 Assign i’s value to min. 10 Initialize j to i+1. 11 Repeat step 12 and 13 until j is equal to size satisfied. 12 If arr[j] is less than arr[min] then assign j to min. 13 Increment j by 1. 14 Store arr[i]’s value in temp. 15 Store arr[min]’s value in arr[i]. 16 Store temp’s value in arr[min]. 17 Increment i by 1. 18 Reinitialize i to 0. 19 Repeat step 20 until i is equal to size satisfied. 20 Display the value for arr[i]. 21 Stop. Algorithm 33: Sort elements of the given array using Selection sort. 82
  • 84. 6.2.2 Flowchart Figure 65: Sort elements of the given array using Selection sort. 83
  • 85. 6.2.3 C Source Code #include<stdio .h> void main ( ) { int arr [7] , min, temp, i , j ; printf ( "Enter the elements of an array : n" ) ; for ( i = 0; i < 7; i ++) scanf ( "%d" , &arr [ i ] ) ; / / Do the sorting [ selection sort ] for ( i = 0; i < 6; i ++){ min = i ; for ( j = i +1; j < 7; j ++) min = ( arr [ j ] < arr [min] ) ? j :min; temp = arr [ i ] ; arr [ i ] = arr [min ] ; arr [min] = temp; } printf ( "the elements after the sorting : n" ) ; for ( i = 0; i < 7; i ++) printf ( "%d t " , arr [ i ] ) ; } 6.2.4 Input and Output Figure 66: Elements of the given array after sorting. 84
  • 86. 6.3 Searching Write a C program to search an element in the given array. 6.3.1 Algorithm 1 Start 2 Declare five variables: i, num, index, flag and an array arr. 3 Store {a1, a2, a3, ..., aN} in arr. 4 Initialize flag and i to 0. 5 Get the value for num. 6 Repeat step 7 to 9 until i is equal to N satisfied. 7 If arr[i] is equal to num, then set flag to 1. 8 Assign i’s value to index go to step 11. 9 Increment i by 1. 10 If flag is one, display index’s value. 11 Else, display "Element is not present". 12 Stop. Algorithm 34: Search an element in an array using linear search. 85
  • 87. 6.3.2 Flowchart Figure 67: Search an element in an array using linear search. 86
  • 88. 6.3.3 C Source Code #include<stdio .h> #include<stdbool .h> void main() { int i , num, index , arr [7] = {9 , 8 , 3 , 6 , 7 , 10 , 2}; bool flag = 0; printf ( "Enter the element to be searched : n" ) ; scanf ( "%d" , &num) ; for ( i = 0; i < 7; i ++) { i f ( arr [ i ] == num) { flag = 1; index = i ; break ; } } i f ( flag ) printf ( "Element is found at %dth location . n" , index ) ; else printf ( "Element is not present in the array . n" ) ; } 6.3.4 Input and Output Figure 68: Search an element 3 in the given array. 87
  • 89. 6.4 Insertion Write a C program to insert an element at a specified location in an array. 6.4.1 Algorithm 1 Start 2 Declare five variables: num, pos, i, last_index and an array arr of size 10. 3 Initialize i to 0. 4 Repeat step 5 and 6 until i is equal to 6 satisfied. 5 Get the value for arr[i]. 6 Increment i by 1. 7 Initialize last_index to i-1. 8 Read values for num and pos. 9 If pos < 0 or pos > 9, then display "Not possible". 10 If pos > 6, assign num and i’s values to arr[i] and last_index, go to step 16. 11 Else, initialize j to i. 12 Repeat step 13 and 14 until j is equal to pos satisfied. 13 Assign arr[j-1]’s value to arr[j]. 14 Decrement j by 1. 15 Assign num’s value to arr[pos] and i’s value to last_index. 16 Reinitialize j to 0. 17 Repeat step 18 and 19 until j is equal to last_index. 18 Display the value of arr[j]. 19 Increment j by 1. 20 Stop. Algorithm 35: Insert a number at a given location in an array. 88
  • 90. 6.4.2 Flowchart Figure 69: Insert a number at a given location in an array. 89
  • 91. 6.4.3 C Source Code #include<stdio .h> void main ( ) { int arr [10] , num, pos , i , last_index ; printf ( "Enter the elements of an array : n" ) ; for ( i = 0; i < 7; i ++) scanf ( "%d" , &arr [ i ] ) ; last_index = i −1; printf ( "Enter the element and i t s position : n" ) ; scanf ( "%d %d" , &num, &pos ) ; i f (pos < 0 | | pos > 9) printf ( " Insertion is not possible n" ) ; else i f (pos > 6){ arr [ i ] = num; last_index = i ; } else { for ( int j = i ; j != pos ; j −−) arr [ j ] = arr [ j −1]; arr [pos] = num; last_index = i ; } printf ( " Print the updated array : n" ) ; for ( int j = 0; j <= last_index ; j ++) printf ( "%d t " , arr [ j ] ) ; } 6.4.4 Input and Output Figure 70: Insert 4 at 3rd location in the given array. 90
  • 92. 6.5 Remove Duplicate Write a C program to remove duplicate elements from the given array. 6.5.1 Algorithm 1 Start 2 Declare six variables:i, j, final_index, array A, array B and array flag. 3 Initialize final_index to 0 and flag[size] = {0}. 4 Initialize i to 0. 5 Repeat step 6 and 7 until i is equal to size satisfied. 6 Read value for A[i]. 7 Increment i by 1. 8 Reinitialize i to 0. 9 Repeat step 10 to 17 until i is equal to size satisfied. 10 if flag == 0, go to next step else go to step 17. 11 Store A[i]’s value in B[final_index]. 12 Increment final_index by 1. 13 Initialize j to i+1. 14 Repeat step 15 and 16 until j is equal to size satisfied. 15 If A[i] is equal to A[j], then store 1 in flag[j]. 16 Increment j by 1. 17 Increment i by 1. 18 Reinitialize i to 0. 19 Repeat 20 and 21 until i is equal to final_index satisfied. 20 Display the value of B[i]. 21 Increment i by 1. 22 Stop Algorithm 36: Remove duplicate elements from an array. 91
  • 93. 6.5.2 Flowchart Figure 71: Remove duplicate elements from an array. 92
  • 94. 6.5.3 C Source Code #include<stdio .h> void main ( ) { int i , j , A[10] , B[10] , final_index = 0 , flag [10]={0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0}; printf ( "Enter the elements for array A : n" ) ; for ( i = 0; i <= 9; i ++) scanf ( "%d" , &A[ i ] ) ; printf ( "A : " ) ; for ( i = 0; i <= 9; i ++) printf ( "%d t " , A[ i ] ) ; printf ( "n" ) ; / / remove duplicate elements for ( i = 0; i <= 9; i ++){ i f ( flag [ i ] == 0){ B[ final_index ] = A[ i ] ; final_index ++; for ( j = i +1; j <= 9; j ++){ i f (A[ i ] == A[ j ] ) flag [ j ] = 1; } } } / / print the output array printf ( "B : " ) ; for ( i = 0; i < final_index ; i ++) printf ( "%d t " , B[ i ] ) ; } 6.5.4 Input and Output Figure 72: Array elements before, and its elements after removal of duplicates. 93
  • 95. 6.6 Matrix Addition Write a C program to find the sum of two matrices. 6.6.1 Algorithm 1 Start 2 Declare five variables: i, j, array A, array B and array C. 3 Initialize i to 0. 4 Repeat step 5 to 10 until i is equal to size satisfied. 5 Initialize j to 0. 6 Repeat step 7 to 9 until j is equal to size satisfied. 7 Read the value for A[i][j]. 8 Read the value for B[i][j]. 9 Increment j by 1. 10 Increment i by 1. 11 Reinitialize i to 0. 12 Repeat step 13 to 17 until i is equal to size satisfied. 13 Reinitialize j to 0. 14 Repeat step 15 and 16 until j is equal to size satisfied. 15 Add A[i][j]’s value with B[i][j]’s value and store the result in C[i][j]. 16 Increment j by 1. 17 Increment i by 1. 18 Reinitialize i to 0. 19 Repeat step 20 to 24 until i is equal to size satisfied. 20 Reinitialize j to 0. 21 Repeat step 22 and 23 until j is equal to size satisfied. 22 Display the value of C[i][j]. 23 Increment j by 1. 24 Increment i by 1. 25 Stop Algorithm 37: Summation of two size * size matrices. 94
  • 96. 6.6.2 Flowchart Figure 73: Summation of two size * size matrices. 95
  • 97. 6.6.3 C Source Code #include<stdio .h> void main ( ) { int i , j , A[ 3 ] [ 3 ] , B[ 3 ] [ 3 ] , C[ 3 ] [ 3 ] ; printf ( "Enter the elements for array A n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++){ printf ( "n[%d][%d] element of A is : " , i , j ) ; scanf ( "%d" , &A[ i ] [ j ] ) ; } } printf ( "Enter the elements for array B n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++){ printf ( "n[%d][%d] element of B is : " , i , j ) ; scanf ( "%d" , &B[ i ] [ j ] ) ; } } printf ( "A : n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++) printf ( "%d t " , A[ i ] [ j ] ) ; printf ( "n" ) ; } printf ( "B : n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++) printf ( "%d t " , B[ i ] [ j ] ) ; printf ( "n" ) ; } / / perform matrix addition operation for ( i = 0; i <= 2; i ++){ for ( j = 0; j <= 2; j ++){ C[ i ] [ j ] = A[ i ] [ j ] + B[ i ] [ j ] ; } } / / final output matrix printf ( "C : n" ) ; for ( i = 0; i <= 2; i ++){ for ( j = 0; j <= 2; j ++) printf ( "%d t " , C[ i ] [ j ] ) ; printf ( "n" ) ; } } 96
  • 98. 6.6.4 Input and Output Figure 74: Summation of two 3*3 matrices. 97
  • 99. 6.7 Matrix Multiplication Write a C program to perform matrix multiplication between two matrices. 6.7.1 Algorithm 1 Start 2 Declare seven variables: i, j, k, sum, array A, array B and array C. 3 Initialize i to 0. 4 Repeat step 5 to 10 until i is equal to size satisfied. 5 Initialize j to 0. 6 Repeat step 7 to 9 until j is equal to size satisfied. 7 Read the value for A[i][j]. 8 Read the value for B[i][j]. 9 Increment j by 1. 10 Increment i by 1. 11 Reinitialize i to 0. 12 Repeat step 13 to 21 until i is equal to size satisfied. 13 Reinitialize j to 0. 14 Repeat step 15 to 20 until j is equal to size satisfied. 15 Initialize sum and k to 0. 16 Repeat step 17 and 18 until k is equal to size satisfied. 17 Multiply A[i][k] with B[k][j] and add it to the current of value of sum. 18 Increment k by 1. 19 Store sum’s value in C[i][j]. 20 Increment j by 1. 21 Increment i by 1. 22 Reinitialize i to 0. 23 Repeat step 24 to 28 until i is equal to size satisfied. 24 Reinitialize j to 0. 25 Repeat step 26 and 27 until j is equal to size satisfied. 26 Display the value of C[i][j]. 27 Increment j by 1. 28 Increment i by 1. 29 Stop Algorithm 38: Multiplication of two size*size matrices. 98
  • 100. 6.7.2 Flowchart Figure 75: Multiplication of two size*size matrices. 99
  • 101. 6.7.3 C Source Code #include<stdio .h> void main() { int i , j , k , A[ 3 ] [ 3 ] , B[ 3 ] [ 3 ] , C[ 3 ] [ 3 ] , sum; printf ( "Enter the elements for array A n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++){ printf ( "n[%d][%d] element of A is : " , i , j ) ; scanf ( "%d" , &A[ i ] [ j ] ) ; } } printf ( "Enter the elements for array B n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++){ printf ( "n[%d][%d] element of B is : " , i , j ) ; scanf ( "%d" , &B[ i ] [ j ] ) ; } } printf ( "A : n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++) printf ( "%d t " , A[ i ] [ j ] ) ; printf ( "n" ) ; } printf ( "B : n" ) ; for ( i = 0; i <= 2; i ++){ for ( j =0; j <=2; j ++) printf ( "%d t " , B[ i ] [ j ] ) ; printf ( "n" ) ; } / / matrix multiplication operation for ( i = 0; i <= 2; i ++){ for ( j = 0; j <= 2; j ++){ sum = 0; for (k = 0; k <=2; k++) sum = sum + A[ i ] [ k] * B[k ] [ j ] ; C[ i ] [ j ] = sum; } } / / final output matrix printf ( "C : n" ) ; for ( i = 0; i <= 2; i ++){ for ( j = 0; j <= 2; j ++) printf ( "%d t " , C[ i ] [ j ] ) ; 100
  • 102. printf ( "n" ) ; } } 6.7.4 Input and Output Figure 76: Multiplication of two 3*3 matrices. 101
  • 103. 6.8 Matrix Transpose Write a C program to find the transpose of a matrix. 6.8.1 Algorithm 1 Start 2 Declare four variables: i, j, array A and array B. 3 Initialize i to 0. 4 Repeat step 5 to 9 until i is equal to size satisfied. 5 Initialize j to 0. 6 Repeat step 7 and 8 until j is equal to size satisfied. 7 Read the value for A[i][j]. 8 Increment j by 1. 9 Increment i by 1. 10 Reinitialize i to 0. 11 Repeat step 12 to 18 until i is equal to size satisfied. 12 Reinitialize j to 0. 13 Repeat step 14 and 15 until j is equal to size satisfied. 14 Place A[j][i]’s value in B[i][j]. 15 Increment j by 1. 16 Increment i by 1. 17 Reinitialize i to 0. 18 Repeat step 19 to 23 until i is equal to size satisfied. 19 Initialize j to 0. 20 Repeat step 21 and 22 until j is equal to size satisfied. 21 Display the value B[i][j]. 22 Increment j by 1. 23 Increment i by 1. 24 Stop Algorithm 39: Transpose of a size*size matrix. 102
  • 104. 6.8.2 Flowchart Figure 77: Transpose of a size*size matrix. 103
  • 105. 6.8.3 C Source Code #include<stdio .h> void main() { int i , j , A[ 3 ] [ 3 ] , B[ 3 ] [ 3 ] ; printf ( "Enter the elements for array A n" ) ; for ( i = 0; i <= 2; i ++) { for ( j =0; j <= 2; j ++) { printf ( "n[%d][%d] element of A is : " , i , j ) ; scanf ( "%d" , &A[ i ] [ j ] ) ; } } printf ( "A : n" ) ; for ( i = 0; i <= 2; i ++) { for ( j = 0; j <= 2; j ++) printf ( "%d t " , A[ i ] [ j ] ) ; printf ( "n" ) ; } / / Transpose of matrix for ( i = 0; i <= 2; i ++){ for ( j =0; j <= 2; j ++) B[ i ] [ j ] = A[ j ] [ i ] ; } / / Output matrix printf ( "B : n" ) ; for ( i = 0; i <= 2; i ++) { for ( j = 0; j <= 2; j ++) printf ( "%d t " , B[ i ] [ j ] ) ; printf ( "n" ) ; } } 104
  • 106. 6.8.4 Input and Output Figure 78: Transpose of a 3*3 matrix. Objectives To utilize one dimensional and multi-dimensional arrays to solve problems that use set(s) of similar type input data. To have a clear idea on passing an complete array or array element as an argument to a function. To write programs that perform multiple classical operations like searching, sorting, updation, or deletion on array elements. 105
  • 107. 7 WEEK Strings, String I/O and Manipulation Functions 7.1 String Length Write a C program to find length of a string with and without using string handling functions. 7.1.1 Algorithm 1 Start 2 Declare two variables: size and an array str. 3 Read the string into str. 4 Call the string length function strlen(str) and assign length to size. 5 Display the value of size. 6 Stop Algorithm 40: Length of a string using string handling functions. 1 Start 2 Declare three variables: i, cnt and an array str. 3 Initialize the values of cnt and i to 0. 4 Read the string into str. 5 Repeat the step 6 and 7 until str[i] != ’0’ is satisfied. 6 Increment the value of cnt by 1. 7 Increment the value of i by 1. 8 Display the value of cnt that is the length of the string. 9 Stop Algorithm 41: Length of a string without using string handling functions. 106
  • 108. 7.1.2 Flowchart Figure 79: Length of a string using string handling functions. Figure 80: Length of a string without using string handling functions. 107
  • 109. 7.1.3 C Source Code a . #include<stdio .h> #include<string .h> void main() { char str [30]; printf ( "enter the string value n" ) ; gets ( str ) ; printf ( "The size of the ’%s ’ is : %lu n" , str , strlen ( str ) ) ; } b. #include<stdio .h> void main() { char str [30]; int cnt = 0; printf ( "enter the string value : n" ) ; gets ( str ) ; / / Count the size of the string while ( str [ cnt ] != ’ 0 ’ ) cnt++; printf ( "The size of the ’%s ’ is : %d n" , str , cnt ) ; } 7.1.4 Input and Output Figure 81: Length of "S&H, VRSEC, Vijayawada" using string handling functions. Figure 82: Length of "VRSEC, Vijayawada" without using string handling functions. 108
  • 110. 7.2 Reverse a String Write a C program to reverse a string with and without using string handling functions. 7.2.1 Algorithm 1 Start 2 Declare an array str and read the string into it. 3 Call the string reverse function strrev(str) and result is stored in str. 4 Display the value of str. 5 Stop Algorithm 42: Reverse a string using string handling function. 1 Start 2 Declare four variables: i, cnt, character arrays str and revstr. 3 Initialize the value of cnt to 0. 4 Read the string into str. 5 Repeat the step 6 until str[cnt]!=’0’ is satisfied. 6 Increment the value of cnt by 1. 7 Initialize the value of i to 0. 8 Repeat the step 9 and 10 till i < cnt is satisfied. 9 Place str[cnt-1-i]’s value in revstr[i]. 10 Increment the value of i by 1. 11 Store ’0’ in revstr[i]. 12 Display the value of str. 13 Stop Algorithm 43: Reverse a string without using string handling function. 7.2.2 Flowchart Figure 83: Reverse a string using string handling function. 109
  • 111. . Figure 84: Reverse a string without using string handling function. 110
  • 112. 7.2.3 C Source Code a . #include<stdio .h> #include<string .h> void main ( ) { char str [30]; printf ( "enter the string value n" ) ; gets ( str ) ; printf ( "Reverse of ’%s ’ is ’%s ’ " , str , strrev ( str ) ) ; } b. #include<stdio .h> void main ( ) { char str [30] , revstr [30]; int i , cnt = 0; printf ( "enter the string value n" ) ; gets ( str ) ; / / Count the size of the string while ( str [ cnt ] != ’ 0 ’ ) cnt++; / / Store the string in reverse order for ( i = 0; i < cnt ; i ++) revstr [ i ] = str [ cnt−1− i ] ; revstr [ i ] = ’ 0 ’ ; printf ( "The reverse of ’%s ’ is ’%s ’ n" , str , revstr ) ; } 7.2.4 Input and Output Figure 85: Reverse a "S&H, VRSE, Vijayawada" using string handling function. Figure 86: Reverse "VRSEC, Vijayawada" without using string handling function. 111
  • 113. 7.3 String Concatenation Write a C program to concatenate two strings with and without using string handling functions. 7.3.1 Algorithm 1 Start 2 Declare two array variables: str1 and str2. 3 Read two strings into str1 and str2. 4 Call the string concatenation function strcat(str1, str2), it concatenates str2 to str1. 5 Display the value of str1. 6 Stop Algorithm 44: String concatenation using string handling function. 1 Start 2 Declare six variables: cnt1, cnt2, cnt3, array str1, array str2 and array str3. 3 Initialize the values of cnt1, cnt2 and cnt3 to 0. 4 Read two strings into str1 and str2. 5 Repeat the step 6 and 7 until str1[cnt1]!=’0’ is satisfied. 6 Place str1[cnt1]’s value in str3[cnt3]. 7 Increment the values of cnt1 and cnt3 by 1. 8 Repeat the step 9 and 10 until str2[cnt2]!=’0’ is satisfied. 9 Place str2[cnt2]’s value in str3[cnt3]. 10 Increment the values of cnt2 and cnt3 by 1. 11 Store ’0’ in str3[cnt3]. 12 Display the value of str3. 13 Stop Algorithm 45: String concatenation without using string handling function. 7.3.2 Flowchart Figure 87: String concatenation using string handling function. 112
  • 114. . Figure 88: String concatenation without using string handling function. 113
  • 115. 7.3.3 C Source Code a . #include<stdio .h> #include<string .h> void main() { char str1 [30] , str2 [30]; printf ( "enter the string value for str1 : n" ) ; gets ( str1 ) ; printf ( "enter the string value for str2 : n" ) ; gets ( str2 ) ; printf ( "The str1+str2 is ’%s ’n" , strcat ( str1 , str2 ) ) ; } b. #include<stdio .h> #include<string .h> void main() { char str1 [30] , str2 [30] , str3 [60]; int cnt1 = 0 , cnt2 = 0 , cnt3 = 0; printf ( "enter the string value for str1 : n" ) ; gets ( str1 ) ; printf ( "enter the string value for str2 : n" ) ; gets ( str2 ) ; while ( str1 [ cnt1 ] != ’ 0 ’ ) { str3 [ cnt3 ] = str1 [ cnt1 ] ; cnt1++; cnt3++; } while ( str2 [ cnt2 ] != ’ 0 ’ ) { str3 [ cnt3 ] = str2 [ cnt2 ] ; cnt2++; cnt3++; } str3 [ cnt3 ] = ’ 0 ’ ; printf ( "The str1+str2 is ’%s ’n" , str3 ) ; } 114
  • 116. 7.3.4 Input and Output Figure 89: Concatenation of "S&H, VRSEC," and "Vijayawada" using string handling function. Figure 90: Concatenation of "S&H, VRSEC" and "Vijayawada" without using string handling function. 115
  • 117. 7.4 String Comparison Write a C program to compare two strings with and without using string handling functions. 7.4.1 Algorithm 1 Start 2 Declare three variables: n, array str1 and array str2. 3 Read two strings into str1 and str2. 4 Call the string comparison function strcmp(str1, str2) and store the return value in n. 5 Display the value of n. 6 Stop Algorithm 46: String comparison using string handling function. 1 Start 2 Declare six variables: cnt1, cnt2, i, flag and array str1 and array str2. 3 Initialize the values of cnt1 and cnt2 to 0. 4 Initialize the value of flag to 1. 5 Read two strings into str1 and str2. 6 Repeat the step 7 until str1[cnt1]!=’0’ is satisfied. 7 Increment the value of cnt1 by 1. 8 Repeat the step 9 until str2[cnt2]!=’0’ is satisfied. 9 Increment the value of cnt1 by 1. 10 If cnt1 is not equal to cnt2, then go to step 14. 11 Initialize the value of i to 0. 12 Repeat the step 13 to 15 till i < cnt1 is satisfied. 13 If str1[i]!=str2[i], go to next step, else go to 15. 14 Store zero in flag, go to step 16. 15 Increment i by 1. 16 If flag is 1, display ’Both the strings are equal’. 17 Else, display ’Both the strings are different’. 18 Stop Algorithm 47: String comparison without using string handling function. 116
  • 118. 7.4.2 Flowchart Figure 91: String comparison using string handling function. 117
  • 119. . Figure 92: String comparison without using string handling function. 118
  • 120. 7.4.3 C Source Code a . #include<stdio .h> #include<string .h> void main ( ) { char str1 [30] , str2 [30]; int cnt1 = 0 , cnt2 = 0; int i , flag = 1; printf ( "enter the string value for str1 : n" ) ; gets ( str1 ) ; printf ( "enter the string value for str2 : n" ) ; gets ( str2 ) ; while ( str1 [ cnt1 ] != ’ 0 ’ ) cnt1++; while ( str2 [ cnt2 ] != ’ 0 ’ ) cnt2++; i f ( cnt1 != cnt2 ) flag = 0; else { for ( i = 0; i < cnt1 ; i ++){ i f ( str1 [ i ] != str2 [ i ] ) { flag = 0; break ; } } } i f ( flag ) printf ( "Both the strings are equal . n" ) ; else printf ( "Both the strings are different . n" ) ; } b. #include<stdio .h> #include<string .h> void main ( ) { char str1 [30] , str2 [30]; printf ( "enter the string value for str1 : n" ) ; gets ( str1 ) ; printf ( "enter the string value for str2 : n" ) ; gets ( str2 ) ; i f ( ! strcmp( str1 , str2 )) printf ( "Both the strings are equal . n" ) ; else printf ( "Both the strings are different . n" ) ; } 119
  • 121. 7.4.4 Input and Output Figure 93: Compare "VRSEC" and "vrsec" without using string handling function. Figure 94: Compare "VRSEC" and "VRsec" using string handling function. Objectives To write programs that work on read, write and manipulate fixed length and variable-length strings and/or arrays of strings. To write programs that use predefined string I/O functions. To write programs that use string manipulation functions from the string library. 120
  • 122. 8 WEEK Concepts of User Defined Functions 8.1 Swap Two Numbers Write a C program to swap two numbers using call by value and call by reference. 8.1.1 Algorithm 1 Start 2 Declare two variables: a and b. 3 Read the value for a and b. 4 Call swap(a, b) function. 5 Stop 1 function swap(a, b) 2 Declare a variable temp. 3 Place a’s value in temp. 4 Place b’s value in a. 5 Place temp’s value in b. 6 Display a’s and b’s values. Algorithm 48: Swap two numbers using call by values. 121
  • 123. 1 Start 2 Declare two variables: a and b. 3 Read the values for a and b. 4 Call swap(&a, &b) function, where &a and &b are addresses of a and b variables. 5 Display a’s and b’s values. 6 Stop 1 function swap(*a, *b) 2 Declare a variable temp. 3 Place *a’s value in temp, where a is a pointer variable 4 Place *b’s value in *a, where b is a pointer variable 5 Place temp’s value in *b. Algorithm 49: Swap two numbers using call by reference. 8.1.2 Flowchart Figure 95: Swap two numbers using call by values. 122
  • 124. . Figure 96: Swap two numbers using call by reference. 123
  • 125. 8.1.3 C Source Code a . #include<stdio .h> void swap( int a , int b ) ; void main() { int a , b; printf ( "Enter the value of a and b : n" ) ; scanf ( "%d %d" , &a , &b ) ; swap(a , b ) ; } void swap( int a , int b) { int temp; temp = a ; a = b; b = temp; printf ( "The a and b values after swapping are %d and %d n" , a , b ) ; } b. #include<stdio .h> void swap( int * a , int * b ) ; void main() { int a , b; printf ( "Enter the value of a and b : n" ) ; scanf ( "%d %d" , &a , &b ) ; swap(&a , &b ) ; printf ( "The a and b values after swapping are %d and %d. n" , a , b ) ; } void swap( int * a , int * b) { int temp; temp = *a ; *a = *b; *b = temp; } 124
  • 126. 8.1.4 Input and Output Figure 97: Swap 5 and 3 using call by values. Figure 98: Swap two numbers using call by reference. 125
  • 127. 8.2 Factorial of a Number Write a C program to find the factorial of the given number using and without using recursion. 8.2.1 Algorithm 1 Start 2 Declare a variable n. 3 Read the value for n. 4 Call factorial(n). 5 Display the return value of factorial(n). 6 Stop 1 function factorial(n) 2 If n == 1 then return 1. 3 Else, return n*factorial(n-1). Algorithm 50: factorial of a +ve number using recursion. 1 Start 2 Declare a variable n. 3 Read the value for n. 4 Call factorial(n). 5 Display the return value of factorial(n). 6 Stop 1 function factorial(n) 2 Declare variables i and mult. 3 Initialize mult to 1. 4 Initialize i to n. 5 Repeat step 6 and 7 till i>0 is satisfied. 6 Multiply i value to current value of mult. 7 Decrement i value by 1. 8 Return mult’s value. Algorithm 51: factorial of a +ve number without using recursion. 126
  • 128. 8.2.2 Flowchart Figure 99: factorial of a +ve number using recursion. 127
  • 129. . Figure 100: factorial of a +ve number without using recursion. 128
  • 130. 8.2.3 C Source Code a . #include<stdio .h> int fact ( int n ) ; void main() { int n; printf ( "Enter an +ve integer number : n" ) ; scanf ( "%d" , &n ) ; printf ( "The factorial of %d is : %d. n" , n, fact (n ) ) ; } int fact ( int n) { int i , mult = 1; for ( i = n; i > 0; i −−) mult = mult * i ; return mult ; } b. #include<stdio .h> int fact ( int n ) ; void main() { int n; printf ( "Enter an +ve integer number : n" ) ; scanf ( "%d" , &n ) ; printf ( "The factorial of %d is : %d. n" , n, fact (n ) ) ; } int fact ( int n) { i f (n == 1) return 1; else return n * fact (n−1); } 129
  • 131. 8.2.4 Input and Output Figure 101: factorial of 6 without using recursion. Figure 102: factorial of 5 using recursion. 130
  • 132. 8.3 Combination Write a C program to find n Cr using functions. 8.3.1 Algorithm 1 Start 2 Declare two variables n and r. 3 Read the value for n and r. 4 If n >= r then call nCr(n, r) function. 5 Display the return value of nCr(n, r). 6 Stop 1 function nCr(n, r) 2 Call fact(n), fact(r) and fact(n-r) functions. 3 Divide return value of fact(n) by product of fact(r)’s and fact(n-r)’s return values. 4 Return the result. 1 function fact(n) 2 If n == 1 then return 1. 3 Else return n*fact(n-1). Algorithm 52: Compute nCr for given n and r. 131
  • 133. 8.3.2 Flowchart Figure 103: Compute nCr for given n and r. 132
  • 134. 8.3.3 C Source Code #include<stdio .h> int nCr( int n, int r ) ; int fact ( int n ) ; void main() { int n, r ; printf ( "Enter the value of n and r : n" ) ; scanf ( "%d %d" , &n, &r ) ; i f (n >= r ) printf ( "The nCr is %d. n" , nCr(n, r ) ) ; else printf ( "You have entered wrong values . n" ) ; } int nCr( int n, int r ) { return fact (n)/( fact ( r ) * fact (n−r ) ) ; } int fact ( int n) { i f (n==1) return 1; else return n * fact (n−1); } 8.3.4 Input and Output Figure 104: Compute nCr for n = 6 and r = 2. 133
  • 135. 8.4 Mean and Standard Deviation Write a C program to find mean and standard deviation of a given set of numbers. (Define func- tions for mean and standard deviation). 8.4.1 Algorithm 1 Start 2 Declare three variables: i, mn and arr[N], where N is a constant. 3 Initialize i to 1. 4 Repeat step 5 until i is equal to N satisfied. 5 Get the value for arr[i], i is the current index position in arr. 6 Call mean (arr, N) function and store the return value in mn. 7 Display mn’s and mean’s values of the given N numbers. 8 Call stddev (arr, mn, N) and display its return value. 9 Stop 1 function mean (*arr, n) 2 Declare two variables: i and mn. 3 Initialize m to 0.0 and i to 0. 4 Repeat step 5 till i<n is satisfied. 5 Add arr[i]’s value to the current value of m. 6 Divide mn by n and store the value into mn. 7 Return mn. 1 function stddev (*arr, mn, n) 2 Declare two variables: i and dev. 3 Initialize dev to 0.0 and i to 0. 4 Repeat step 5 and 6 till i<n is satisfied. 5 Calculate square of the difference between arr[i] and mn. 6 Add result to the current value of dev. 7 Divide dev by n and store square root of the resulted value in dev. 8 Return dev’s value. Algorithm 53: Mean and standard deviation of a set of numbers. 134
  • 136. 8.4.2 Flowchart Figure 105: Mean and standard deviation of a set of numbers. 135
  • 137. 8.4.3 C Source Code #include<stdio .h> #include<math.h> #define N 7 float mean( float * arr , int n ) ; float stddev ( float * arr , float mn, int n ) ; void main() { int i ; float mn, arr [N] ; printf ( "Enter the value of the array : n" ) ; for ( i = 0; i < N; i ++){ scanf ( "%f " , &arr [ i ] ) ; } mn = mean(&arr [0] , N) ; printf ( "mean value of arr is %f . n" , mn) ; printf ( "stddev of arr is %f . n" , stddev(&arr [0] , mn, N) ) ; } float mean( float * arr , int n) { int i ; float mn = 0.0; for ( i = 0; i < n; i ++) mn = mn + *( arr+i ) ; mn /= n; return mn; } float stddev ( float * arr , float mn, int n) { int i ; float dev = 0.0; for ( i = 0; i < n; i ++) dev = dev + pow( * ( arr+i )−mn, 2); dev = sqrt (dev/n ) ; return dev ; } 136
  • 138. 8.4.4 Input and Output Figure 106: Mean and standard deviation of the given set of numbers. Objectives Have a clear idea on function declaration, call, and definition. To write a program using more than one function with or without parameters and function re- turn type. To understand the global and local scope, and implement inter function communication for various problems. 137
  • 139. 9 WEEK Pointers and Their Applications 9.1 Arithmetic Operations Write a C program to implement arithmetic operations on integers using pointers. 9.1.1 Algorithm 1 Start 2 Declare two variables (a and b) and two pointer variables (p and q). 3 Get the integer values for a and b. 4 Assign the address of a to pointer p. 5 Assign the address of b to pointer q. 6 Add the dereferenced values of p and q and display the result. 7 Subtract q’s dereferenced value from p’s dereferenced value and display the result. 8 Multiply the dereferenced values of p and q and display the result. 9 Divide p’s derefrenced value by q’s derefrenced value and display the result. 10 Stop. Algorithm 54: Arithmetic operations on integers using pointers. 138
  • 140. 9.1.2 Flowchart Figure 107: Arithmetic operations on integers using pointers. 139
  • 141. 9.1.3 C Source Code #include<stdio .h> void main ( ) { int a , b; int *p = &a , *q = &b; printf ( "Enter the value of a and b : n" ) ; scanf ( "%d %d" , p, q ) ; printf ( "%d + %d is %d n" , *p, *q, *p + *q ) ; printf ( "%d − %d is %d n" , *p, *q, *p − *q ) ; printf ( "%d * %d is %d n" , *p, *q, *p * *q ) ; printf ( "%d / %d is %d n" , *p, *q, *p / *q ) ; } 9.1.4 Input and Output Figure 108: Arithmetic operations on 5 and 3 using pointers. 140
  • 142. 9.2 String Sorting Write a C program to sort names in ascending order using functions and pointers. 9.2.1 Algorithm 1 Start 2 Declare two variables: i and a 2D character array name. 3 Initialize i to 0. 4 Repeat step 5 until i is equal to size satisfied, where size is a constant. 5 Get the value for name[i]. 6 Call sort(name) function. 7 Reinitialize i to 0. 8 Repeat step 9 until i is equal to size satisfied, where size is a constant. 9 Display name[i]’s value. 10 Stop. 1 function sort(*name) 2 Declare a character array temp. 3 Declare three variables i, j and min. 4 Initialize i to 0. 5 Repeat step 6 to 12 until i == size is satisfied. 6 Place the i’s value in min. 7 Initialize j to i+1. 8 Repeat step 9 until j == size is satisfied. 9 If name[min] is greater than name[j], then min = j. 10 Assign name[i]’s value to temp. 11 Assign name[min]’s value to name[i]. 12 Assign temp’s value to name[min]. Algorithm 55: Sort names in ascending order using functions and pointers. 141
  • 143. 9.2.2 Flowchart Figure 109: Sort names in ascending order using functions and pointers. 142
  • 144. 9.2.3 C Source Code #include<stdio .h> #include<string .h> #define size 7 void sort (char *name) ; void main() { int i ; char name[ size ] [ 2 0 ] ; printf ( "Enter the input : n" ) ; for ( i = 0; i < size ; i ++) gets(&name[ i ] ) ; printf ( " print the array before sorting : n" ) ; for ( i = 0; i < size ; i ++) printf ( "%s n" , name[ i ] ) ; sort(&name[ 0 ] [ 0 ] ) ; printf ( " print the array after sorting : n" ) ; for ( i = 0; i < size ; i ++) printf ( "%s n" , name[ i ] ) ; } void sort (char *name) { char temp[20]; int i , j , min; for ( i = 0; i < size ; i ++) { min = i ; for ( j = i +1; j < size ; j ++) { i f (strcmp(name[min] , name[ j ] ) > 0) min = j ; } strcpy (temp, name[ i ] ) ; strcpy (name[ i ] , name[min ] ) ; strcpy (name[min] , temp ) ; } } 143
  • 145. 9.2.4 Input and Output Figure 110: Sort city names in ascending order using functions and pointers. 144
  • 146. 9.3 Largest Element Write a C program to find the largest element in an integer array using an user-defined function and dynamic memory allocation. 9.3.1 Algorithm 1 Start 2 Declare two variables (i and max) and one pointer variable p. 3 Call malloc(sizeof(int)*7) function using p to allocate memory at runtime. 4 Initialize i to 0. 5 Repeat step 6 until i is equal to 7 satisfied. 6 Get the value for p[i]. 7 Call maximum(p) function and store its return value in max. 8 Display max’s value. 9 Stop. 1 function maximum(*l) 2 Declare two variables: i and max. 3 Assign l[0] to max. 4 Initialize i to 1. 5 Repeat step 6 until i is equal to 7 satisfied. 6 if l[i] is larger than max, then max = l[i]. 7 Return the value of max. Algorithm 56: Largest element in an integer array using user-defined function and DMA. 145
  • 147. 9.3.2 Flowchart Figure 111: Largest element in an integer array using user-defined function and DMA. 146
  • 148. 9.3.3 C Source Code #include<stdio .h> #include<stdlib .h> int maximum( int * ) ; void main( ) { int i , *p, max; p = ( int *) malloc ( sizeof ( int ) * 7 ) ; printf ( "Enter the value of array p : n" ) ; for ( i = 0; i < 7; i ++) scanf ( "%d" , p+i ) ; max = maximum(p ) ; printf ( "The maximum is %d" , max) ; } int maximum( int * l ) { int i , max = * l ; for ( i = 1; i < 7; i ++){ i f ( * ( l+i ) > max) max = *( l +i ) ; } return max; } 9.3.4 Input and Output Figure 112: Largest element in the given array using user-defined function and DMA. Objectives To understand the concept of pointers and have a clear idea on pointers declaration, definition, and initialization. To use pointers to access data in programs and also use them as parameters and return types for user defined functions. To understand the correlation between pointers and arrays, and use pointers to perform all kinds of mathematical operations. To write programs using static and dynamic memory allocation. 147
  • 149. 10 WEEK Structure, Union, and Enumeration 10.1 Student’s Details Write a C program to read name of a student, roll number and marks obtained in subjects from keyboard, and print name of the student, roll number, marks in 3 subjects, and total marks by using structures concept. 10.1.1 Algorithm 1 Start 2 Define a structure student of total and three arrays name, roll and marks as members. 3 Declare two variables: i and s1; s1 is a student type variable. 4 Initialize s1.total and i to 0. 5 Get the values for s1.name and s1.roll. 6 Repeat step 7 to 9 until i is equal to 3 satisfied. 7 Get the values for s1.marks[i]. 8 Add s1.marks[i] value to the current value of s1.total. 9 Increment i by 1. 10 Display s1.name’s and s1.roll’s values. 11 Repeat step 12 until i is equal to 3 satisfied. 12 Display s1.marks[i]’s value. 13 Display s1.total’s value. 14 Stop. Algorithm 57: Print student’s details. 148
  • 150. 10.1.2 Flowchart Figure 113: Print student’s details. 149
  • 151. 10.1.3 C Source Code #include<stdio .h> struct student { char name[20]; char r o l l [15]; float marks [ 3 ] ; float total ; } ; void main ( ) { struct student s1 ; int i ; s1 . total = 0; printf ( "Enter name of the student : n" ) ; gets ( s1 .name) ; printf ( "Enter r o l l no. of the student : n" ) ; gets ( s1 . r o l l ) ; for ( i = 0; i < 3; i ++){ printf ( "Enter the sub %d marks : " , i +1); scanf ( "%f " , &s1 . marks[ i ] ) ; s1 . total = s1 . total + s1 . marks[ i ] ; } printf ( "Name of the student : %s n" , s1 .name) ; printf ( " Roll no of the student : %s n" , s1 . r o l l ) ; for ( i = 0; i < 3; i ++) printf ( "The sub %d marks : %f n" , i +1, s1 . marks[ i ] ) ; printf ( "Total mark : %f n" , s1 . total ) ; } 10.1.4 Input and Output Figure 114: Student’s name, roll number, marks in 3 subjects, and total mark. 150
  • 152. 10.2 Students’ Details Write a C program to read name of the students, roll number and marks obtained in subjects from keyboard and print name of the students, roll number, marks in 3 subjects, and total marks by using array of structures concept. 10.2.1 Algorithm 1 Start 2 Define a structure student of total and three arrays name, roll and marks as members. 3 Declare three variables i, j and s[N]; s is a student type array and N is a constant. 4 Initialize i to 0. 5 Repeat step 6 to 13 until i is equal to N satisfied. 6 Get the values for s[i].name and s[i].roll. 7 Initialize s[i].total to 0. 8 Initialize j to 0. 9 Repeat step 10 to 12 until j is equal to 3 satisfied. 10 get the value for s[i].marks[j]. 11 Add s[i].marks[j]’s values to s[i].total. 12 Increment j by 1. 13 Increment i by 1. 14 Initialize i to 0. 15 Repeat step 16 to 22 until i is equal to N satisfied. 16 Display s[i].name’s and s[i].roll’s values. 17 Initialize j to 0. 18 Repeat step 19 and 20 until j is equal to 3 satisfied. 19 Display s[i].marks[j]’s value. 20 Increment j by 1. 21 Display s[i].total’s value. 22 Increment i by 1. 23 Stop. Algorithm 58: Print students’ details. 151
  • 153. 10.2.2 Flowchart Figure 115: Print students’ details. 152
  • 154. 10.2.3 C Source Code #include<stdio .h> #include<string .h> struct student { char name[15]; char r o l l [15]; float marks [ 3 ] ; float total ; } ; void main() { struct student s [ 3 ] ; int i , j ; for ( i= 0; i <= 2; i ++) { printf ( "Enter name of the student %d : " , i +1); gets ( s [ i ] .name) ; } for ( i= 0; i <= 2; i ++) { printf ( "Enter r o l l no. of the student %d : " , i +1); gets ( s [ i ] . r o l l ) ; } for ( i= 0; i <= 2; i ++) { s [ i ] . total = 0; for ( j = 0; j < 3; j ++) { printf ( "Enter the sub %d mark of student %d : " , j +1, i +1); scanf ( "%f " , &s [ i ] . marks[ j ] ) ; s [ i ] . total = s [ i ] . total + s [ i ] . marks[ j ] ; } } for ( i= 0; i <= 2; i ++) { printf ( "Name of the student %d : %s n" , i +1, s [ i ] .name) ; printf ( " Roll no. of the student %d : %s n" , i +1, s [ i ] . r o l l ) ; for ( j = 0; j < 3; j ++) printf ( "The sub %d mark of student %d : %f n" , j +1, i +1, s [ i ] . marks[ j ] ) ; printf ( "Total mark of student %d : %f n" , i +1, s [ i ] . total ) ; } } 153
  • 155. 10.2.4 Input and Output Figure 116: Students’ names, roll numbers, marks in 3 subjects, and total marks. 154
  • 156. 10.3 Days in a Week Write a C program to print a day in a week using Enumeration. 10.3.1 Algorithm 1 Start 2 Define a enum week of {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} as enum constants. 3 Declare a enum week variable day and get the value for it in between 0 and 6 . 4 If day is Sunday then display ’Sunday’ and go to step 12. 5 If day is Monday then display ’Monday’ and go to step 12. 6 If day is Tuesday then display ’Tuesday’ and go to step 12. 7 If day is Wednesday then display ’Wednesday’ and go to step 12. 8 If day is Thursday then display ’Thursday’ and go to step 12. 9 If day is Friday then display ’Friday’ and go to step 12. 10 If day is Saturday then display ’Saturday’ and go to step 12. 11 Stop. Algorithm 59: Print a day in a week. 155
  • 157. 10.3.2 Flow Chart Figure 117: Print a day in a week. 156
  • 158. 10.3.3 C Source Code #include<stdio .h> enum week {Sunday , Monday, Tuesday , Wednesday, Thursday , Friday , Saturday } ; void main ( ) { enum week day ; printf ( "Enter a day between 0 and 6 : n" ) ; scanf ( "%d" , &day ) ; switch (day ) { case Sunday : printf ( " I t is Sunday n" ) ; break ; case Monday: printf ( " I t is Monday n" ) ; break ; case Tuesday : printf ( " I t is Tuesday n" ) ; break ; case Wednesday: printf ( " I t is Wednesday n" ) ; break ; case Thursday : printf ( " I t is Thursday n" ) ; break ; case Friday : printf ( " I t is Friday n" ) ; break ; case Saturday : printf ( " I t is Saturday n" ) ; } } 10.3.4 Input and Output Figure 118: Display a day in a week using Enumeration. Objectives To instigate about the structure, union, and enumerated types derived data types. To use structure or union data types to address elements of multiple instances present in prob- lems. To write C programs using enumeration data types, an easiest way of mapping symbolic names to integer values. 157
  • 159. 11 WEEK File Handling Operations 11.1 Count Number of Character, Spaces, Words and Lines Write a C program to count number of character, spaces, words and lines in a file. 11.1.1 Algorithm 1 Start 2 Declare pre_ch, ch, character, line, space, words, char arr in_name and file * in_file. 3 Initialize character, line, space and words to 0. 4 Read a file name into in_name. 5 Call fopen(in_name, "r") function using in_file to open the file in read mode. 6 if in_file == NULL then display "Unable to open the file" and go to step 18. 7 Call fgetc(in_file) to read a character from the file and store it in ch. 8 Repeat the step 9 to 14 until ch is equal to EOF satisfied. 9 Increment character by 1. 10 If ch is equal to ’ ’, then space by 1. 11 If ch is equal to ’n’, then increment line by 1. 12 If ch is equal to ’ ’, ’t’, ’n’ or ’0’, then increment word by 1. 13 Assign ch value to pre_ch. 14 Call fgetc(in_file) to read the next character from the file and store it in ch. 15 If ch is not equal to ’ ’, ’t’, ’n’ and ’0’, then increment word and line by 1. 16 Call fclose(in_file) function to close the file input stream. 17 Display the values of character, line, space and words. 18 Stop. Algorithm 60: Count number of character, spaces, words and lines in a file. 158
  • 160. 11.1.2 Flowchart Figure 119: Count number of character, spaces, words and lines in a file. 159
  • 161. 11.1.3 C Source Code #include<stdio .h> void main( void ) { char in_name [80]; FILE * i n_fi l e ; int pre_ch , ch , character = 0 , line = 0 , space = 0 , words = 0; printf ( "Enter f i l e name : " ) ; scanf ( "%s" , in_name ) ; i n_fi l e = fopen(in_name , "r" ) ; i f ( i n_ fi l e == NULL) printf ( "Can ’ t open %s for reading .n" , in_name ) ; else { while (( ch = fgetc ( i n_ fil e )) != EOF) { character ++; i f (ch == ’ ’ ) space++; i f (ch == ’ n ’ ) line ++; i f (ch == ’ ’ | | ch == ’ t ’ | | ch == ’ n ’ | | ch == ’ 0 ’ ) words++; pre_ch = ch ; } i f ( pre_ch != ’ ’ && pre_ch != ’ t ’ && pre_ch != ’ n ’ && pre_ch != ’ 0 ’ ) { words++; line ++; } fclose ( i n_ fi l e ) ; printf ( "nNumber of characters = %d. n" , character ) ; printf ( "nNumber of spaces = %d. n" , space ) ; printf ( "nNumber of words = %d. n" , words ) ; printf ( "nNumber of lines = %d. n" , line ) ; } } 160
  • 162. 11.1.4 Input and Output Figure 120: Count number of character, spaces, words and lines in 123.txt. Figure 121: Number of Character, Spaces, Words and Lines in 123.txt. 161
  • 163. 11.2 Count Number of Alphabets, Digits, Punctuation Marks Write a C program that will read a text file and count the number of alphabetic characters, dig- its,punctuation characters in a file. 11.2.1 Algorithm 1 Start 2 Declare seven variables: ch, alp, digit, splch, k, an array in_name and file pointer in_file. 3 Initialize alp, digit and splch to 0. 4 Read a file name into in_name. 5 Call fopen(in_name, "r") function using in_file to open the file in read mode. 6 If in_file == NULL then display "Unable to open the file" and go to step 16. 7 Call fgetc(in_file) to read a character from the file and store it in ch. 8 Repeat the step 9 to 13 until ch is equal to EOF satisfied. 9 If ch is a character from [a-zA-Z], then increment alp by 1. 10 If ch is a character from [0-9], then increment digit by 1. 11 Call ispunct(ch) function and store the return value in k. 12 If k is equal to 1, then increment splch by 1. 13 Call fgetc(in_file) to read the next character from the file and store it in ch. 14 Call fclose(in_file) function to close the file input stream. 15 Display alp’s, digit’s and splch’s values. 16 Stop. Algorithm 61: Count number of alphabetic characters, digits and punctuation characters in a file. 162
  • 164. 11.2.2 Flowchart Figure 122: Count number of alphabetic characters, digits and punctuation characters in a file. 163
  • 165. 11.2.3 C Source Code #include<stdio .h> #include<ctype .h> void main( void ) { char in_name [80]; FILE * i n_fi l e ; int ch , alp , digit , splch ; alp = digit = splch = 0; printf ( "Count total number of alphabets , digits and " ) ; printf ( "Punctuation characters : n" ) ; printf ( "Enter f i l e name : n" ) ; scanf ( "%s" , in_name ) ; i n_fi l e = fopen(in_name , "r" ) ; i f ( i n_ fi l e == NULL) printf ( "Can ’ t open %s for reading .n" , in_name ) ; else { while (( ch = fgetc ( i n_ fil e )) != EOF) { i f (( ch >= ’a ’ && ch <= ’z ’ ) | | (ch >= ’A ’ && ch <= ’Z ’ )) alp ++; else i f (ch >= ’0 ’ && ch <= ’9 ’ ) digit ++; else i f ( ispunct (ch )) splch ++; } fclose ( i n_ fi l e ) ; printf ( "Number of Alphabets : %d" , alp ) ; printf ( "nNumber of Digits : %d" , digit ) ; printf ( "nNumber of Punctuation Characters : %d" , splch ) ; } } 164
  • 166. 11.2.4 Input and Output Figure 123: Contents of 123.txt. Figure 124: Number of alphabetic characters, digits and punctuation characters in 123.txt. 165
  • 167. 11.3 Merge Contents of Two Files Write a program in C to merge contents of two files and write it in a new file. 11.3.1 Algorithm 1 Start 2 Declare three file pointers fs1, fs2 and ft. 3 Declare a character variable ch and three character arrays file1, file2 and file3. 4 Read file names into file1, file2 and file3. 5 Call fopen(file1, "r") function using fs1 to open the file in read mode. 6 Call fopen(file2, "r") function using fs2 to open the file in read mode. 7 Call fopen(file3, "w") function using ft to open the file in write mode. 8 If fs1, fs2 and ft are equal to NULL, display "error" and go to step 20. 9 Call fgetc(fs1) function to read a character from the file1 and store it in ch. 10 Repeat the step 11 and 12 until ch is equal to EOF satisfied. 11 Call fputc(ch, ft) function to write ch value to file3. 12 Call fgetc(fs1) function to read next character from the file1 and store it in ch. 13 Call fgetc(fs2) function to read a character from the file2 and store it in ch. 14 Repeat the step 15 and 16 until ch is equal to EOF satisfied. 15 Call fputc(ch, ft) function to write ch value to file3. 16 Call fgetc(fs2) function to read next character from the file2 and store it in ch. 17 Display "Merged successfully". 18 Call fclose(fs1) function to close the file input stream linked to file1. 19 Call fclose(fs2) function to close the file input stream linked to file2. 20 Call fclose(ft) function to close the file output stream linked to file3. 21 Stop. Algorithm 62: Merge contents of two files and write it in a new file. 166
  • 168. 11.3.2 Flowchart Figure 125: Merge contents of two files and write it in a new file. 167
  • 169. 11.3.3 C Source Code #include <stdio .h> #include <stdlib .h> void main() { FILE * fs1 , * fs2 , * f t ; char ch , f i l e 1 [20] , f i l e 2 [20] , f i l e 3 [20]; printf ( "Enter name of f i r s t f i l e : n" ) ; gets ( f i l e 1 ) ; printf ( "Enter name of second f i l e : n" ) ; gets ( f i l e 2 ) ; printf ( "Enter name of f i l e to store contents of the two f i l e s : n" ) ; gets ( f i l e 3 ) ; fs1 = fopen ( file1 , " r" ) ; fs2 = fopen ( file2 , " r" ) ; i f ( fs1 == NULL | | fs2 == NULL) { perror ( "Error" ) ; printf ( "Press any key to exit . . . n" ) ; exit (EXIT_FAILURE ) ; } f t = fopen( file3 , "w" ) ; i f ( f t == NULL) { perror ( "Error" ) ; printf ( "Press any key to exit . . . n" ) ; exit (EXIT_FAILURE ) ; } while (( ch = fgetc ( fs1 )) != EOF) fputc (ch , f t ) ; while (( ch = fgetc ( fs2 )) != EOF) fputc (ch , f t ) ; printf ( "The two f i l e s were merged into %s f i l e .n" , f i l e 3 ) ; fclose ( fs1 ) ; fclose ( fs2 ) ; fclose ( f t ) ; } 168
  • 170. 11.3.4 Input and Output Figure 126: Contents of 123.txt. Figure 127: Contents of 124.txt. Figure 128: Contents of 125.txt after merging the contents of 123.txt and 124.txt. Figure 129: Contents of 125.txt. 169
  • 171. 11.4 Compare Contents of Two Files Write a C program to compare the contents of two files. If both are same, print the contents of one file else print the contents of both files. 11.4.1 Algorithm 1 Start 2 Declare two file pointers fptr1 and fptr2. 3 Declare s, flag, two character arrays path1 and path2. 4 Read file names into path1 and path2. 5 Call fopen(path1, "r") function using fptr1 to open the file1 in read mode. 6 Call fopen(path2, "r") function using fptr2 to open the file2 in read mode. 7 If fptr1 and fptr2 are equal to NULL, display "error" and go to step 22. 8 Call compareFile(fptr1, fptr2) function to compare the contents of two files. 9 If the return value is -1, then set flag to 2. 10 Else, set flag to 1. 11 Call fgetc(fptr1) function to read a character from the file1 and store it in s. 12 Repeat step 13 and 14 until s is equal to EOF satisfied. 13 Display the value of s. 14 Call fgetc(fptr1) function to read the next character from the file1 and store it in s. 15 If flag is equal to 1, then go to step 22. 16 Call fgetc(fptr2) function to read a character from the file2 and store it in s. 17 Repeat step 18 and 19 until s is equal to EOF satisfied. 18 Display the value of s. 19 Call fgetc(fptr2) function to read the next character from the file2 and store it in s. 20 Call fclose(fptr1) function to close the file input stream linked to file1. 21 Call fclose(fptr2) function to close the file input stream linked to file2. 22 Stop. 1 function compareFile(*fptr1, *fptr2) 2 Declare two variables ch1 and ch2. 3 Call fgetc(fptr1) function to read a character from the file1 and store it in ch. 4 Call fgetc(fptr2) function to read a character from the file2 and store it in ch. 5 If ch1 is not equal to ch2, then return -1. 6 Repeat step 3 to 5 till ch1 and ch2 are not equal to EOF. 7 If ch1 and ch2 are equal to EOF, then return 0. 8 Else, return -1. Algorithm 63: Compare the contents of two files and print the output. 170
  • 172. 11.4.2 Flowchart Figure 130: Compare the contents of two files and print the output. 171
  • 173. 11.4.3 C Source Code #include <stdio .h> #include <stdlib .h> int compareFile (FILE * fPtr1 , FILE * fPtr2 ) ; void main( void ) { FILE * fPtr1 ; FILE * fPtr2 ; char path1 [100]; char path2 [100]; char s ; int diff , flag ; printf ( "Enter path of f i r s t f i l e : n" ) ; scanf ( "%s" , path1 ) ; printf ( "Enter path of second f i l e : n" ) ; scanf ( "%s" , path2 ) ; fPtr1 = fopen(path1 , "r " ) ; fPtr2 = fopen(path2 , "r " ) ; i f ( fPtr1 == NULL | | fPtr2 == NULL) { printf ( "nUnable to open f i l e .n" ) ; exit (EXIT_FAILURE ) ; } d i f f = compareFile ( fPtr1 , fPtr2 ) ; i f ( d i f f == 0) flag =1; else flag =2; i f ( flag == 1){ while (( s = fgetc ( fPtr1 )) != EOF) printf ( "%c" , s ) ; } i f ( flag == 2){ while (( s = fgetc ( fPtr1 )) != EOF) ; printf ( "%c" , s ) ; printf ( "n" ) ; while (( s = fgetc ( fPtr2 )) != EOF) printf ( "%c" , s ) ; } fclose ( fPtr1 ) ; fclose ( fPtr2 ) ; } int compareFile ( FILE * fPtr1 , FILE * fPtr2 ) { char ch1 , ch2 ; do{ ch1 = fgetc ( fPtr1 ) ; ch2 = fgetc ( fPtr2 ) ; 172
  • 174. i f (ch1 != ch2) return −1; } while (ch1 != EOF && ch2 != EOF) ; i f (ch1 == EOF && ch2 == EOF) return 0; else return −1; } 11.4.4 Input and Output Figure 131: Contents of 123.txt. Figure 132: Contents of 126.txt. Figure 133: Output after comparing 123.txt and 126.txt files contents. Objectives To understand the use of file I/O commands using streams. Have a clear knowledge on read, write, append and update modes while performing any file operations. To write programs that execute read and write files using the formatting I/O and character I/O functions. To understand and apply file positioning, status and system commands based on a problem requirements. 173
  • 175. 12 WEEK Command Line Arguments 12.1 Copy the Content of File Write a C program to copy the content of one file into another file using command line argu- ments. 12.1.1 Algorithm 1 Start 2 Call main(3, "w12_1.exe", "123.txt", "124.txt") function. 3 Stop. 1 function main(argc, **argv) 2 Declare one character variable ch and two file pointers fs and ft. 3 If argc != 3 then display "Invalid no. of arguments" and return. 4 Call fopen(argv[1], "r") function using fs to open 123.txt file in read mode. 5 Call fopen(argv[2], "w") function using ft to open 124.txt file in write mode. 6 If fs == NULL or ft == NULL then display "Unable to open file(s) and return. 7 Read a character from 123.txt using fs and store it into ch. 8 Repeat step till ch == EOF is satisfied. 9 Write ch value to 124.txt using fp. 10 Read a character from 123.txt using fs and store it into ch. 11 Call fclose(fs) function to close the file input stream linked to 123.txt. 12 Call fclose(ft) function to close the file output stream linked to 124.txt. 13 Display "Successfully updated". Algorithm 64: Copy the content of one file into another file. 174
  • 176. 12.1.2 Flow Chart Figure 134: Copy the content of one file into another file. 175
  • 177. 12.1.3 C Source Code #include<stdio .h> #include<stdlib .h> void main( int argc , char* argv [ ] ) { FILE * fs , * f t ; int ch ; i f ( argc !=3) { printf ( " Invalid numbers of arguments .n" ) ; exit (EXIT_FAILURE ) ; } fs = fopen( argv [1] , "r " ) ; f t = fopen( argv [2] , "w" ) ; i f ( fs == NULL | | f t == NULL) { perror ( "Error" ) ; printf ( "Press any key to exit . . . n" ) ; exit (EXIT_FAILURE ) ; } while (( ch = fgetc ( fs )) != EOF) fputc (ch , f t ) ; printf ( " Successfully updated n" ) ; fclose ( fs ) ; fclose ( f t ) ; } 176
  • 178. 12.1.4 Input and Output Figure 135: Contents of 123.txt. Figure 136: Command line arguments for copying a file contents. Figure 137: Contents of 124.txt after copy operation. 177
  • 179. 12.2 Minimum and Maximum Integers in a List Write a C program that reads integer data from the standard input unit and prints the minimum integer read, maximum integer read, and the average of the list. Test your program with the data shown below. Use command line arguments to take the inputs. The set of integer numbers are {24, 7, 31, -5, 64, 0, 57, -23, 7, 63, 31, 15, 7, -3, 2, 4, 6} 12.2.1 Algorithm 1 Start 2 Call main(18, "w12_2.exe", "24", "7", "31", "-5", ..., "2", "4", "6") function. 3 Stop. 1 function main(argc, **argv) 2 Declare i, min, max, sum and an array arr. 3 Initialize sum to 0. 4 If argc != 18 then display "Invalid no. of arguments" and return. 5 Initialize i to 1. 6 Repeat step 7 and 8 until i > 17 is satisfied 7 Convert argv[i] to integer and store it into arr[i-1]. 8 Increment i by 1. 9 Initialize min and max to arr[0] 10 Reinitialize i to 0 11 Repeat step 12 to 14 until i is equal to 17 satisfied 12 If max is smaller than arr[i] then store arr[i] value in max 13 If min is greater than arr[i] then store arr[i]’s value in min. 14 Add arr[i]’s value to sum. 15 Display the of max, min and sum/argc. Algorithm 65: Maximum, minimum and average of a list of elements. 178
  • 180. 12.2.2 Flowchart Figure 138: Maximum, minimum and average of a list of elements. 179
  • 181. 12.2.3 C Source Code #include<stdio .h> #include<stdlib .h> void main( int argc , char* argv [ ] ) { int i , min, max, arr [17] , sum = 0; float avg ; i f ( argc != 18) { printf ( " Invalid numbers of arguments . n" ) ; exit (EXIT_FAILURE ) ; } for ( i = 1; i <= 17; i ++) arr [ i −1] = atoi ( argv [ i ] ) ; max = min = arr [ 0 ] ; for ( i = 0; i < 17; i ++) { i f (max < arr [ i ] ) max = arr [ i ] ; i f (min > arr [ i ] ) min = arr [ i ] ; sum = sum + arr [ i ] ; } printf ( "The maximum is : %dn" , max) ; printf ( "The minimum is : %dn" , min) ; printf ( "The average is : %f n" , ( float )sum/argc ) ; } 12.2.4 Input and Output Figure 139: Maximum, minimum and average of the given list of elements. 180
  • 182. 12.3 Reverses Elements of an Array Write a C program using the command line arguments. Write a function that reverses the ele- ments of an array so that the last element becomes the first, the second from the last becomes the second, and so forth. The function is to reverse the elements in place-that is, without using another array. (It is permissible to use a variable to hold an element temporarily.) Test the pro- gram twice, once with an even number of elements in the array and once with an odd number of elements in the array. 12.3.1 Algorithm 1 Start 2 Call main(n+1, "w12_3.exe", "a1", "a2", ..., "an") function. 3 Stop. 1 function main(argc, **argv) 2 Declare i and an array arr of size n. 3 If argc < 2 then display "Less arguments" and return. 4 Initialize i to 1. 5 Repeat step 6 and 7 until i == argc is satisfied 6 Convert argv[i] to integer and store it into arr[i-1]. 7 Increment i by 1. 8 Call reverse(arr, argc-1) function. 1 function reverse(*p, n) 2 Declare three variables: i, temp and mid. 3 Calculate middle index of array and store it into mid. (mid := (n-1)/2) 4 Initialize i to 0. 5 Repeat step 6 to 9 till i <= mid is satisfied. 6 Assign p[i] value to temp. 7 Assign p[n-1-i] value to p[i]. 8 Assign temp’s value to p[n-1-i]. 9 Increment i by 1. 10 Reinitialize i to 0. 11 Repeat step 12 and 13 till i < n is satisfied. 12 Display p[i]’s value. 13 Increment i by 1. Algorithm 66: Reverse elements of an odd and even sized arrays. 181
  • 183. 12.3.2 Flowchart Figure 140: Reverse elements of an odd and even sized arrays. 182
  • 184. 12.3.3 C Source Code #include<stdio .h> #include<stdlib .h> void reverse ( int *p, int n ) ; void main( int argc , char * argv [ ] ) { int i , arr [20]; i f ( argc < 2){ printf ( " Invalid numbers of arguments . n" ) ; exit (EXIT_FAILURE ) ; } for ( i = 1; i < argc ; i ++) arr [ i −1] = atoi ( argv [ i ] ) ; reverse ( arr , argc −1); } void reverse ( int *p, int n) { char temp; int i , mid = (n−1)/2; for ( i = 0; i <= mid; i ++){ temp = p[ i ] ; p[ i ] = p[n−1− i ] ; p[n−1− i ] = temp; } for ( i = 0; i < n; i ++) printf ( "%d t " , p[ i ] ) ; } 12.3.4 Input and Output Figure 141: Reverse elements of the given arrays. Objectives To use command line arguments to pass inputs in a single line while executing a program through the DOS command prompt or Linux terminal. To use atoi function to convert a default string value argument to an integer value inside the main function in a program. To use atof function to convert a default string value argument to a float value inside the main function in a program. 183
  • 185. 13 WEEK References 13.1 Text Books 1. Programming and Problem Solving Through "C" Language By HarshaPriya, R. Ranjeet Firewall media 2006. 2. Behrouz A. Forouzan and Richard F. Gilberg, "Computer Science A Structured Program- ming Approach Using C", CENGAGE Learning, Third Edition. 13.2 Reference Books 1. Anil B. Chaudhuri, "Flowchart and Algorithm Basics: The Art of Programming", Mercury Learning Information, 2020. 2. R.G. Dromey, "How to Solve it By Computer", Prentice-Hall International Series in Com- puter Science,1982. 3. YashwantKanetkar, "Let us C", BPB Publications, 16th Edition 2017. 4. Kernighan and Ritchie, "The C programming language", The (Ansi C Version), PHI, second edition. 5. Paul J. Dietel and Harvey M. Deitel, "C: How to Program", Prentice Hall, 8th edition (Jan 19.2021). 6. K.R.Venugopal, Sundeep R. Prasad, "Mastering C", McGraw Hill, 2nd Edition, 2015. 184
  • 186. 13.3 e-Resources and Other Digital Materials 1. Computer Science and Engineering - Noc:problem Solving Through Programming in C. [online] https://nptel.ac.in/courses/106/105/106105171/ 2. Computer Science and Engineering Noc:introduction To Programming in C. [online] https://nptel.ac.in/courses/106/104/106104128/ 3. C For Everyone: Structured Programming. [online] https://www.coursera.org/ learn/c-structured-programming 4. Advanced C Programming CourseTim Academy-Jason Fedin. [online] https://www. udemy.com/course/advanced-c-programming-course/ 185