You are on page 1of 158

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 )
Table of Contents
1 Introduction to C Programming 4
1.1 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Print Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Escape Sequence and Format Specifiers . . . . . . . . . . . . . . . . . 8
1.4 Literal, Defined and Memory Constants . . . . . . . . . . . . . . . . . 9
1.5 ASCII to Text Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Data Types and Variable Declarations 13


2.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Swap Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Comparison of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4 Size and Range of C Data Types . . . . . . . . . . . . . . . . . . . . . . 22

3 Selection – Making Decisions 26


3.1 Even or Odd Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.2 Biggest and Smallest Number . . . . . . . . . . . . . . . . . . . . . . . 28
3.3 Leap Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 Electricity Bill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4 Looping Constructs and Their Applications 35


4.1 Decimal to Binary Conversion . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 Factorial of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 Reverse of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.4 Strong Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.5 Armstrong Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.6 Fibonacci Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.7 Palindrome Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.8 Perfect Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.9 Print Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.10 Prime Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

5 Unconditional Control Transfer Statements 57


5.1 Calculator Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.2 Sum of N Natural Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.3 Even Numbers not Divisible by 6 and 8 . . . . . . . . . . . . . . . . . . 61

6 Arrays and Their Applications 63


6.1 Minimum and Maximum Elements . . . . . . . . . . . . . . . . . . . . 63
6.2 Sorting of n numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

1
6.3 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.4 Insertion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.5 Remove Duplicate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.6 Matrix Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.7 Matrix Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.8 Matrix Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

7 Strings, String I/O and Manipulation Functions 88


7.1 String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.2 Reverse a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
7.3 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.4 String Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

8 Concepts of User Defined Functions 102


8.1 Swap Two Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.2 Factorial of a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.3 Combination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.4 Mean and Standard Deviation . . . . . . . . . . . . . . . . . . . . . . . 112

9 Pointers and Their Applications 116


9.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
9.2 String Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
9.3 Largest Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

10 Structure, Union, and Enumeration 124


10.1 Student’s Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
10.2 Students’ Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
10.3 Days in a Week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

11 File Handling Operations 133


11.1 Count Number of Character, Spaces, Words and Lines . . . . . . . . . 133
11.2 Count Number of Alphabets, Digits, Punctuation Marks . . . . . . . 136
11.3 Merge Contents of Two Files . . . . . . . . . . . . . . . . . . . . . . . . 139
11.4 Compare Contents of Two Files . . . . . . . . . . . . . . . . . . . . . . 143

12 Command Line Arguments 147


12.1 Copy the Content of File . . . . . . . . . . . . . . . . . . . . . . . . . . 147
12.2 Minimum and Maximum Integers in a List . . . . . . . . . . . . . . . 150
12.3 Reverses Elements of an Array . . . . . . . . . . . . . . . . . . . . . . . 153

13 References 156
13.1 Text Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

2
13.2 Reference Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
13.3 e-Resources and Other Digital Materials . . . . . . . . . . . . . . . . . 157

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.1 Variable Declarations
1
Introduction to C
Programming
SECTION

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.

1.1.3 C Source Code

#include < s t d i o . h>


void main ( ) {
/ / a character v a r i a b l e named option .
char option ;
/ / an i n t e g e r variable , sum, i n i t i a l i z e d to 0 .
int sum = 0 ;
/ / a f l o a t i n g −point variable , product , i n i t i a l i z e d to 1 .
f l o a t product = 1 ;
/ / a short i n t e g e r v a r i a b l e named code .
short int code ;
/ / a constant named sales_Tax i n i t i a l i z e d to 0 . 0 8 2 5 .
const f l o a t sales_Tax = 0 . 0 8 2 5 ;
/ / a f l o a t i n g −point named sum_of_size double i n i t i a l i z e d to 0 .
f l o a t sum_of_size = 0 ;
}

5
1.1.4 Input and Output

Figure 2: Character, integer, floating-point variable declarations and initialization.

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.

6
1.2.2 Flowchart

Figure 3: Rectangle star pattern.

Figure 4: Right angle triangle star pattern.

1.2.3 C Source Code

I. #include < s t d i o . h>


void main ( ) {
p r i n t f ( " * \ t * \ t * \ t * \ t * \ t * \n" ) ;
p r i n t f ( " * \ t * \ t * \ t * \ t * \ t * \n" ) ;
p r i n t f ( " * \ t * \ t * \ t * \ t * \ t * \n" ) ;
p r i n t f ( " * \ t * \ t * \ t * \ t * \ t * \n" ) ;
}

7
I I . #include < s t d i o . h>
void main ( ) {
p r i n t f ( " * \n" ) ;
p r i n t f ( " * \ t * \n" ) ;
p r i n t f ( " * \ t * \ t * \n" ) ;
p r i n t f ( " * \ t * \ t * \ t * \n" ) ;
}

1.2.4 Input and Output

Figure 5: Rectangle star pattern [4x6].

Figure 6: Right angle triangle star pattern.

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.

8
1.3.2 Flowchart

Figure 7: Outcomes using escape sequence and format specifiers.

1.3.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int a = 1 , b = 10 , c = 100 , d = 1000 , e = 10000;
p r i n t f ( "a : %d , b : %d , c : %d , d : %d , e : %d \n" , a , b , c , d , e ) ;
p r i n t f ( "a : %f , b : %f " , ( f l o a t ) a , ( f l o a t ) b ) ;
p r i n t f ( "c : %f , d : %f , e : %f \n" , ( f l o a t ) c , ( f l o a t ) d , ( f l o a t ) e ) ;
}

1.3.4 Input and Output

Figure 8: Outcomes using \n escape sequence, %d and %f format specifiers.

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.

9
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.

10
1.4.3 C Source Code

#include < s t d i o . 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 ;
p r i n t f ( "%c \ t %c \ t %c \ t %c \ t %c \n" , a , b , c , d , e ) ;
p r i n t f ( "%d \ t %d \ t %d \ t %d \ t %d \n" , i , j , k , l , m) ;
p r i n t f ( "%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.

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.

11
1.5.2 Flowchart

Figure 11: ASCII to text conversion.

1.5.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int k ;
p r i n t f ( " Enter the value of k \n" ) ;
scanf ( "%d" , &k ) ;
p r i n t f ( "The number as a character : %c" , k ) ;
p r i n t f ( "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.

12
2.1 Arithmetic Operations
Data Types and Variable
2
Declarations
SECTION

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.

13
2.1.2 Flowchart

Figure 13: Arithmetic operations between different types of data.

14
2.1.3 C Source Code

#include < s t d i o . h>


#include <stdbool . h>
void main ( )
{
bool a = f a l s e , b = true ;
char x , y ;
int i , j ;
f l o a t l , m;
p r i n t f ( " Enter the i n t e g e r values of i and j : \n" ) ;
scanf ( "%d %d" , &i , &j ) ;
p r i n t f ( " Enter the f l o a t values of l and m : \n" ) ;
scanf ( "%f %f " , &l , &m) ;
p r i n t f ( " Enter the character values of x and y : \n" ) ;
scanf ( "%c %c" , &x , &y ) ;
p r i n t f ( " Arithmetic operations on boolean data : \n" ) ;
p r i n t f ( " Addition : %d \n Subtraction : %d \n" , a+b , a−b ) ;
p r i n t f ( " M u l t i p l i c a t i o n : %d \n Division : %d \n Modulus %d \n" \
, a * b , a/b , a%b ) ;
p r i n t f ( " Arithmetic operations on i n t e g e r data : \n" ) ;
p r i n t f ( " Addition : %d \n Subtraction : %d \n" , i +j , i − j ) ;
p r i n t f ( " M u l t i p l i c a t i o n : %d \n Division : %d \n Modulus : %d \n" \
, i * j , i / j , i%j ) ;
p r i n t f ( " Arithmetic operations on f l o a t data : \n" ) ;
p r i n t f ( " Addition : %f \n Subtraction : %f \n" , l +m, l −m) ;
p r i n t f ( " M u l t i p l i c a t i o n : %f \n Division : %f \n" , l *m, l /m) ;
p r i n t f ( " Arithmetic operations on character data : \n" ) ;
p r i n t f ( " Addition : %c \n Subtraction : %c \n" , x+y , x−y ) ;
p r i n t f ( " M u l t i p l i c a t i o n : %c \n Division : %c \n Modulus : %c \n" \
, x * y , x /y , x%y ) ;
}

15
2.1.4 Input and Output

Figure 14: Arithmetic operations between boolean, integer, float, and character data.

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.

16
2.2.2 Flowchart

Figure 15: Swap two integer numbers with third variable.

Figure 16: Swap two integer numbers without third variable.

17
2.2.3 C Source Code

a. #include < s t d i o . h>


void main ( ) {
int a , b , temp ;
p r i n t f ( " Enter two i n t e g e r values : " ) ;
scanf ( "%d %d" , &a , &b ) ;
p r i n t f ( "a = %d , b = %d \n" , a , b ) ;
temp = a ;
a = b;
b = temp ;
p r i n t f ( " A f t e r swapping the values : \n" ) ;
p r i n t f ( "a = %d , b = %d \n" , a , b ) ;
}

b. #include < s t d i o . h>


void main ( ) {
int a , b ;
p r i n t f ( " Enter two i n t e g e r values : " ) ;
scanf ( "%d %d" , &a , &b ) ;
p r i n t f ( "a = %d , b = %d \n" , a , b ) ;
a = a+b ;
b = a−b ;
a = a−b ;
p r i n t f ( " A f t e r swapping the values : \n" ) ;
p r i n t f ( "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.

18
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.

19
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.

20
2.3.3 C Source Code

a. #include < s t d i o . h>


void main ( ) {
int a , b , c , max, min ;
p r i n t f ( " Enter three i n t e g e r values : " ) ;
scanf ( "%d %d %d" , &a , &b , &c ) ;
p r i n t f ( "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 ;
p r i n t f ( " Largest : %d \n" , max ) ;
p r i n t f ( " Smallest : %d" ,min ) ;
}

b. #include < s t d i o . h>


void main ( ) {
int a , b , c , max, min ;
p r i n t f ( " Enter three i n t e g e r values : " ) ;
scanf ( "%d %d %d" , &a , &b , &c ) ;
p r i n t f ( "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 ) ;
p r i n t f ( " Largest : %d \n" , max ) ;
p r i n t f ( " 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.

21
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.

22
2.4.2 Flowchart

Figure 23: Data types’ ranges and sizes.

23
2.4.3 C Source Code

#include < s t d i o . h>


#include <stddef . h>
#include < s t d i n t . h>
#include < l i m i t s . h>
#include < f l o a t . h>
# define UINT_MIN 0
# define SIZE_MIN 0
void main ( ) {
p r i n t f ( " char : %ld \n" , s i z e o f ( char ) ) ;
p r i n t f ( " signed char %ld \n" , s i z e o f ( signed char ) ) ;
p r i n t f ( " i n t : %ld \n" , s i z e o f ( i nt ) ) ;
p r i n t f ( " signed i n t : %ld \n" , s i z e o f ( signed in t ) ) ;
p r i n t f ( " unsigned i n t : %ld \n" , s i z e o f ( unsigned i nt ) ) ;
p r i n t f ( " long i n t : %ld \n" , s i z e o f ( long i nt ) ) ;
p r i n t f ( " long long i n t : %ld \n" , s i z e o f ( long long i n t ) ) ;
p r i n t f ( " intmax_t : %ld \n" , s i z e o f ( intmax_t ) ) ;
p r i n t f ( " s i z e _ t : %ld \n" , s i z e o f ( s i z e _ t ) ) ;
p r i n t f ( " f l o a t : %ld \n" , s i z e o f ( f l o a t ) ) ;
p r i n t f ( "double : %ld \n" , s i z e o f ( double ) ) ;
p r i n t f ( " long double : %ld \n" , s i z e o f ( long double ) ) ;
p r i n t f ( "The minimum value of CHAR i s = %d\n" , CHAR_MIN) ;
p r i n t f ( "The maximum value of CHAR i s = %d\n" , CHAR_MAX) ;
p r i n t f ( "The minimum value of Signed CHAR i s = %d\n" , SCHAR_MIN ) ;
p r i n t f ( "The maximum value of Signed CHAR i s = %d\n" , SCHAR_MAX) ;
p r i n t f ( "The minimum value of INT i s = %d\n" , INT_MIN ) ;
p r i n t f ( "The maximum value of INT i s = %d\n" , INT_MAX ) ;
p r i n t f ( "The minimum value of signed INT i s = %d\n" , INT_MIN ) ;
p r i n t f ( "The maximum value of signed INT i s = %d\n" , INT_MAX ) ;
p r i n t f ( "The minimum value of Unsigned INT i s = %u\n" , UINT_MIN ) ;
p r i n t f ( "The maximum value of Unsigned INT i s = %u\n" , UINT_MAX ) ;
p r i n t f ( "The minimum value of Short INT i s = %d\n" , SHRT_MIN ) ;
p r i n t f ( "The maximum value of Short INT i s = %d\n" , SHRT_MAX) ;
p r i n t f ( "The minimum value of LONG INT i s = %ld \n" , LONG_MIN) ;
p r i n t f ( "The maximum value of LONG INT i s = %ld \n" , LONG_MAX) ;
p r i n t f ( "The minimum value of LONG LONG INT i s = %l l d \n" , LLONG_MIN) ;
p r i n t f ( "The maximum value of LONG LONG INT i s = %l l d \n" , LLONG_MAX) ;
p r i n t f ( "The minimum value of INTMAX_T i s = %l l d \n" , INTMAX_MIN ) ;
p r i n t f ( "The maximum value of INTMAX_T i s = %l l d \n" , INTMAX_MAX) ;
p r i n t f ( "The minimum value of SIZE_T i s = %l l u \n" , SIZE_MIN ) ;
p r i n t f ( "The maximum value of SIZE_T i s = %l l u \n" , SIZE_MAX ) ;
p r i n t f ( "The minimum value of f l o a t i s = %.10e\n" , FLT_MIN ) ;
p r i n t f ( "The maximum value of f l o a t i s = %.10e\n" , FLT_MAX ) ;
p r i n t f ( "The minimum value of Double i s = %.10e\n" , DBL_MIN ) ;
p r i n t f ( "The maximum value of Double i s = %.10e\n" , DBL_MAX) ;

24
p r i n t f ( "The minimum value of LONG Double i s = %.10Le\n" ,LDBL_MIN ) ;
p r i n t f ( "The maximum value of LONG Double i s = %.10Le\n" ,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.

25
3.1 Even or Odd Number
Selection – Making Decisions
3 SECTION

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.

26
3.1.2 Flowchart

Figure 25: Even or odd number.

3.1.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int num;
p r i n t f ( " Enter an i n t e g e r number : \n" ) ;
scanf ( "%d" , &num) ;
i f (num % 2 == 0)
p r i n t f ( "%d i s an even number" , num) ;
el se
p r i n t f ( "%d i s an odd number" , num) ;
}

3.1.4 Input and Output

Figure 26: Even or odd number.

27
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.

3.2.2 Flowchart

Figure 27: Biggest among three numbers.

28
Figure 28: Smallest among three numbers.

3.2.3 C Source Code

a. #include < s t d i o . h>


void main ( ) {
int a , b , c ;
p r i n t f ( " Enter three i n t e g e r numbers : \n" ) ;
scanf ( "%d %d %d" , &a , &b , &c ) ;
i f ( a>=b ) {
i f ( a>=c )
p r i n t f ( "%d i s bi gge st \n" , a ) ;
el se
p r i n t f ( "%d i s bi gge st \n" , c ) ;
}
el se {
i f ( b>=c )
p r i n t f ( "%d i s bi gge st \n" , b ) ;
el se
p r i n t f ( "%d i s bi gge st \n" , c ) ;
}
}

b. #include < s t d i o . h>


void main ( ) {
int a , b , c ;
p r i n t f ( " Enter three i n t e g e r numbers : \n" ) ;

29
scanf ( "%d %d %d" , &a , &b , &c ) ;
i f ( a<=b ) {
i f ( a<=c )
p r i n t f ( "%d i s smallest \n" , a ) ;
el se
p r i n t f ( "%d i s smallest \n" , c ) ;
}
el se {
i f ( b<=c )
p r i n t f ( "%d i s smallest \n" , b ) ;
el se
p r i n t f ( "%d i s smallest \n" , c ) ;
}
}

3.2.4 Input and Output

Figure 29: Largest among three numbers.

Figure 30: Smallest among three numbers.

30
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.

3.3.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int yr ;
p r i n t f ( " Enter a year to check leap yr . or not : " ) ;
scanf ( "%d" , &yr ) ;
i f ( yr%100 == 0 && yr%400 == 0)

31
p r i n t f ( "%d i s a leap year " , yr ) ;
el se i f ( yr%100 ! = 0 && yr%4 == 0)
p r i n t f ( "%d i s a leap year " , yr ) ;
el se
p r i n t f ( "%d i s not a leap year " , yr ) ;
}

3.3.4 Input and Output

Figure 32: Verify year 1900 is a leap year or not.

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.

32
3.4.2 Flowchart

Figure 33: Compute electricity bill with slabs.

33
3.4.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int units ;
float ebill ;
p r i n t f ( " Enter the amount of units consumed : \n" ) ;
scanf ( "%d" , &units ) ;
i f ( units <200)
e b i l l = units * 1 . 2 0 ;
el se i f ( units >= 200 && units < 400)
e b i l l = 199 * 1.20 + ( units − 1 9 9 ) * 1 . 5 0 ;
el se i f ( units >= 400 && units < 600)
e b i l l = 199 * 1.20 + 200 * 1.50 + ( units − 3 9 9 ) * 1 . 8 0 ;
el se
e b i l l = 199 * 1.20 + 200 * 1.50 + 200 * 1.80 + ( units − 5 9 9 ) * 2 . 0 ;
p r i n t f ( "The t o t a l e b i l l amount i s %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.

34
4.1 Decimal to Binary Conversion
Looping Constructs and
4
Their Applications
SECTION

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.

35
4.1.2 Flowchart

Figure 35: Decimal to binary conversion.

4.1.3 C Source Code

#include < s t d i o . h>


#include <math . h>
void main ( ) {
int num, rem , sum = 0 , cnt = 0 ;
p r i n t f ( " Enter a decimal number : " ) ;
scanf ( "%d" , &num) ;
while (num ! = 0 ) {
rem = num % 2 ;
sum = rem * pow( 1 0 , cnt ) + sum;
num = num/ 2 ;
cnt ++;
}
p r i n t f ( "The binary no i s %d" , sum ) ;
}

36
4.1.4 Input and Output

Figure 36: Binary value of decimal number 10.

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.

37
4.2.3 C Source Code

#include < s t d i o . h>


void main ( )
{
int num, f a c t = 1 ;
p r i n t f ( " Enter a i n t e g e r number \n" ) ;
scanf ( "%d" , &num) ;
while (num ! = 0 ) {
f a c t = f a c t * num;
num− −;
}
p r i n t f ( " F a c t o r i a l of a number i s %d" , f a c t ) ;
}

4.2.4 Input and Output

Figure 38: Factorial of the number 6.

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.

38
4.3.2 Flowchart

Figure 39: Reverse of a given number.

4.3.3 C Source Code

#include < s t d i o . h>


void main ( )
{
int num, rem , sum = 0 ;
p r i n t f ( " Enter a i n t e g e r number \n" ) ;
scanf ( "%d" , &num) ;
while (num ! = 0 ) {
rem = num % 10;
sum = sum * 10 + rem ;
num = num / 10;
}
p r i n t f ( "The reverse no i s : %d" , sum ) ;
}

39
4.3.4 Input and Output

Figure 40: Reverse of the given number 12345.

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.

40
4.4.2 Flowchart

Figure 41: Verify a number is a strong number or not.

4.4.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int num, i , j , rem , f a c t , sum = 0 ;

41
p r i n t f ( " Enter a i n t e g e r number \n" ) ;
scanf ( "%d" , &num) ;
for ( i = num; i ! = 0 ; i = i / 1 0 ) {
rem = i % 10;
fact = 1;
for ( j = rem ; j ! = 0 ; j −−)
fact = fact * j ;
sum = sum + f a c t ;
}
i f (sum == num)
p r i n t f ( "%d i s a strong number" , num) ;
el se
p r i n t f ( "%d i s not a strong number" , num) ;
}

4.4.4 Input and Output

Figure 42: Verify 145 is a strong number or not.

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 r em num_si ze 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.

42
4.5.2 Flowchart

Figure 43: Verify a number is an Armstrong number or not.

4.5.3 C Source Code

#include < s t d i o . h>


#include <math . h>
void main ( ) {
int num, temp , rem , size , sum = 0 ;
p r i n t f ( " Enter the s i z e of a number \n" ) ;
scanf ( "%d" , &s i z e ) ;
p r i n t f ( " Enter a i n t e g e r number \n" ) ;
scanf ( "%d" , &num) ;
temp = num;

43
do {
rem = temp % 10;
sum = sum + pow(rem , s i z e ) ;
temp = temp/ 1 0 ;
} while (temp ! = 0 ) ;
i f (num == sum)
p r i n t f ( "%d i s an Armstrong number" , num) ;
el se
p r i n t f ( "%d i s not an Armstrong number" , num) ;
}

4.5.4 Input and Output

Figure 44: Verify 1634 is an Armstrong number or not.

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.

44
4.6.2 Flowchart

Figure 45: Fibonacci series up to step = steps.

4.6.3 C Source Code

#include < s t d i o . h>


void main ( )
{
int f1 = 0 , f2 = 1 , f3 , cnt = 0 , steps ;
p r i n t f ( " Enter the no . of steps to p r i n t fibonacci s e r i e s : " ) ;
scanf ( "%d" , &steps ) ;
do
{
p r i n t f ( "%d \n" , f1 ) ;
f3 = f1 + f2 ;

45
f1 = f2 ;
f2 = f3 ;
cnt ++;
} while ( cnt < steps ) ;
}

4.6.4 Input and Output

Figure 46: Fibonacci series up to step 7.

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.

46
4.7.2 Flowchart

Figure 47: Verify a number is a palindrome or not.

47
4.7.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int i , num, rem , sum = 0 ;
p r i n t f ( " Enter an i n t e g e r number \n" ) ;
scanf ( "%d" , & num) ;
for ( i = num; i ! = 0 ; i = i / 1 0 ) {
rem = i % 10;
sum = sum * 10 + rem ;
}
i f (sum == num)
p r i n t f ( "%d i s a palindrome" , num) ;
el se
p r i n t f ( "%d i s not a palindrome" , num) ;
}

4.7.4 Input and Output

Figure 48: Verify 12321 is a palindrome or not.

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.

48
4.8.2 Flowchart

Figure 49: Verify a number is a perfect number or not.

49
4.8.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int i , num, sum = 0 ;
p r i n t f ( " Enter a +ve i n t e g e r number : " ) ;
scanf ( "%d" , &num) ;
for ( i = 1 ; i < num; i ++){
i f (num % i == 0)
sum = sum + i ;
}
i f (sum == num)
p r i n t f ( "%d i s a p e r f e c t number" , num) ;
el se
p r i n t f ( "%d i s not a p e r f e c t number" , num) ;
}

4.8.4 Input and Output

Figure 50: Verify 28 is a perfect number or not.

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.

50
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.

4.9.2 Flowchart

Figure 51: * in right angle triangle pattern.

51
Figure 52: * in equilateral triangle pattern.

52
4.9.3 C Source Code

a. #include < s t d i o . h>


void main ( ) {
int i , j , s i z e ;
p r i n t f ( " Enter s i z e of the l a t e r a l : " ) ;
scanf ( "%d" , &s i z e ) ;
for ( i = 1 ; i <= s i z e ; i ++){
for ( j = 1 ; j <= i ; j ++)
printf ( "*" ) ;
p r i n t f ( " \n" ) ;
}
}
\ vspace { 0 . 3cm}
b. #include < s t d i o . h>
void main ( ) {
int i , j , k , s i z e ;
p r i n t f ( " Enter s i z e of the l a t e r a l : " ) ;
scanf ( "%d" , &s i z e ) ;
for ( i = 1 ; i <= s i z e ; i ++){
for ( j = s i z e − i ; j ! = 0 ; j −−)
printf ( " " ) ;
for ( k = 1 ; k <= i ; k++)
printf ( "* " ) ;
p r i n t f ( " \n" ) ;
}
}

4.9.4 Input and Output

Figure 53: * in right angle triangle pattern of size = 5.

53
Figure 54: * in equilateral triangle pattern of size = 5.

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.

54
4.10.2 Flowchart

Figure 55: Prime numbers between 1 and n.

55
4.10.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int i , j , num, f l a g ;
p r i n t f ( " 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 ( f l a g == 0)
p r i n t f ( "%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.

56
5.1 Calculator Application
Unconditional Control
Transfer Statements
5 SECTION

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.

57
5.1.2 Flowchart

Figure 57: Calculator application to perform arithmetic operations.

5.1.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int a , b , c , i ;
p r i n t f ( " Enter two i n t e g e r number : " ) ;
scanf ( "%d %d" , &a , &b ) ;
p r i n t f ( " Enter your choice : \n" ) ;
p r i n t f ( " [ 1 ] Addition \n [ 2 ] Subtraction \n" ) ;
p r i n t f ( " [ 3 ] M u l t i p l i c a t i o n \n [ 4 ] Division \n [ 5 ] Modulus \n" ) ;
scanf ( "%d" , &i ) ;
switch ( i ) {
case 1 : c = a + b ;
p r i n t f ( " Addition : %d \n" , c ) ;
break ;
case 2 : c = a − b ;
p r i n t f ( " Subtraction : %d \n" , c ) ;
break ;
case 3 : c = a * b ;
p r i n t f ( " M u l t i p l i c a t i o n : %d \n" , c ) ;
break ;
case 4 : c = a / b ;

58
p r i n t f ( " Division : %d \n" , c ) ;
break ;
case 5 : c = a % b ;
p r i n t f ( "Modulus : %d \n" , c ) ;
break ;
default : p r i n t f ( " I n v a l i d Option \n" ) ;
}
}

5.1.4 Input and Output

Figure 58: Calculator application to perform arithmetic operations.

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.

59
5.2.2 Flowchart

Figure 59: Sum of 1 to n Natural numbers.

5.2.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int i = 1 , n , sum = 0 ;
p r i n t f ( " Enter the value of n : \n" ) ;
scanf ( "%d" , &n ) ;
start :
sum += i ;
i ++;
i f ( i <= n)
goto s t a r t ;
p r i n t f ( "The sum i s : %d \n" , sum ) ; }

5.2.4 Input and Output

Figure 60: Sum of 1 to 10 Natural numbers.

60
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.

61
5.3.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int n , i ;
p r i n t f ( " 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 ;
el se
p r i n t f ( "%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.

62
6.1 Minimum and Maximum Elements
6 SECTION

Arrays and Their


Applications

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.

63
6.1.2 Flowchart

Figure 63: Maximum and minimum elements in an array.

6.1.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int a r r [ 7 ] , min , max, i ;
p r i n t f ( " Enter the elements of an array : \n" ) ;
for ( i = 0 ; i < 7 ; i ++)
scanf ( "%d" , &a r r [ i ] ) ;
min = max = a r r [ 0 ] ;
for ( i = 1 ; i < 7 ; i ++){
max = ( a r r [ i ] > max) ? a r r [ i ] : max ;

64
min = ( a r r [ i ] < min ) ? a r r [ i ] : min ; }
p r i n t f ( "The maximum i s : %d and the minimum i s : %d \n" , max, min ) ;
}

6.1.4 Input and Output

Figure 64: Maximum and minimum elements in the given array.

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.

65
6.2.2 Flowchart

Figure 65: Sort elements of the given array using Selection sort.

6.2.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int a r r [ 7 ] , min , temp , i , j ;

66
p r i n t f ( " Enter the elements of an array : \n" ) ;
for ( i = 0 ; i < 7 ; i ++)
scanf ( "%d" , &a r r [ i ] ) ;
/ / Do the s o r t i n g [ s e l e c t i o n s o r t ]
for ( i = 0 ; i < 6 ; i ++){
min = i ;
for ( j = i +1; j < 7 ; j ++)
min = ( a r r [ j ] < a r r [min ] ) ? j : min ;
temp = a r r [ i ] ;
a r r [ i ] = a r r [min ] ;
a r r [min] = temp ; }
p r i n t f ( " the elements a f t e r the s o r t i n g : \n" ) ;
for ( i = 0 ; i < 7 ; i ++)
p r i n t f ( "%d \ t " , a r r [ i ] ) ; }

6.2.4 Input and Output

Figure 66: Elements of the given array after sorting.

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.

67
6.3.2 Flowchart

Figure 67: Search an element in an array using linear search.

6.3.3 C Source Code

#include < s t d i o . h>


#include <stdbool . h>
void main ( ) {
int i , num, index , a r r [ 7 ] = { 9 , 8 , 3 , 6 , 7 , 10 , 2 } ;
bool f l a g = 0 ;
p r i n t f ( " Enter the element to be searched : \n" ) ;
scanf ( "%d" , &num) ;
for ( i = 0 ; i < 7 ; i ++){

68
i f ( a r r [ i ] == num) {
f l a g = 1 ; index = i ;
break ; }}
if ( flag )
p r i n t f ( "Element i s found at %dth location . \n" , index ) ;
el se
p r i n t f ( "Element i s not present in the array . \n" ) ;
}

6.3.4 Input and Output

Figure 68: Search an element 3 in the given array.

6.4 Insertion
Write a C program to insert an element at a specified location in an array.

69
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.

70
6.4.2 Flowchart

Figure 69: Insert a number at a given location in an array.

71
6.4.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int a r r [ 1 0 ] , num, pos , i , l a s t _ i n d e x ;
p r i n t f ( " Enter the elements of an array : \n" ) ;
for ( i = 0 ; i < 7 ; i ++)
scanf ( "%d" , &a r r [ i ] ) ;
l a s t _ i n d e x = i −1;
p r i n t f ( " Enter the element and i t s position : \n" ) ;
scanf ( "%d %d" , &num, &pos ) ;
i f ( pos < 0 | | pos > 9)
p r i n t f ( " I n s e r t i o n i s not possible \n" ) ;
el se i f ( pos > 6 ) {
a r r [ i ] = num;
last_index = i ;
}
el se {
for ( int j = i ; j ! = pos ; j −−)
arr [ j ] = arr [ j −1];
a r r [ pos ] = num;
last_index = i ;
}
p r i n t f ( " P r i n t the updated array : \n" ) ;
for ( int j = 0 ; j <= l a s t _ i n d e x ; j ++)
p r i n t f ( "%d \ t " , a r r [ j ] ) ;
}

6.4.4 Input and Output

Figure 70: Insert 4 at 3rd location in the given array.

72
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.

73
6.5.2 Flowchart

Figure 71: Remove duplicate elements from an array.

74
6.5.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int i , j , A[ 1 0 ] , B[ 1 0 ] , f i n a l _ i n d e x = 0 , \
flag [10]={0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0};
p r i n t f ( " Enter the elements f o r array A : \n" ) ;
for ( i = 0 ; i <= 9 ; i ++)
scanf ( "%d" , &A[ i ] ) ;
p r i n t f ( "A : " ) ;
for ( i = 0 ; i <= 9 ; i ++)
p r i n t f ( "%d \ t " , A[ i ] ) ;
p r i n t f ( " \n" ) ;
/ / remove duplicate elements
for ( i = 0 ; i <= 9 ; i ++){
i f ( f l a g [ i ] == 0 ) {
B[ f i n a l _ i n d e x ] = A[ i ] ;
f i n a l _ i n d e x ++;
for ( j = i +1; j <= 9 ; j ++){
i f (A[ i ] == A[ j ] )
flag [ j ] = 1;
}
}
}
/ / pri nt the output array
p r i n t f ( "B : " ) ;
for ( i = 0 ; i < f i n a l _ i n d e x ; i ++)
p r i n t f ( "%d \ t " , B[ i ] ) ;
}

6.5.4 Input and Output

Figure 72: Array elements before, and its elements after removal of duplicates.

75
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.

76
6.6.2 Flowchart

Figure 73: Summation of two size * size matrices.

77
6.6.3 C Source Code

#include < s t d i o . h>


void main ( ) {
int i , j , A [ 3 ] [ 3 ] , B [ 3 ] [ 3 ] , C [ 3 ] [ 3 ] ;
p r i n t f ( " Enter the elements f o r array A \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++){
p r i n t f ( " \n[%d][%d ] element of A i s : " , i , j ) ;
scanf ( "%d" , &A[ i ] [ j ] ) ;
}
}
p r i n t f ( " Enter the elements f o r array B \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++){
p r i n t f ( " \n[%d][%d ] element of B i s : " , i , j ) ;
scanf ( "%d" , &B[ i ] [ j ] ) ;
}
}
p r i n t f ( "A : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++)
p r i n t f ( "%d\ t " , A[ i ] [ j ] ) ;
p r i n t f ( " \n" ) ;
}
p r i n t f ( "B : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++)
p r i n t f ( "%d\ t " , B[ i ] [ j ] ) ;
p r i n t f ( " \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 ] ;
}
}
/ / f i n a l output matrix
p r i n t f ( "C : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j = 0 ; j <= 2 ; j ++)
p r i n t f ( "%d\ t " , C[ i ] [ j ] ) ;
p r i n t f ( " \n" ) ;
}
}

78
6.6.4 Input and Output

Figure 74: Summation of two 3*3 matrices.

79
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.

80
6.7.2 Flowchart

Figure 75: Multiplication of two size*size matrices.

81
6.7.3 C Source Code

#include < s t d i o . h>


void main ( )
{
int i , j , k , A [ 3 ] [ 3 ] , B [ 3 ] [ 3 ] , C[ 3 ] [ 3 ] , sum;
p r i n t f ( " Enter the elements f o r array A \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++){
p r i n t f ( " \n[%d][%d ] element of A i s : " , i , j ) ;
scanf ( "%d" , &A[ i ] [ j ] ) ;
}
}
p r i n t f ( " Enter the elements f o r array B \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++){
p r i n t f ( " \n[%d][%d ] element of B i s : " , i , j ) ;
scanf ( "%d" , &B[ i ] [ j ] ) ;
}
}
p r i n t f ( "A : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++)
p r i n t f ( "%d\ t " , A[ i ] [ j ] ) ;
p r i n t f ( " \n" ) ;
}
p r i n t f ( "B : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <=2; j ++)
p r i n t f ( "%d\ t " , B[ i ] [ j ] ) ;
p r i n t f ( " \n" ) ;
}
/ / matrix mu l ti p l i c a t i o n 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;
}
}
/ / f i n a l output matrix
p r i n t f ( "C : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++){
for ( j = 0 ; j <= 2 ; j ++)
p r i n t f ( "%d\ t " , C[ i ] [ j ] ) ;

82
p r i n t f ( " \n" ) ;
}
}

6.7.4 Input and Output

Figure 76: Multiplication of two 3*3 matrices.

83
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.

84
6.8.2 Flowchart

Figure 77: Transpose of a size*size matrix.

85
6.8.3 C Source Code

#include < s t d i o . h>


void main ( )
{
int i , j , A [ 3 ] [ 3 ] , B [ 3 ] [ 3 ] ;
p r i n t f ( " Enter the elements f o r array A \n" ) ;
for ( i = 0 ; i <= 2 ; i ++)
{
for ( j =0; j <= 2 ; j ++)
{
p r i n t f ( " \n[%d][%d ] element of A i s : " , i , j ) ;
scanf ( "%d" , &A[ i ] [ j ] ) ;
}
}
p r i n t f ( "A : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++)
{
for ( j = 0 ; j <= 2 ; j ++)
p r i n t f ( "%d\ t " , A[ i ] [ j ] ) ;
p r i n t f ( " \n" ) ;
}
/ / Transpose of matrix
for ( i = 0 ; i <= 2 ; i ++){
for ( j =0; j <= 2 ; j ++)
B[ i ] [ j ] = A[ j ] [ i ] ;
}
/ / Output matrix
p r i n t f ( "B : \n" ) ;
for ( i = 0 ; i <= 2 ; i ++)
{
for ( j = 0 ; j <= 2 ; j ++)
p r i n t f ( "%d\ t " , B[ i ] [ j ] ) ;
p r i n t f ( " \n" ) ;
}
}

86
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.

87
7.1 String Length
Strings, String I/O and
Manipulation Functions
7 SECTION

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 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 40: Length of a string without using string handling functions.

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 41: Length of a string using string handling functions.

88
7.1.2 Flowchart

Figure 79: Length of a string without using string handling functions.

Figure 80: Length of a string using string handling functions.

89
7.1.3 C Source Code

a. #include < s t d i o . h>


void main ( ) {
char s t r [ 3 0 ] ;
int cnt = 0 ;
p r i n t f ( " enter the s t r i n g value : \n" ) ;
gets ( s t r ) ;
/ / Count the s i z e of the s t r i n g
while ( s t r [ cnt ] ! = ’ \0 ’ )
cnt ++;
p r i n t f ( "The s i z e of the ’%s ’ i s : %d \n" , s t r , cnt ) ;
}

b. #include < s t d i o . h>


#include < s t r i n g . h>
void main ( ) {
char s t r [ 3 0 ] ;
p r i n t f ( " enter the s t r i n g value \n" ) ;
gets ( s t r ) ;
p r i n t f ( "The s i z e of the ’%s ’ i s : %lu \n" , s t r , s t r l e n ( s t r ) ) ;
}

7.1.4 Input and Output

Figure 81: Length of "VRSEC, Vijayawada" without using string handling functions.

Figure 82: Length of "S&H, VRSEC, Vijayawada" using string handling functions.

90
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 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 42: Reverse a string without using string handling function.

1 Start
2 Declare an array str.
3 Read the string into str.
4 Call the string reverse function strrev(str) and result is stored in str.
5 Display the value of str.
6 Stop

Algorithm 43: Reverse a string using string handling function.

91
7.2.2 Flowchart

Figure 83: Reverse a string without using string handling function.

92
Figure 84: Reverse a string using string handling function.

7.2.3 C Source Code

a. #include < s t d i o . h>


void main ( ) {
char s t r [ 3 0 ] , r e v s t r [ 3 0 ] ;
int i , cnt = 0 ;
p r i n t f ( " enter the s t r i n g value \n" ) ;
gets ( s t r ) ;
/ / Count the s i z e of the s t r i n g
while ( s t r [ cnt ] ! = ’ \0 ’ )
cnt ++;
/ / S to r e the s t r i n g in r e v e r s e order
for ( i = 0 ; i < cnt ; i ++)
r e v s t r [ i ] = s t r [ cnt −1− i ] ;
r e v s t r [ i ] = ’ \0 ’ ;
p r i n t f ( "The reverse of ’%s ’ i s ’%s ’ \n" , s t r , r e v s t r ) ;
}

b. #include < s t d i o . h>


#include < s t r i n g . h>
void main ( ) {
char s t r [ 3 0 ] ;
p r i n t f ( " enter the s t r i n g value \n" ) ;
gets ( s t r ) ;
p r i n t f ( " Reverse of ’%s ’ i s ’%s ’ " , s t r , s t r r e v ( s t r ) ) ;
}

93
7.2.4 Input and Output

Figure 85: Reverse "VRSEC, Vijayawada" without using string handling function.

Figure 86: Reverse a "S&H, VRSE, Vijayawada" using string handling function.

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 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 to 8 until str1[cnt1]!=’\0’ is satisfied.
6 Place str1[cnt1]’s value in str3[cnt3].
7 Increment the value of cnt1 by 1.
8 Increment the value of cnt3 by 1.
9 Repeat the step 10 to 12 until str2[cnt2]!=’\0’ is satisfied.
10 Place str2[cnt2]’s value in str3[cnt3].
11 Increment the value of cnt2 by 1.
12 Increment the value of cnt3 by 1.
13 Store ’\0’ in str3[cnt3].
14 Display the value of str3.
15 Stop

Algorithm 44: String concatenation without using string handling function.

94
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 45: String concatenation using string handling function.

7.3.2 Flowchart

Figure 87: String concatenation without using string handling function.

95
Figure 88: String concatenation using string handling function.

7.3.3 C Source Code

a. #include < s t d i o . h>


#include < s t r i n g . h>
void main ( )
{
char s t r 1 [ 3 0 ] , s t r 2 [ 3 0 ] , s t r 3 [ 6 0 ] ;
int cnt1 = 0 , cnt2 = 0 , cnt3 = 0 ;
p r i n t f ( " enter the s t r i n g value f o r s t r 1 : \n" ) ;
gets ( s t r 1 ) ;
p r i n t f ( " enter the s t r i n g value f o r s t r 2 : \n" ) ;
gets ( s t r 2 ) ;
while ( s t r 1 [ cnt1 ] ! = ’ \0 ’ ) {
s t r 3 [ cnt3 ] = s t r 1 [ cnt1 ] ;
cnt1 ++;
cnt3 ++;
}
while ( s t r 2 [ cnt2 ] ! = ’ \0 ’ ) {
s t r 3 [ cnt3 ] = s t r 2 [ cnt2 ] ;
cnt2 ++;
cnt3 ++;
}
s t r 3 [ cnt3 ] = ’ \0 ’ ;
p r i n t f ( "The s t r 1 + s t r 2 i s ’%s ’ \n" , s t r 3 ) ;
}

96
b. #include < s t d i o . h>
#include < s t r i n g . h>
void main ( )
{
char s t r 1 [ 3 0 ] , s t r 2 [ 3 0 ] ;
p r i n t f ( " enter the s t r i n g value f o r s t r 1 : \n" ) ;
gets ( s t r 1 ) ;
p r i n t f ( " enter the s t r i n g value f o r s t r 2 : \n" ) ;
gets ( s t r 2 ) ;
p r i n t f ( "The s t r 1 + s t r 2 i s ’%s ’ \n" , s t r c a t ( s tr1 , s t r 2 ) ) ;
}

7.3.4 Input and Output

Figure 89: Concatenation of "S&H, VRSEC" and "Vijayawada" without using string handling
function.

Figure 90: Concatenation of "S&H, VRSEC," and "Vijayawada" using string handling function.

97
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 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 46: String comparison without using string handling function.

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 47: String comparison using string handling function.

98
7.4.2 Flowchart

Figure 91: String comparison without using string handling function.

99
Figure 92: String comparison using string handling function.

7.4.3 C Source Code

a. #include < s t d i o . h>


#include < s t r i n g . h>
void main ( ) {
char s t r 1 [ 3 0 ] , s t r 2 [ 3 0 ] ;
int cnt1 = 0 , cnt2 = 0 ;
int i , f l a g = 1 ;
p r i n t f ( " enter the s t r i n g value f o r s t r 1 : \n" ) ;
gets ( s t r 1 ) ;
p r i n t f ( " enter the s t r i n g value f o r s t r 2 : \n" ) ;
gets ( s t r 2 ) ;
while ( s t r 1 [ cnt1 ] ! = ’ \0 ’ )
cnt1 ++;
while ( s t r 2 [ cnt2 ] ! = ’ \0 ’ )
cnt2 ++;
i f ( cnt1 ! = cnt2 )
flag = 0;
el se {
for ( i = 0 ; i < cnt1 ; i ++){
i f ( str1 [ i ] != str2 [ i ] ) {
flag = 0;
break ;
}
}

100
}
if ( flag )
p r i n t f ( "Both the s t r i n g s are equal . \n" ) ;
el se
p r i n t f ( "Both the s t r i n g s are d i f f e r e n t . \n" ) ;
}

b. #include < s t d i o . h>


#include < s t r i n g . h>
void main ( ) {
char s t r 1 [ 3 0 ] , s t r 2 [ 3 0 ] ;
p r i n t f ( " enter the s t r i n g value f o r s t r 1 : \n" ) ;
gets ( s t r 1 ) ;
p r i n t f ( " enter the s t r i n g value f o r s t r 2 : \n" ) ;
gets ( s t r 2 ) ;
i f ( ! strcmp ( str1 , s t r 2 ) )
p r i n t f ( "Both the s t r i n g s are equal . \n" ) ;
el se
p r i n t f ( "Both the s t r i n g s are d i f f e r e n t . \n" ) ;
}

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.

101
8.1 Swap Two Numbers
Concepts of User Defined
8 Functions
SECTION

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.

102
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.

103
Figure 96: Swap two numbers using call by reference.

8.1.3 C Source Code

a. #include < s t d i o . h>


void swap ( int a , int b ) ;
void main ( )
{
int a , b ;
p r i n t f ( " 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 ;
p r i n t f ( "The a and b values a f t e r swapping are %d and %d \n" , a , b ) ;
}

b . #include < s t d i o . h>


void swap ( int * a , int * b ) ;
void main ( )
{

104
int a , b ;
p r i n t f ( " Enter the value of a and b : \n" ) ;
scanf ( "%d %d" , &a , &b ) ;
swap(&a , &b ) ;
p r i n t f ( "The a and b values a f t e r swapping are %d and %d . \n" , a , b ) ;
}
void swap ( int * a , int * b)
{
int temp ;
temp = * a ;
* a = *b ;
* b = temp ;
}

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.

105
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 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 50: factorial of a +ve number without 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 If n == 1 then return 1.
3 Else, return n*factorial(n-1).

Algorithm 51: factorial of a +ve number using recursion.

106
8.2.2 Flowchart

Figure 99: factorial of a +ve number without using recursion.

107
Figure 100: factorial of a +ve number using recursion.

8.2.3 C Source Code

a. #include < s t d i o . h>


i nt f a c t ( int n ) ;
void main ( ) {
int n ;
p r i n t f ( " Enter an +ve i n t e g e r number : \n" ) ;
scanf ( "%d" , &n ) ;
p r i n t f ( "The f a c t o r i a l of %d i s : %d . \n" , n , f a c t (n ) ) ;
}
i nt f a c t ( int n ) {
int i , mult = 1 ;
for ( i = n ; i > 0 ; i −−)
mult = mult * i ;
return mult ;
}

b. #include < s t d i o . h>


i nt f a c t ( int n ) ;
void main ( ) {
int n ;
p r i n t f ( " Enter an +ve i n t e g e r number : \n" ) ;
scanf ( "%d" , &n ) ;
p r i n t f ( "The f a c t o r i a l of %d i s : %d . \n" , n , f a c t (n ) ) ;

108
}
i nt f a c t ( int n ) {
i f (n == 1)
return 1 ;
el se
return n * f a c t (n− 1 ) ;
}

8.2.4 Input and Output

Figure 101: factorial of 6 without using recursion.

Figure 102: factorial of 5 using recursion.

8.3 Combination
Write a C program to find n C r 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.

109
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.

8.3.2 Flowchart

Figure 103: Compute nCr for given n and r.

110
8.3.3 C Source Code

#include < s t d i o . h>


i nt nCr ( int n , int r ) ;
i nt f a c t ( int n ) ;
void main ( )
{
int n , r ;
p r i n t f ( " Enter the value of n and r : \n" ) ;
scanf ( "%d %d" , &n , &r ) ;
i f (n >= r )
p r i n t f ( "The nCr i s %d . \n" , nCr (n , r ) ) ;
el se
p r i n t f ( "You have entered wrong values . \n" ) ;
}
i nt nCr ( int n , int r )
{
return f a c t (n ) / ( f a c t ( r ) * f a c t (n−r ) ) ;
}
i nt f a c t ( int n)
{
i f (n==1)
return 1 ;
el se
return n * f a c t (n− 1 ) ;
}

8.3.4 Input and Output

Figure 104: Compute nCr for n = 6 and r = 2.

111
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.

112
8.4.2 Flowchart

Figure 105: Mean and standard deviation of a set of numbers.

113
8.4.3 C Source Code

#include < s t d i o . h>


#include <math . h>
# define N 7
f l o a t mean( f l o a t * arr , int n ) ;
f l o a t stddev ( f l o a t * arr , f l o a t mn, i nt n ) ;
void main ( )
{
int i ;
f l o a t mn, a r r [N] ;
p r i n t f ( " Enter the value of the array : \n" ) ;
for ( i = 0 ; i < N; i ++){
scanf ( "%f " , &a r r [ i ] ) ;
}
mn = mean(& a r r [ 0 ] , N) ;
p r i n t f ( "mean value of a r r i s %f . \n" , mn) ;
p r i n t f ( " stddev of a r r i s %f . \n" , stddev(& a r r [ 0 ] , mn, N) ) ;
}
f l o a t mean( f l o a t * arr , int n)
{
int i ;
f l o a t mn = 0 . 0 ;
for ( i = 0 ; i < n ; i ++)
mn = mn + * ( a r r + i ) ;
mn /= n ;
return mn;
}
f l o a t stddev ( f l o a t * arr , f l o a t mn, i nt n)
{
int i ;
f l o a t dev = 0 . 0 ;
for ( i = 0 ; i < n ; i ++)
dev = dev + pow( * ( a r r + i ) −mn, 2 ) ;
dev = s q r t ( dev/n ) ;
return dev ;
}

114
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.

115
9.1 Arithmetic Operations
9
Pointers and Their
Applications
SECTION

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.

116
9.1.2 Flowchart

Figure 107: Arithmetic operations on integers using pointers.

9.1.3 C Source Code

#include < s t d i o . h>


void main ( ) {
i nt a , b ;
int * p = &a , * q = &b ;
p r i n t f ( " Enter the value of a and b : \n" ) ;
scanf ( "%d %d" , p , q ) ;
p r i n t f ( "%d + %d i s %d \n" , * p , * q , * p + *q ) ;
p r i n t f ( "%d − %d i s %d \n" , * p , * q , * p − *q ) ;
p r i n t f ( "%d * %d i s %d \n" , * p , * q , * p * *q ) ;
p r i n t f ( "%d / %d i s %d \n" , * p , * q , * p / *q ) ;
}

117
9.1.4 Input and Output

Figure 108: arithmetic operations on 5 and 3 using pointers.

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.

118
9.2.2 Flowchart

Figure 109: Sort names in ascending order using functions and pointers.

9.2.3 C Source Code

#include < s t d i o . h>


#include < s t r i n g . h>
# define s i z e 7
void s o r t ( char *name ) ;
void main ( ) {

119
int i ;
char name[ s i z e ] [ 2 0 ] ;
p r i n t f ( " Enter the input : \n" ) ;
for ( i = 0 ; i < s i z e ; i ++)
gets (&name[ i ] ) ;
p r i n t f ( " p r i n t the array before s o r t i n g : \n" ) ;
for ( i = 0 ; i < s i z e ; i ++)
p r i n t f ( "%s \n" , name[ i ] ) ;
s o r t (&name [ 0 ] [ 0 ] ) ;
p r i n t f ( " p r i n t the array a f t e r s o r t i n g : \n" ) ;
for ( i = 0 ; i < s i z e ; i ++)
p r i n t f ( "%s \n" , name[ i ] ) ; }
void s o r t ( char *name) {
char temp [ 2 0 ] ;
int i , j , min ;
for ( i = 0 ; i < s i z e ; i ++){
min = i ;
for ( j = i +1; j < s i z e ; j ++){
i f ( strcmp (name[min ] , name[ j ] ) > 0)
min = j ; }
strcpy (temp , name[ i ] ) ;
strcpy (name[ i ] , name[min ] ) ;
strcpy (name[min ] , temp ) ; }}

9.2.4 Input and Output

Figure 110: Sort city names in ascending order using functions and pointers.

120
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.

121
9.3.2 Flowchart

Figure 111: Largest element in an integer array using user-defined function and DMA.

9.3.3 C Source Code

#include < s t d i o . h>


#include < s t d l i b . h>
i nt maximum( int * ) ;
void main( ) {
int i , * p , max ;
p = ( int * ) malloc ( s i z e o f ( i nt ) * 7 ) ;

122
p r i n t f ( " Enter the value of array p : \n" ) ;
for ( i = 0 ; i < 7 ; i ++)
scanf ( "%d" , p+ i ) ;
max = maximum(p ) ;
p r i n t f ( "The maximum i s %d" , max ) ;
}
i nt 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.

123
10.1 Student’s Details
10
Structure, Union, and
Enumeration
S ECTION

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.

124
10.1.2 Flowchart

Figure 113: Print student’s details.

125
10.1.3 C Source Code

#include < s t d i o . h>


str uct student {
char name[ 2 0 ] ;
char r o l l [ 1 5 ] ;
f l o a t marks [ 3 ] ;
float total ;
};
void main ( ) {
struct student s1 ;
int i ;
s1 . t o t a l = 0 ;
p r i n t f ( " Enter name of the student : \n" ) ;
gets ( s1 .name ) ;
p r i n t f ( " Enter r o l l no . of the student : \n" ) ;
gets ( s1 . r o l l ) ;
for ( i = 0 ; i < 3 ; i ++){
p r i n t f ( " Enter the sub %d marks : " , i + 1 ) ;
scanf ( "%f " , &s1 . marks [ i ] ) ;
s1 . t o t a l = s1 . t o t a l + s1 . marks [ i ] ;
}
p r i n t f ( "Name of the student : %s \n" , s1 .name ) ;
p r i n t f ( " R o l l no of the student : %s \n" , s1 . r o l l ) ;
for ( i = 0 ; i < 3 ; i ++)
p r i n t f ( "The sub %d marks : %f \n" , i +1 , s1 . marks [ i ] ) ;
p r i n t f ( " Total mark : %f \n" , s1 . t o t a l ) ;
}

10.1.4 Input and Output

Figure 114: Student’s name, roll number, marks in 3 subjects, and total mark.

126
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.

127
10.2.2 Flowchart

Figure 115: Print students’ details.

128
10.2.3 C Source Code

#include < s t d i o . h>


#include < s t r i n g . h>
str uct student {
char name[ 1 5 ] ;
char r o l l [ 1 5 ] ;
f l o a t marks [ 3 ] ;
float total ;
};
void main ( )
{
struct student s [ 3 ] ;
int i , j ;
for ( i = 0 ; i <= 2 ; i ++)
{
p r i n t f ( " Enter name of the student %d : " , i + 1 ) ;
gets ( s [ i ] . name ) ;
}
for ( i = 0 ; i <= 2 ; i ++)
{
p r i n t f ( " 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 ++)
{
p r i n t f ( " Enter the sub %d mark of student %d : " , j +1 , i + 1 ) ;
scanf ( "%f " , &s [ i ] . marks [ j ] ) ;
s [ i ] . t o t a l = s [ i ] . t o t a l + s [ i ] . marks [ j ] ;
}
}
for ( i = 0 ; i <= 2 ; i ++)
{
p r i n t f ( "Name of the student %d : %s \n" , i +1 , s [ i ] . name ) ;
p r i n t f ( " R o l l no . of the student %d : %s \n" , i +1 , s [ i ] . r o l l ) ;
for ( j = 0 ; j < 3 ; j ++)
p r i n t f ( "The sub %d mark of student %d : %f \n" , j +1 , \
i +1 , s [ i ] . marks [ j ] ) ;
p r i n t f ( " Total mark of student %d : %f \n" , i +1 , s [ i ] . t o t a l ) ;
}
}

129
10.2.4 Input and Output

Figure 116: Students’ names, roll numbers, marks in 3 subjects, and total marks.

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.
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 Else, display "Invalid Input".
12 Stop.
Algorithm 59: Print a day in a week.

130
10.3.2 Flow Chart

Figure 117: Print a day in a week.

131
10.3.3 C Source Code

#include < s t d i o . h>


enum week { Sunday , Monday, Tuesday , Wednesday , Thursday , Friday , \
Saturday } ;
void main ( ) {
enum week day ;
p r i n t f ( " Enter a day between 0 and 6 : \n" ) ;
scanf ( "%d" , &day ) ;
switch ( day ) {
case Sunday : p r i n t f ( " I t i s Sunday \n" ) ;
break ;
case Monday : p r i n t f ( " I t i s Monday \n" ) ;
break ;
case Tuesday : p r i n t f ( " I t i s Tuesday \n" ) ;
break ;
case Wednesday : p r i n t f ( " I t i s Wednesday \n" ) ;
break ;
case Thursday : p r i n t f ( " I t i s Thursday \n" ) ;
break ;
case Friday : p r i n t f ( " I t i s Friday \n" ) ;
break ;
case Saturday : p r i n t f ( " I t i s 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.

132
11
File Handling Operations

11.1 Count Number of Character, Spaces, Words and Lines


S ECTION

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.

133
11.1.2 Flowchart

Figure 119: Count number of character, spaces, words and lines in a file.

134
11.1.3 C Source Code

#include < s t d i o . h>


void main( void ) {
char in_name [ 8 0 ] ;
FILE * i n _ f i l e ;
int pre_ch , ch , character = 0 , l i n e = 0 , space = 0 , words = 0 ;
p r i n t f ( " Enter f i l e name : " ) ;
scanf ( "%s " , in_name ) ;
i n _ f i l e = fopen ( in_name , " r " ) ;
i f ( i n _ f i l e == NULL)
p r i n t f ( "Can ’ t open %s f o r reading . \ n" , in_name ) ;
el se {
while ( ( ch = f g e t c ( i n _ f i l e ) ) ! = EOF) {
character ++;
i f ( ch == ’ ’ )
space ++;
i f ( ch == ’ \n ’ )
l i n e ++;
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++;
l i n e ++;
}
fclose ( in_file ) ;
p r i n t f ( " \nNumber of characters = %d . \n" , character ) ;
p r i n t f ( " \nNumber of spaces = %d . \n" , space ) ;
p r i n t f ( " \nNumber of words = %d . \n" , words ) ;
p r i n t f ( " \nNumber of l i n e s = %d . \n" , l i n e ) ;
}
}

11.1.4 Input and Output

Figure 120: Count number of character, spaces, words and lines in 123.txt.

135
Figure 121: Number of Character, Spaces, Words and Lines in 123.txt.

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.

136
11.2.2 Flowchart

Figure 122: Count number of alphabetic characters, digits and punctuation characters in a file.

137
11.2.3 C Source Code

#include < s t d i o . h>


#include <ctype . h>
void main( void )
{
char in_name [ 8 0 ] ;
FILE * i n _ f i l e ;
int ch , alp , d i g i t , splch ;
alp = d i g i t = splch = 0 ;
p r i n t f ( "Count t o t a l number of alphabets , d i g i t s and " ) ;
p r i n t f ( " Punctuation characters : \n" ) ;
p r i n t f ( " Enter f i l e name : \n" ) ;
scanf ( "%s " , in_name ) ;
i n _ f i l e = fopen ( in_name , " r " ) ;
i f ( i n _ f i l e == NULL)
p r i n t f ( "Can ’ t open %s f o r reading . \ n" , in_name ) ;
el se
{
while ( ( ch = f g e t c ( i n _ f i l e ) ) ! = EOF)
{
i f ( ( ch >= ’ a ’ && ch <= ’ z ’ ) | | ( ch >= ’A ’ && ch <= ’Z ’ ) )
alp ++;
el se i f ( ch >= ’ 0 ’ && ch <= ’ 9 ’ )
d i g i t ++;
el se i f ( ispunct ( ch ) )
splch ++;
}
fclose ( in_file ) ;
p r i n t f ( "Number of Alphabets : %d" , alp ) ;
p r i n t f ( " \nNumber of D i g i t s : %d" , d i g i t ) ;
p r i n t f ( " \nNumber of Punctuation Characters : %d" , splch ) ;
}
}

11.2.4 Input and Output

Figure 123: Contents of 123.txt.

138
Figure 124: Number of alphabetic characters, digits and punctuation characters in 123.txt.

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.

139
11.3.2 Flowchart

Figure 125: Merge contents of two files and write it in a new file.

140
11.3.3 C Source Code

#include < s t d i o . h>


#include < s t d l i b . h>
void main ( )
{
FILE * fs1 , * fs2 , * f t ;
char ch , f i l e 1 [ 2 0 ] , f i l e 2 [ 2 0 ] , f i l e 3 [ 2 0 ] ;
p r i n t f ( " Enter name of f i r s t f i l e : \n" ) ;
gets ( f i l e 1 ) ;
p r i n t f ( " Enter name of second f i l e : \n" ) ;
gets ( f i l e 2 ) ;
p r i n t f ( " Enter name of f i l e to s t o r e contents of the two f i l e s : \n" ) ;
gets ( f i l e 3 ) ;
f s 1 = fopen ( f i l e 1 , " r " ) ;
f s 2 = fopen ( f i l e 2 , " r " ) ;
i f ( f s 1 == NULL | | f s 2 == NULL)
{
perror ( " Error " ) ;
p r i n t f ( " Press any key to e x i t . . . \ n" ) ;
e x i t ( EXIT_FAILURE ) ;
}
f t = fopen ( f i l e 3 , "w" ) ;
i f ( f t == NULL)
{
perror ( " Error " ) ;
p r i n t f ( " Press any key to e x i t . . . \ n" ) ;
e x i t ( EXIT_FAILURE ) ;
}
while ( ( ch = f g e t c ( f s 1 ) ) ! = EOF)
fputc ( ch , f t ) ;
while ( ( ch = f g e t c ( f s 2 ) ) ! = EOF)
fputc ( ch , f t ) ;
p r i n t f ( "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 ) ;
}

141
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.

142
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.

143
11.4.2 Flowchart

Figure 130: Compare the contents of two files and print the output.

144
11.4.3 C Source Code

#include < s t d i o . h>


#include < s t d l i b . h>
i nt compareFile ( FILE * fPtr1 , FILE * f P t r 2 ) ;
void main( void ) {
FILE * f P t r 1 ;
FILE * f P t r 2 ;
char path1 [ 1 0 0 ] ;
char path2 [ 1 0 0 ] ;
char s ;
int d i f f , f l a g ;
p r i n t f ( " Enter path of f i r s t f i l e : \n" ) ;
scanf ( "%s " , path1 ) ;
p r i n t f ( " Enter path of second f i l e : \n" ) ;
scanf ( "%s " , path2 ) ;
f P t r 1 = fopen ( path1 , " r " ) ;
f P t r 2 = fopen ( path2 , " r " ) ;
i f ( f P t r 1 == NULL | | f P t r 2 == NULL) {
p r i n t f ( " \nUnable to open f i l e . \ n" ) ;
e x i t ( EXIT_FAILURE ) ;
}
d i f f = compareFile ( fPtr1 , f P t r 2 ) ;
i f ( d i f f == 0)
f l a g =1;
el se
f l a g =2;
i f ( f l a g == 1 ) {
while ( ( s = f g e t c ( f P t r 1 ) ) ! = EOF)
p r i n t f ( "%c" , s ) ;
}
i f ( f l a g == 2 ) {
while ( ( s = f g e t c ( f P t r 1 ) ) ! = EOF ) ;
p r i n t f ( "%c" , s ) ;
p r i n t f ( " \n" ) ;
while ( ( s = f g e t c ( f P t r 2 ) ) ! = EOF)
p r i n t f ( "%c" , s ) ;
}
fclose ( fPtr1 ) ;
fclose ( fPtr2 ) ;
}
i nt compareFile ( FILE * fPtr1 , FILE * f P t r 2 ) {
char ch1 , ch2 ;
do {
ch1 = f g e t c ( f P t r 1 ) ;
ch2 = f g e t c ( f P t r 2 ) ;

145
i f ( ch1 ! = ch2 )
return −1;
} while ( ch1 ! = EOF && ch2 ! = EOF ) ;
i f ( ch1 == EOF && ch2 == EOF)
return 0 ;
el se
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.

146
12
Command Line Arguments

12.1 Copy the Content of File


S ECTION

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.

147
12.1.2 Flow Chart

Figure 134: Copy the content of one file into another file.

12.1.3 C Source Code

#include < s t d i o . h>


#include < s t d l i b . h>
void main( int argc , char * argv [ ] ) {
FILE * fs , * f t ;
int ch ;
i f ( argc ! = 3 ) {
p r i n t f ( " I n v a l i d numbers of arguments . \ n" ) ;
e x i t ( EXIT_FAILURE ) ;
}

148
f s = fopen ( argv [ 1 ] , " r " ) ;
f t = fopen ( argv [ 2 ] , "w" ) ;
i f ( f s == NULL | | f t == NULL) {
perror ( " Error " ) ;
p r i n t f ( " Press any key to e x i t . . . \n" ) ;
e x i t ( EXIT_FAILURE ) ;
}
while ( ( ch = f g e t c ( f s ) ) ! = EOF)
fputc ( ch , f t ) ;
p r i n t f ( " S u c c e s s f u l l y updated \n" ) ;
fclose ( fs ) ;
fclose ( f t ) ;
}

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.

149
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.

150
12.2.2 Flowchart

Figure 138: Maximum, minimum and average of a list of elements.

151
12.2.3 C Source Code

#include < s t d i o . h>


#include < s t d l i b . h>
void main( int argc , char * argv [ ] )
{
int i , min , max, a r r [ 1 7 ] , sum = 0 ;
f l o a t avg ;
i f ( argc ! = 18)
{
p r i n t f ( " I n v a l i d numbers of arguments . \n" ) ;
e x i t ( EXIT_FAILURE ) ;
}
for ( i = 1 ; i <= 17; i ++)
a r r [ i −1] = a t o i ( argv [ i ] ) ;
max = min = a r r [ 0 ] ;
for ( i = 0 ; i < 17; i ++)
{
i f (max < a r r [ i ] )
max = a r r [ i ] ;
i f (min > a r r [ i ] )
min = a r r [ i ] ;
sum = sum + a r r [ i ] ;
}
p r i n t f ( "The maximum i s : %d\n" , max ) ;
p r i n t f ( "The minimum i s : %d\n" , min ) ;
p r i n t f ( "The average i s : %f \n" , ( f l o a t )sum/ argc ) ;
}

12.2.4 Input and Output

Figure 139: Maximum, minimum and average of the given list of elements.

152
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.

153
12.3.2 Flowchart

Figure 140: Reverse elements of an odd and even sized arrays.

154
12.3.3 C Source Code

#include < s t d i o . h>


#include < s t d l i b . h>
void reverse ( int * p , int n ) ;
void main( int argc , char * argv [ ] ) {
int i , a r r [ 2 0 ] ;
i f ( argc < 2 ) {
p r i n t f ( " I n v a l i d numbers of arguments . \n" ) ;
e x i t ( EXIT_FAILURE ) ;
}
for ( i = 1 ; i < argc ; i ++)
a r r [ i −1] = a t o i ( 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 ++)
p r i n t f ( "%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.

155
13.1 Text Books
13 References
S ECTION

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.

156
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/

157

You might also like