Learn Programming With C_Self-Practice Book for Learning
Learn Programming With C_Self-Practice Book for Learning
com
Learn Programming with C
Authored by two standout professors in the feld of Computer Science and Technology
with extensive experience in instructing, Learn Programming with C: An Easy Step-by Step
Self-Practice Book for Learning C is a comprehensive and accessible guide to programming
with one of the most popular languages.
Meticulously illustrated with fgures and examples, this book is a comprehensive
guide to writing, editing, and executing C programs on diferent operating systems and
platforms, as well as how to embed C programs into other applications and how to create
one’s own library. A variety of questions and exercises are included in each chapter to test
the readers’ knowledge.
Written for the novice C programmer, especially undergraduate and graduate students,
this book’s line-by-line explanation of code and succinct writing style makes it an excellent
companion for classroom teaching, learning, and programming labs.
Sazzad M.S. Imran, Ph.D., is Professor in the Department of Electrical and Electronic
Engineering, University of Dhaka, Bangladesh. He completed his B.Sc. and M.S. degrees in
Applied Physics, Electronics & Communication Engineering from the University of Dhaka
and received his Ph.D. degree from the Optical Communication Lab of the Kanazawa
University, Japan. Dr. Imran has vast experience in teaching C/C++, Assembly Language,
MATLAB®, PSpice, AutoCAD, etc., at the university level (more at sazzadmsi.webnode.
com).
ProgReference.com
ProgReference.com
Learn Programming with C
An Easy Step-by-Step Self-Practice Book
for Learning C
ProgReference.com
MATLAB® is a trademark of The MathWorks, Inc. and is used with permission. The MathWorks does not warrant the
accuracy of the text or exercises in this book. This book’s use or discussion of MATLAB® software or related products
does not constitute endorsement or sponsorship by The MathWorks of a particular pedagogical approach or particular
use of the MATLAB® software.
First edition published 2024
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431
and by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
CRC Press is an imprint of Taylor & Francis Group, LLC
© 2024 Prof. Sazzad M.S. Imran, Ph.D. and Prof. Md Atiqur Rahman Ahad, Ph.D.
Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot
assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize to
copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been
acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or
utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including
photocopying, microfilming, and recording, or in any information storage or retrieval system, without written
permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the
Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978–750–8400. For works that
are not available on CCC please contact [email protected]
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for
identification and explanation without intent to infringe.
Library of Congress Cataloging-in-Publication Data
Names: Imran, Sazzad, author. | Ahad, Md. Atiqur Rahman, author.
Title: Learn programming with C / Prof. Sazzad Imran, Ph.D, and Prof. Md. Atiqur Rahman Ahad, Ph.D.
Description: First edition. | Boca Raton, FL : CRC Press, 2024. | Includes bibliographical references and index. |
Summary: “Authored by two standout professors in the fields of Computer Science and Technology with
extensive experience in instructing, Learn Programming with C is a comprehensive and accessible guide to
programming with one of the most popular languages. Meticulously illustrated with figures and examples, this
book is a comprehensive guide to writing, editing and executing C programs on different operating systems and
platforms, as well as how to embed C programs into other applications and how to create one’s own library.
A variety of questions and exercises are included in each chapter to test the readers’ knowledge Written for the
novice C programmer, especially undergraduate and graduate students, this book’s line-by-line explanation of
code and succinct writing style makes it an excellent companion for classroom teaching, learning and
programming labs”—Provided by publisher.
Identifiers: LCCN 2023033790 (print) | LCCN 2023033791 (ebook) | ISBN 9781032299082 (hbk) |
ISBN 9781032283555 (pbk) | ISBN 9781003302629 (ebk)
Subjects: LCSH: C (Computer program language). | Computer programming.
Classification: LCC QA76.73.C15 I47 2024 (print) | LCC QA76.73.C15 (ebook) | DDC 005.13/3—dc23/eng/20231026
LC record available at https://lccn.loc.gov/2023033790
LC ebook record available at https://lccn.loc.gov/2023033791
ISBN: 9781032299082 (hbk)
ISBN: 9781032283555 (pbk)
ISBN: 9781003302629 (ebk)
DOI: 10.1201/9781003302629
Typeset in Minion
by Apex CoVantage, LLC
Access the Support Material: www.routledge.com/learn-programming-with-c/ahad/p/book/9781032299082
ProgReference.com
Contents
Preface, xi
CHAPTER 1 ◾ Introduction 1
1.1 HISTORY OF PROGRAMMING LANGUAGE 1
1.2 DIFFERENT TYPES OF PROGRAMMING LANGUAGE 2
1.3 IMPORTANCE OF PROGRAMMING 3
1.4 C PROGRAM STRUCTURE 3
1.5 STEP-BY-STEP TUTORIAL TO RUN A C PROGRAM 5
1.6 KEYWORDS 7
1.7 IDENTIFIERS 7
1.8 OPERATORS 8
1.9 OPERATOR PRECEDENCE IN C 9
1.10 VARIABLES 9
1.11 CONSTANTS 10
1.12 ESCAPE SEQUENCES 10
1.13 DATA TYPES 10
1.14 TYPE CASTING 11
1.15 EXAMPLES 12
EXERCISES 26
– MCQ with Answers 26
– Questions with Short Answers 37
– Problems to Practice 44
ProgReference.com
vi ◾ Contents
ProgReference.com
Contents ◾ vii
EXERCISES 294
– MCQ with Answers 294
– Questions with Short Answers 296
– Problems to Practice 299
ProgReference.com
viii ◾ Contents
ProgReference.com
Contents ◾ ix
PROJECT-13 560
PROJECT-14 560
PROJECT-15 560
PROJECT-16 560
PROJECT-17 560
PROJECT-18 561
PROJECT-19 561
PROJECT-20 561
PROJECT-21 561
PROJECT-22 561
INDEX, 563
ProgReference.com
ProgReference.com
Preface
xi
ProgReference.com
xii ◾ Preface
In conclusion, this book is a guided self-study for those interested in learning C by fol-
lowing a detailed, tutorial-type problem-solving book. We feel that it is a great book for
teachers to cover as a textbook for C programming language.
ProgReference.com
CHAPTER 1
Introduction
DOI: 10.1201/9781003302629-1 1
ProgReference.com
2 ◾ Learn Programming with C
Smalltalk in 1972. Leafy, Logitech, and CrowdStrike were among the companies that used
it. In the same year, Dennis Ritchie created C for use with the Unix operating system at Bell
Telephone Laboratories. C is the basis for several modern languages, including C#, Java,
JavaScript, Perl, PHP, and Python. In 1972, IBM researchers Raymond Boyce and Donald
Chamberlain created SQL, which stood for Structured Query Language. It is a program
that lets you explore and edit data stored in databases.
Afer mathematician Ada Lovelace, Ada was created in 1980–1981 by a team directed
by Jean Ichbiah of CUU Honeywell Bull. Ada is an organized, statically typed, imperative,
wide-spectrum, and object-oriented high-level programming language used for air trafc
control systems. Bjarne Stroustrup created C++ afer modifying the C language at Bell
Labs in 1983. C++ is a high-performance programming language used in Microsof Ofce,
Adobe Photoshop, game engines, and other high-performance sofware. Brad Cox and
Tom Love created the Objective-C programming language in 1983 to construct sofware
for macOS and iOS. Larry Wall designed Perl in 1987 as a general-purpose, high-level pro-
gramming language for text editing.
Haskell, a general-purpose programming language, was created in 1990 to deal with
complex calculations, records, and number crunching. Guido Van Rossum created the
general-purpose, high-level programming language Python in 1991, and it is used by
Google, Yahoo, and Spotify. Visual Basic is a programming language created by Microsof
in 1991 that allows programmers to use a graphical user interface and is used in vari-
ous applications such as Word, Excel, and Access. Yukihiro Matsumoto designed Ruby
in 1993 as an interpreted high-level language for web application development. James
Gosling designed Java in 1995 as a general-purpose, high-level programming language
with cross-platform capabilities. Rasmus Lerdorf created the hypertext preprocessor PHP
in 1995 to create and maintain dynamic web pages and server-side applications. Brendan
Eich wrote JavaScript in 1995 for desktop widgets, dynamic web development, and PDF
documents.
Microsof created C# in 2000 by combining the computing power of C++ with the sim-
plicity of Visual Basic. Almost every Microsof product currently uses C#. In 2003, Martin
Odersky created Scala, which combines functional mathematical and object-oriented pro-
gramming. Scala is a Java-compatible programming language that is useful in Android
development. In 2003, James Strachan and Bob McWhirter created Groovy, a concise and
easy-to-learn language derived from Java. Google created Go in 2009, and it has since
gained popularity among Uber, Twitch, and Dropbox. Apple created Swif in 2014 to
replace C, C++, and Objective-C for desktop, mobile, and cloud applications.
ProgReference.com
Introduction ◾ 5
arguments or parameters afer the function name, they are enclosed in parentheses; other-
wise, they are lef empty. Te body of the main() function is comprised of all the statements
between the opening and closing curly braces.
Write C-Program (or any name of your choice) on the ‘Project title:’ and choose the
folder (for example, C:\Users\SazzadImran\Desktop\) where you want to create the
project. Click Next>→Finish. A project or folder is created on the desktop.
ProgReference.com
6 ◾ Learn Programming with C
Step-3: Double click on C-Program on Workspace to select the project and click
File→New→Empty fle→Yes. Write a fle name of your choice (Example-1, for example)
and click Save.
An empty fle name Example-1.c is created and saved in the C-Program folder.
Step-4: Write your C program codes on the fle Example-1.c and save the fle.
ProgReference.com
Introduction ◾ 7
Step-5: Click Build→‘Compile current fle’ to compile the program. Correct any error(s)
or warning(s) on the codes. Correcting the errors is a must though it is optional to
correct the warnings. Recompile the program until we get 0 error(s) and 0 warning(s).
Step-6: Click Build→‘Build and run’ to execute the program. Te output screen will look
as follows:
1.6 KEYWORDS
In C programming, 32 reserved words have special meaning to compilers and are utilized
as a part of the syntax. Tese terms cannot be used as names or identifers for variables. Te
list of reserved C keywords is as follows:
auto, break, case, char, const, continue, default, do, int, long, register, return, short,
signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while, double,
else, enum, extern, foat, for, goto, if.
1.7 IDENTIFIERS
Variables, functions, structures, and other objects in a program are given unique names
called identifers. For example, in the statement of the preceding demo program
int age;
int is a keyword and age is an identifer assigned to a variable by the compiler to iden-
tify the entity uniquely. When naming an identifer, the following guidelines should be
observed.
(1) A valid identifer can include uppercase and lowercase letters, numbers, and
underscores.
(2) Te frst character cannot be a digit.
(3) We cannot use any keyword as an identifer.
(4) Te length of the identifer is unlimited.
1.8 OPERATORS
In C, operators are symbols that perform operations on values or variables. Tere is a rich
set of operators used in C programming.
C arithmetic operators are as follows:
+ (addition)
− (subtraction)
* (multiplication)
/ (division) and
% (modulus or remainder of division)
= (a = b)
+= (a += b → a = a + b)
−=
*=
/= and
%=
== (equal to, a == b)
> (greater than)
< (less than)
!= (not equal to)
>= (greater than or equal to) and
<= (less than or equal to)
ProgReference.com
Introduction ◾ 9
&& (AND)
|| (OR) and
! (NOT)
& (AND)
| (OR)
^ (EX-OR)
<< (shif lef) and
>> (shif right)
(1) *, /, %
(2) +, −
(1) &&
(2) ||
(3) !
Te operators && and || have lef-to-right associativity, while ! has right-to-lef associativity.
1.10 VARIABLES
When a variable is declared in a C program, it refers to a memory storage space where the
data is held. Te value of a variable can be altered, but its data type cannot be changed once
it has been declared, but type conversion is permitted in a mathematical expression. For
example, in the statement
int age;
ProgReference.com
10 ◾ Learn Programming with C
age is a variable name that holds any integer type data in a fxed position in memory. Te
same rules apply to naming variables as they do to naming identifers.
1.11 CONSTANTS
If we want to keep the value of a variable constant or fxed, we can use the term const before
the variable’s data type. As a result, the variable is now a symbolic constant. For example, PI is
a symbolic constant whose value cannot be changed in the program in the following statement:
\b (backspace)
\f (form feed)
\n (newline)
\r (return)
\t (horizontal tab)
\v (vertical tab)
\\ (backslash)
\’ (single quotation mark)
\” (double quotation mark)
\? (question mark) and
\0 (null character)
ProgReference.com
Introduction ◾ 11
foat [%f]
double [%lf]
short int [%hd]
unsigned int [%u]
long int [%ld, %li]
long long int [%lld, %lli]
unsigned long int [%lu]
unsigned long long int [%llu]
signed char [%c]
unsigned char [%c]
long double [%Lf]
int, foat, double, char, and void are the basic data types,
short and long can be used as a type specifer, and
signed and unsigned as type modifers.
void is used as a return type when a function does not return anything; nevertheless, it
does not create variables.
(1) Implicit: In this situation, the compiler casts the values of distinct data types in an
expression to a common type, which is the highest hierarchy.
int → unsigned int → long → unsigned long → long long → unsigned long long → foat
→ double → long double
Example:
Here, because foat data type is higher in the hierarchy between foat and int, the arithme-
tic expression total/count gives a foat value.
ProgReference.com
12 ◾ Learn Programming with C
(2) Explicit: In this situation, the programmer uses the cast operator to explicitly
change values of one type to another. Te syntax is as follows:
(type_name) expression
Example:
First, the total is transformed from an int to a foat, and then division is performed. Because
total has been converted to foat and count has been changed to int, the result is a decimal
value because foat is higher in the hierarchy than int data type.
1.15 EXAMPLES
PROBLEM-01
Write a program to print the sentence “Hello! Atiqur Rahman! How are you?” on the
screen.
ProgReference.com
Introduction ◾ 13
PROBLEM-02
Write a program to input an integer and then print the integer value.
ProgReference.com
14 ◾ Learn Programming with C
PROBLEM-03
Write a program that enters two integer values and displays the summation on the screen.
ProgReference.com
Introduction ◾ 15
ProgReference.com
16 ◾ Learn Programming with C
PROBLEM-04
Write a program that will input two foating-point numbers and then display the
product on the screen.
ProgReference.com
Introduction ◾ 17
prod = num1*num2;
/*numa1 is multiplied by num2 and the result is assigned to
variable prod*/
printf("Product of %0.2lf and %0.2lf is: %0.2lf", num1, num2,
prod);
/*printf() function displays the text inside the double
quotations as it is on the screen, with the exception that
the value of num1 replaces the first format specifier %0.2lf,
value of num2 replaces the second %0.2lf, and the value of prod
replaces the third %0.2lf; the format specifier 0.2lf specifies
that the number is displayed with a precision of two decimal
points*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-05
Write a program to input two integers and show the result of the division.
ProgReference.com
18 ◾ Learn Programming with C
ProgReference.com
Introduction ◾ 19
PROBLEM-06
Write a program to calculate the area and circumference of a circle.
ProgReference.com
20 ◾ Learn Programming with C
PROBLEM-07
Write a program that calculates the power of a given number.
ProgReference.com
Introduction ◾ 21
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-08
Write a program to fnd the size of the data types int, foat, double, and char.
ProgReference.com
Introduction ◾ 23
float type2;
/*float type variable type2 is declared*/
double type3;
/*double type variable type3 is declared*/
char type4;
/*character type variable type4 is declared*/
printf("Size of int data type is: %d byte\n", sizeof(type1));
/*sizeof(type1) returns the size of variable type1 in bytes, that is
displayed on the screen in place of format specifier %d; other text
in the quotes is displayed as it is except for a newline replaces \n*/
printf("Size of float data type is: %d byte\n", sizeof(type2));
/*sizeof(type2) returns the size of variable type2 in bytes,
that is displayed on the screen in place of format specifier
%d; other text in the quotes is displayed as it is except for
a newline replaces \n*/
printf("Size of double data type is: %d byte\n", sizeof(type3));
/*sizeof(type3) returns the size of variable type3 in bytes,
that is displayed on the screen in place of format specifier
%d; other text in the quotes is displayed as it is except for
a newline replaces \n*/
printf("Size of char data type is: %d byte", sizeof(type4));
/*sizeof(type4) returns the size of variable type4 in bytes,
that is displayed on the screen in place of format specifier
%d; other text in the quotes is displayed as it is except for
a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-09
Write a program that swaps two numbers.
ProgReference.com
24 ◾ Learn Programming with C
ProgReference.com
Introduction ◾ 25
num2 = temp;
/*the value of temp=num1 is assigned to num2*/
printf("After swapping:\n\tFirst number = %0.2f\n", num1);
/*this printf() function displays the text in double quotations
as it is on the screen except for a tab replaces \t, a newline
replaces \n, value of num1 replaces format specifier %0.2f with
two decimal points precision*/
printf("\tSecond number = %0.2f", num2);
/*this printf() function displays the text in the double quotes
as it is on the screen except for a tab replaces \t and the
value of num2 replaces format specifier %0.2f with two decimal
points precision*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-10
Write a program that displays the ASCII number of a character entered by the user.
ProgReference.com
26 ◾ Learn Programming with C
int main(){
/*all C program must have a main() function with return type void
or int; here there is no parameter of the main() function and it
returns an integer; opening curly brace specifies start of the
main() function and no statement before that curly brace is executed
by the compiler*/
char ch;
/*char type variable ch is declared that stores only character*/
printf("Please enter a character: ");
/*this displays the text inside the double quotations as it is
on the output screen*/
scanf("%c", &ch);
/*this reads a character from input terminal and assigns the
character to ch*/
printf("ASCII code of %c is %d.", ch, ch);
/*this printf() function displays the text in double quotations
as it is on the screen except for character ch replaces format
specifier %c and the ASCII code of that character ch replaces
format specifier %d*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
EXERCISES
ProgReference.com
Introduction ◾ 27
ProgReference.com
28 ◾ Learn Programming with C
ProgReference.com
Introduction ◾ 29
B) 34
C) 62
D) 64
15) Each statement in a C program should end with a
A) Semicolon (;)
B) Colon (:)
C) Period/dot (.)
D) None of the above
16) Which of the following is not a valid identifer?
A) _atiqahad
B) 2atiqahad
C) atiq_ahad
D) atiqahad2
17) How many bytes are occupied by void in memory?
A) 0
B) 1
C) 2
D) 4
18) What is the range of signed char?
A) −128 to +127
B) 0 to 255
C) −128 to −1
D) 0 to +127
19) What is the range of unsigned char?
A) −128 to +127
B) 0 to 255
C) −128 to −1
D) 0 to +127
ProgReference.com
30 ◾ Learn Programming with C
ProgReference.com
Introduction ◾ 31
C) Garbage
D) Null
26) Variable that are declared but not initialized contains_______.
A) 0
B) Blank space
C) Garbage
D) None of the above
27) What are the sizes of foat, double, and long double in bytes?
A) 4, 8, 16
B) 4, 8, 10
C) 2, 4, 6
D) 4, 6, 8
28) What is the range of signed long variables?
A) −231−1 to +231
B) 0 to +232
C) −231 to +231−1
D) 0 to 232−1
29) What is the range of unsigned long variables?
A) −231−1 to +231
B) 0 to +232
C) −231 to +231−1
D) 0 to 232−1
30) Which of the following does not store a sign?
A) short
B) int
C) long
D) byte
31) Which is the only function all C programs must contain?
A) getch()
ProgReference.com
32 ◾ Learn Programming with C
B) main()
C) printf()
D) scanf()
ProgReference.com
Introduction ◾ 33
ProgReference.com
34 ◾ Learn Programming with C
B) % > * > /
C) % =/> *
D) % =/= *
43) What is the priority among operators (*, /, %), (+, −), and (=) in C language?
A) (*, /, %) > (+, −) < (=)
B) (*, /, %) < (+, −) < (=)
C) (*, /, %) > (+, −) > (=)
D) (*, /, %) < (+, −) (+, −) = (=)
44) Te result of a logical or relational expression in C is
A) True or false
B) 0 or 1
C) 0 if the expression is false and any positive number if the expression is true
D) None of the mentioned
45) Which of the following is not a logical operator?
A) &
B) &&
C) ||
D) !
46) Expand or abbreviate ASCII in C language.
A) Australian Standard Code for Information Interchange
B) American Standard Code for Information Interchange
C) American Symbolic Code for Information Interchange
D) Australian Symbolic Code for Information Interchange
47) Which of the following statement output “hello world.”?
A) scanf(“hello world.”);
B) printf(“hello world”);
C) scan(“hello world.”);
D) print(“hello world.”);
ProgReference.com
Introduction ◾ 35
ProgReference.com
36 ◾ Learn Programming with C
C) Long
D) double
54) Which of the following is an invalid header fle in C?
A) math.h
B) mathio.h
C) string.h
D) ctype.h
55) Which of the following operators has the highest precedence?
A) unary
B) shif
C) equality
D) postfx
56) sizeof() is a _______.
A) Function
B) Variable
C) Both A and B
D) Operator
57) Which operator is known as ternary operator?
A) ::
B) ;
C) ?:
D) :
58) What is the value of x in the following C statement?
int x = 7%4*3/2;
A) 4
B) 1
C) 3
D) 0
ProgReference.com
Introduction ◾ 37
[Ans. C, C, C, A, B, D, D, D, A, B, D, A, A, A, A, B, A, A, B, A, B, A, C, C, A, C, B, C, D, D,
B, B, A, B, A, A, C, B, B, A, D, D, C, B, A, B, B, B, C, D, A, D, D, B, D, D, C, A, D]
ProgReference.com
38 ◾ Learn Programming with C
ProgReference.com
Introduction ◾ 39
ProgReference.com
40 ◾ Learn Programming with C
ProgReference.com
Introduction ◾ 41
ProgReference.com
42 ◾ Learn Programming with C
Ans. Te modulus operator (%) is an arithmetic operator that yields the remainder
of an integer division.
33) What is the remainder for 5.0%2?
Ans. Because the modulus operator can only be used for integer division, and one
of the operands for the above % operator is a real value, it would be an invalid
operation.
34) What is type casting?
Ans. Converting one data type to another is known as typecasting or type conver-
sion. It can be either implicit (done automatically by the compiler) or explicit (done
by the user). When an expression has multiple data types, implicit type casting is
used. Type conversion is performed to avoid any data loss.
35) What is constant?
Ans. Constants are fxed values that cannot be altered while the program is run-
ning. Constants can be int, foat, char, or any other basic data type.
36) Defne modifer? What are the modifers available in C?
Ans. Modifers are C keywords that increase or decrease the amount of memory
space assigned to a variable. Tey are prefxed with basic data types. Short, long,
signed, and unsigned are the four modifers used in C.
37) Is it possible to use curly braces to enclose a single statement?
Ans. Tere is no error if a single statement is enclosed in curly braces, and the pro-
gram compiles and runs fne. Curly braces, on the other hand, are most commonly
employed to enclose a set of multiple statements or lines of code.
38) Describe the escape sequence with an example.
Ans. In C, an escape sequence is a set of characters that do not represent themselves
but are instead transformed into another character or set of characters. It consists
of a backslash (\) and one or more letters that represent the escape sequence. Te
character \n, for example, is an escape sequence that represents a newline character.
39) How do we construct an increment or decrement statement?
Ans. Te increment operator ++ and the decrement operator can create an incre-
ment or decrement statement. Both can be used as a prefx (++x, −−x) or postfx
(x++, x−−) with variables.
40) What are the diferences between sum++ and ++sum, where the sum is an integer
type variable?
Ans. sum++ is a postfx operator, which means that the expression is evaluated frst
with the current sum value. Ten the sum value is increased by 1. ++sum, on the
ProgReference.com
Introduction ◾ 43
other hand, is a prefx operator that signifes the sum value is increased by 1 before
the expression is evaluated with the new sum value.
41) What are the diferent categories of C operators in terms of operand numbers?
Ans. Tree categories of operators in C language are as follows:
i) Unary: Operators operate on a single operand. Example: sizeof(), ++,−−, etc.
ii) Binary: Operators operate on two operands. Example: +,−, =, *, /, %, ==, >, <=, etc.
iii) Ternary: Operators operate on three operands. ?: is the only C ternary operator.
42) Can we use int data type to store the value 32768? Why?
Ans. Because the int data type can only store values from −32768 to 32767 (−215 to
215−1), it cannot be used to store the value 32768. To store the value 32768, we can
use unsigned int or long in.
43) What is wrong in the statement- “scanf(“%d”, num);”?
Ans. scanf() is a built-in library function that reads a value of a specifc data type from
the standard input terminal and stores it in the memory locations reserved for the
corresponding variable. As a result, the variable name num must be preceded by the
address operator &. Terefore, the preceding statement results in a run-time error.
44) Te % symbol has particular use in printf() statement. How would we output this
character on the screen?
Ans Te printf() function can be used to display the % symbol by using %%. For
example, to have the output appear as 80% on the screen, write printf(“80%%”);
45) What does the format %5.2 mean when included in printf() statement?
Ans. Tis format is employed for two purposes. To begin with, place 5 before the
decimal point to specify the number of spaces for the output number. Te second
integer following the decimal point is used to specify how many decimal places
the output number should have. Additional space characters are introduced if the
number of spaces flled by the output number is less than 5.
46) What is the purpose of the keyword typedef?
Ans. Te keyword typedef is used to create a new name to an existing type or sim-
plify a type’s complex declaration. It does not result in the creation of a new data
type. For instance, afer following the type defnition
typedef unsigned long int byte;
the identifer byte can be used as an abbreviation for the type unsigned long int,
such as
byte x; is equivalent to declaring unsigned long int x;
ProgReference.com
44 ◾ Learn Programming with C
Ans. In C, %i is a valid format specifer that serves the same purpose as %d. As a
result, the program above will display 17 on the screen.
48) What should be the output of the following program?
void main(){
int a=10/3;
printf("%d", a);}
Ans. Instead of 3.33, the program displays 3 on the screen. Te decimal part is dis-
carded because the result of integer division (int/int) is simply an int.
49) What should be the output of the following program?
void main(){
int a=40, b=50;
printf("%d, %d, ", a++, b−−);
printf("%d, %d", ++a,−−b);}
Problems to Practice
1) Write a program to print the sentence “Hello! Atiqur Rahman! How are you?” on
the screen.
2) Write a program to input an integer and then print the integer value.
3) Write a program that enters two integer values and displays the summation on the
screen.
ProgReference.com
Introduction ◾ 45
4) Write a program that will input two foating-point numbers and then display the
product on the screen.
5) Write a program to input two integers and show the result of the division.
6) Write a program to calculate the area and circumference of a circle.
7) Write a program to calculate the power of a number.
8) Write a program to fnd the size of the data types int, foat, double, and char.
9) Write a program that swaps two numbers.
10) Write a program to display the ASCII code of a character entered by the user.
11) Write a program to display the ASCII codes of consecutive ten characters where the
starting character is entered by the user.
12) Write a program to display your name, date of birth, and mobile number.
13) Write a program to print a block F using hash (#), where the F has a height of seven
characters and width of fve and four characters.
14) Write a program to compute the perimeter and area of a circle with a radius of 6
inches.
15) Write a program that reads no. of days and converts it into years, weeks, and days.
16) Write a program that reads and converts Centigrade to Fahrenheit.
17) Write a program to input an employee’s ID, total worked hours in a day, and the
amount he received per hour. Print the employee’s ID and monthly salary with two
decimal places.
18) Write a program to input the coordinates of two points and calculate the distance
between them.
19) Write a program to generate a random number.
20) Write a program to calculate perimeter of a rectangle. Take sides a and b from the
user.
21) Take a number n from the user and display its cube.
22) Write a program to display the average of any three numbers. Take the numbers
from the user.
ProgReference.com
CHAPTER 2
Flow Control
F low control refers to the sequence in which individual function calls, instruc-
tions, or statements are executed when a program is running. Based on the output of an
expression, a decision is made on which of the several paths to pursue using a control flow
statement. Branching and looping are the two types of control flow available in C.
2.1 IF STATEMENT
The statements inside the body of the “if” are executed only if the condition is true. If the
condition is false, the “if” statement’s body is skipped, and normal execution resumes after
the body. Structure of if statement is as follows:
if (conditions){
//blocks of valid C statements
//these statements are executed if the conditions
//return true or 1
}
//valid C statements
46 DOI: 10.1201/9781003302629-2
ProgReference.com
Flow Control ◾ 47
if (conditions){
//blocks of valid C statements
//these statements are executed if the conditions
//return true or 1
}
else{
//blocks of valid C statements
//these statements are executed if the conditions
//return false or 0
}
//valid C statements
Using opening and closing curly braces is optional if the body of the “if” or “else” includes
a single sentence.
if (condition1){
//blocks of valid C statements
ProgReference.com
48 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 49
same operation in a single statement. It is also known as the ternary operator because
it operates on three operands. It helps in the quickest possible writing of the if..else
statement.
Syntax of the conditional operator is as follows:
Using if..else statement, the ternary operator (?:) can be visualized as follows:
if (expression1)
variable = expression2;
else
variable = expression3;
Example:
ProgReference.com
50 ◾ Learn Programming with C
Example:
Variation-1: Te initialization part can be skipped and declared before the “for” loop
begins. Example:
Variation-2: Te increment or decrement part of the loop can be skipped and done within
the body of the “for” loop. Example:
Variation-3: In the “for” loop, it is allowed to use multiple initializations, conditions, and/
or increments or decrements. Example:
ProgReference.com
Flow Control ◾ 51
Nested for loop: Any valid for loop is allowed to use inside another for loop.
Example:
Note: If condition in the “for” loop can never be false or always returns 0, it is an infnite
loop and using such a condition is a logical error. Example:
initialization;
while (conditions){
//blocks of valid C statements
//statements are executed repeatedly as long as
//the conditions are true
increment or decrement;
}
ProgReference.com
52 ◾ Learn Programming with C
Example:
initialization;
do{
//blocks of valid C statements
//statements are executed repeatedly as long as
//the conditions are true
increment or decrement;
}while (conditions);
Example:
ProgReference.com
Flow Control ◾ 53
(1) Te condition is checked frst in a while loop before the statements in the body are
executed. Whereas the condition is checked afer the loop’s body is executed in a
do..while loop.
(2) Te statements in the body of the do..while loop are executed at least once, even if
the condition is false. In contrast, the statements in the body of the while loop are
never executed if the condition is false.
(3) A semicolon is used afer while (condition) in the do..while loop and no semicolon
is used afer while (condition) in the while loop.
ProgReference.com
54 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 55
goto label_name;
//block-1 of valid C statements
label_name:
//block-2 of valid C statements
/*statements are executed as soon as the above goto is encountered, skipping the
block-1 statements*/
ProgReference.com
56 ◾ Learn Programming with C
2.12 EXAMPLES
PROBLEM-01
Write a program to check whether a given number is positive or negative.
ProgReference.com
Flow Control ◾ 57
scanf("%d", &num);
/*when a value is entered from input terminal, the scanf()
function assigns it to num; the address operator, which must be
used before the variable name since the input value is placed
in the memory location allocated for that variable*/
if (num>=0)
/*if num is greater than or equal to zero then it is true or 1,
and the following statement is executed*/
printf("%d is a positive number.", num);
/*this printf() displays the text inside the quotations
as it is on the screen except for the value of num is
replaces the format specifier %d; as there is only one
statement in the body of if loop no curly brace is
required*/
else
/*if the above condition is false, then the following statement
is executed*/
printf("%d is a negative number.", num);
/*printf() function displays the text inside the quotations
as it is on the screen except for the value of num is
replaces %d; as there is only one statement in the body
of else loop, no curly brace is required*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-02
Write a program to check whether a number is even or odd.
ProgReference.com
58 ◾ Learn Programming with C
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-03
Write a program to check whether a character is an alphabet or not.
scanf("%c", &ch);
/*input function scanf() reads a character from the input
terminal and assigns the character to ch*/
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch<= 'Z'))
/*first two conditions check if the ch is a small letter;
the last two conditions check whether the ch is a capital
letter; if ch is either a small letter or a capital letter
above expression returns true=1 and the following statement is
executed*/
printf("%c is an alphabet.", ch);
/*this printf() function displays %c is an alphabet
with the value of ch replaces the format specifier %c*/
else
/*if ch is neither a small letter nor a capital letter above
expression of 'if' returns false = 0 and following statement is
executed*/
printf("%c is not an alphabet.", ch);
/*printf() function displays the text inside double
quotations as it is on the screen except for the
character ch replaces the format specifier %c*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-04
Write a program to count the number of digits in an integer.
ProgReference.com
Flow Control ◾ 61
ProgReference.com
62 ◾ Learn Programming with C
PROBLEM-05
Write a program to generate and display multiplication table of a number entered
by user.
ProgReference.com
Flow Control ◾ 63
ProgReference.com
64 ◾ Learn Programming with C
PROBLEM-06
Write a program to determine and display the sum of the following harmonic series
for a given value of n.
1 1 1
1+ + + +
2 3 n
Step-1: Start
Step-2: Initialize sum←0
Step-3: Read value of n
ProgReference.com
Flow Control ◾ 65
ProgReference.com
66 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 67
sum=sum+(1/(float)i);
/*in each iteration of the loop, the type of i is converted
to float from int, so that 1/i gives a decimal value;
this action sequentially adds 1/1, 1/2, 1/3, . . . to the
sum*/
if (n>5)
/*if n>5 then the condition is true and following statement is
executed*/
printf("1 + 1/2 + 1/3 + . . . ");
/*this printf() function displays the text inside the
double quotations as it is on the screen*/
else{
/*statements in the body of else, enclosed by curly braces, are
executed if the condition of 'if' is false, that is, n<=5*/
printf("1");
/*output function printf() displayes 1 on the screen*/
for (j=2; j<n; j++)
/*j=2 is initialization, i<=n is condition and i++ is
increment; initialization is done once at the beginning
of the loop; then the condition is checked, and if it is
true, the statement in the body is executed; the value of
j is incremented by 1 before the condition is re-checked;
these procedures are repeated until the condition is no
longer true at which point the program flow exits the
loop*/
printf(" + 1/%d", j);
/*printf() function displays the text inside the double
quores as it is on the screen except for the value of j
replaces the format specifier %d*/
}
/*this closing curly brace specifies the end of else*/
printf(" + 1/%d = %0.2f\n", n, sum);
/*the printf() function displays the text in the double-quotes
as it is on the screen, with the exception that the value of n
replaces the format specifier %d, the value of sum replaces the
format specifier %0.2f with two decimal points precision, and
a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
ProgReference.com
68 ◾ Learn Programming with C
PROBLEM-07
Write a program to fnd the number and sum of all integers greater than 100 and less
than 200 divisible by 7.
Step-1: Start
Step-2: Initialize num←0, sum←0 and i←101
Step-3: If i<200
ProgReference.com
Flow Control ◾ 69
3.1: If i%7=0
3.1.1: num←num+1
3.1.2: sum←sum+i
3.2: i←i+1
3.3: Go to Step-3
Step-4: Display values of num and sum
Step-5: Stop
ProgReference.com
70 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 71
PROBLEM-08
Write a program to compute the roots of a quadratic equation:
ax 2 + bx + c = 0
Te program should request the values of the constants a, b, and c and display the values
of the roots.
Flowchart of the Solution:
Figure 2.3 shows the fowchart followed to solve this problem.
ProgReference.com
72 ◾ Learn Programming with C
Step-1: Start
Step-2: Read values of a, b, and c
Step-3: If a=0
3.1: If b=0
3.1.1: Display ‘no solution’
3.1.2: Go to Step-9
3.2: Display value of -c/b
3.3: Go to Step-9
Step-4: If b2−4ac<0
4.1: x1←−b/2a
4.2: x2←(4ac-b2)/2a
4.3: Display x1+ix2
4.4: Display x1−ix2
4.5: Go to Step-9
Step-5: If b2−4ac=0
4.6.1: Display value of -b/2a
4.6.2: Go to Step-9
Step-6: x1←(−b+(b2−4ac))/2a
Step-7: x2←(−b−(b2−4ac))/2a
Step-8: Display values of x1 and x2
Step-9: Stop
ProgReference.com
Flow Control ◾ 73
ProgReference.com
74 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 75
}
/*this is the end of first if statement with the condition
(a==0)*/
else if ((b*b−4*a*c)<0){
/*if a≠0, then this else if condition is checked; if b2−4ac<0,
the statements in the body of 'else if' enclosed with curly
braces are executed*/
x1=−b/(2*a);
/*first multiplication operation inside first brackets and
then the division operation are done, the result is assigned
to x1*/
x2=sqrt(4*a*c−b*b)/(2*a);
/*sqrt() function returns the square root value of its
argument 4ac−b2, this value is divided by 2a and the result
is assigned to x2*/
printf("Two imaginary roots of the equation are:\n");
/*output function printf() displays the text inside the
double quotations as it is on the screen except for a
newline \n*/
printf("(1) %0.2f+i%0.2f\n(2) %0.2f−i%0.2f\n", x1, x2, x1,
x2);
/*this printf() function displays the text inside the
double quotations as it is on the screen except for a
newline replaces \n; 1st and 3rd format specifiers %0.2f are
replaced by the values of x1 two decimal points precision
while 2nd and 4th %0.2f by the values of x2*/
}
/*this closing curly brace specifies the end of 'else if' with
condition b2−4ac<0*/
else if ((b*b−4*a*c)==0)
/*if a≠0 and b2−4ac≥0 then program flow jumps to this 'else if'
condition; if b2−4ac=0, then the statement in this 'else if'
body is executed*/
printf("The only root of the equation is: %0.2f\n",
−b/(2*a));
/*this printf() function displays the text inside double
quotations as it is on the screen except for the format
specifier %0.2f is replaced by the value of operation − b/2a
with two decimal points precision and a newline replaces
\n*/
else{
/*statements in the body of this else are executed only if all
the above conditions a==0, b2−4ac<0 and b2−4ac==0 are false*/
x1=(−b+sqrt(b*b−4*a*c))/(2*a);
/*sqrt() returns square root of its argument b2−4ac; result
of operation (−b+√(b2−4ac))/2a is assigned to x1*/
ProgReference.com
76 ◾ Learn Programming with C
x2=(−b−sqrt(b*b−4*a*c))/(2*a);
/*sqrt() returns square root of its argument b2−4ac; result
of operation (−b−√(b2−4ac))/2a is assigned to x1*/
printf("The roots of the equation are: %0.2f and %0.2f\n",
x1, x2);
/*this printf() function displays the text inside the double
quotes as it is on the screen except for a newline replaces
\n; 1st format specifier %0.2f is replaced by the value of
x1 with two decimal points precision while the 2nd %0.2f by
the value of x2*/
}
/*this closing curly brace specifies the end of else*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-09
Write a program to compute the sum of individual digits of a given positive integer
number.
ProgReference.com
Flow Control ◾ 77
Step-1: Start
Step-2: Initialize sum←0
Step-3: Read value of n
Step-4: If (num/10)≠0
4.1: sum←sum+num%10
4.2: num←num/10
4.3: Go to Step-4
Step-5: sum←sum+num
Step-6: Display value of sum
Step-7: Stop
ProgReference.com
78 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 79
PROBLEM-10
Develop a program to implement a calculator. The program should request the
user to input two numbers and display one of the following as per the desire
of the user (consider the operators “+”, “−”, “*”, “/”, “%” and use “switch”
statement):
ProgReference.com
80 ◾ Learn Programming with C
Step-1: Start
Step-2: Initialize ch←‘y’
Step-3: If ch≠‘n’
3.1: Read values of num1, num2, and op
3.2: If op=‘+’
3.2.1: Display value of num1+num2
3.2.2: Go to Step-3.6
3.3: If op=‘−’
3.3.1: Display value of num1−num2
3.3.2: Go to Step-3.6
ProgReference.com
Flow Control ◾ 81
3.4: If op=‘*’
3.4.1: Display value of num1×num2
3.4.2: Go to Step-3.6
3.5: If op=‘/’
3.5.1: If num2≠0
3.5.1.1: Display value of num1/num2
3.5.1.2: Go to Step-3.6
3.5.2: Display ‘cannot divide by zero’
3.6: Read value of ch (=y/n)
3.7: Display enter
3.8: Go to Step-3
Step-4: Stop
ProgReference.com
82 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 83
ProgReference.com
84 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 85
PROBLEM-11
A person has 10 vori gold, 25 vori silver, and tk 10,000.00 in cash. He also has tk
5,000.00 in debt, and he owes his cousin tk 7,500.00. Calculate the amount of money
he has to pay for piety tax this year. Piety tax is payable to the poor, 2.5% of total
wealth (gold, silver, cash, or any business items) one person has afer one lunar year if
his total wealth is more than 7.5 vori gold or 52.5 vori silver or its equivalent money
whichever is smaller.
Step-1: Start
Step-2: Read values of gold, silver, bank, cash, item, debt, owe, gdprice, and srprice
Step-3: nisab←gdprice×7.5
Step-4: If silver≠0
4.1: Go to Step-8.1
Step-5: If bank≠0
5.1: Go to Step-8.1
Step-6: If cash≠0
6.1: Go to Step-8.1
Step-7: If item≠0
7.1: Go to Step-8.1
ProgReference.com
86 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 87
Step-8: If owe≠0
8.1: If nisab>srprice×52.5
8.1.1: nisab←srprice×52.5
Step-9: Display value of nisab
Step-10: asset←gold×gdprice+silver×srprice+bank+cash+item+owe−debt
Step-11: Display value of asset
Step-12: If asset<nisab
12.1: Display ‘no piety-tax’
12.2: Go to Step-15
Step-13: zakat←asset×2.5/100
Step-14: Display value of zakat
Step-15: Stop
ProgReference.com
88 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 89
ProgReference.com
90 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 91
if (asset<nisab)
/*if value of asset is less than nisab amount then above condition
is true and following statement is executed*/
printf("You don't have to pay any piety-tax in this lunar"
"year.\n");
/*printf() function displays the text in the quotations as
it is on the screen except for a newline replaces \n*/
else{
/*if asset>=nisab then above condition is false, and following
statements, enclosed by curly braces, are executed*/
zakat=asset*2.5/100;
/*zakat or piety-tax amount of the person concerned is
calculated*/
printf("Payable piety-tax to poor in this year is %0.2f"
"taka.\n", zakat);
/*printf() function displays the text in the quotations as
it is on the screen except for the format specifier %0.2f
is replaced by the value of zakat with two decimal points
precision and a newline replaces \n*/
}
/*this closing curly brace specifies the end of else*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-12
A person gets a monthly salary of tk 60,000.00 with two festival allowances of
tk 80,000.00. He also gets tk 50,000.00 from monthly house rent. His average
monthly expenditure is tk 45,000.00, and he has to pay tk 5,000.00 for provident
fund and tk 10,000.00 for life insurance premium. He also has to pay tk 30,000.00
for City Corporation Tax for his apartment. Calculate the amount of income tax
he has to pay to the government in this year. The government fixes the tax for
this year as follows:
Income Tax
First tk 2,20,000.00 Nil
Next tk 3,00,000.00 10%
Next tk 4,00,000.00 15%
Next tk 5,00,000.00 20%
Rest amount 25%
Minimum payable tax is tk 3,000.00
ProgReference.com
92 ◾ Learn Programming with C
Provident funds, life insurance, and share investment are considered personal invest-
ments, and the taxpayer gets a 15% rebate on his total investment. Festival allowance
and other allowances are exempted from the tax.
Flowchart of the Solution:
Figure 2.7 shows the fowcharts followed to solve this problem.
Step-1: Start
Step-2: Initialize income1←0, income2←0, income3←0, income4←0, and income5←0
Step-3: Read values of msalary, fallowance, oallowance, oincome, pfund, linsurance,
share, oinvest, and otaxp
Step-4: tallowance←fallowance+oallowance
Step-5: tincome←(msalary+oincome)×12+tallowance
Step-6: taxincome←tincome-tallowance
Step-7: tinvest←pfund×12+linsurance+share+oinvest
Step-8: rebate←tinvest×15/100
Step-9: Display values of tincome, tallowance, taxincome, and tinvest
Step-10: If taxincome<=220000
10.1: income1←taxincome
10.2: Go to Step-19
ProgReference.com
94 ◾ Learn Programming with C
Step-11: If taxincome<=520000
11.1: income1←220000
11.2: income2←taxincome-220000
11.3: Go to Step-19
Step-12: If taxincome<=920000
12.1: income1←220000
12.2: income2←300000
12.3: income3←taxincome-520000
12.4: Go to Step-19
Step-13: If taxincome<=1420000
13.1: income1←220000
13.2: income2←300000
13.3: income3←400000
13.4: income4←taxincome-920000
13.5: Go to Step-19
Step-14: income1←220000
Step-15: income2←300000
Step-16: income3←400000
Step-17: income4←500000
Step-18: income5←taxincome-1420000
Step-19: tax2←income2×10/100
Step-20: tax3←income3×15/100
Step-21: tax4←income4×20/100
Step-22: tax5←income5×25/100
Step-23: taxtot←tax1+tax2+tax3+tax4+tax5
Step-24: taxpaid←taxtot-rebate-otaxp
Step-25: Display values of income1, income2, tax2, income3, tax3, income4, tax4,
income5, tax5, taxincome, taxtot, rebate, and otaxp
Step-26: If taxtot>0
26.1: If taxpaid<3000
ProgReference.com
Flow Control ◾ 95
ProgReference.com
96 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 97
ProgReference.com
98 ◾ Learn Programming with C
/*five float type variables are declared that can store only
decimal values; required memory spaces are assigned for each
variable*/
float tincome, tallowance, taxincome, tinvest, rebate, taxpaid;
/*six float type variables are declared; required memory spaces
are assigned for each variable*/
float income1=0.0, income2=0.0, income3=0.0, income4=0.0;
/*four float type variables are declared and initialized to
0.0; required memory spaces are assigned for each variable;
they are used to save income that falls into distinct slabs;
if income is not that high, income in that slab remains at
0.0*/
float income5=0.0, tax2, tax3, tax4, tax5, taxtot;
/*six float type variables are declared; required memory spaces
are assigned for each variable; 1st variable is initialized to
0.0 and used to save income of another slab*/
printf("This is a simple income tax calculator . . . \n");
/*function printf() displays the text inside the double
quotations as it is on the screen except for a newline replaces
\n*/
printf("What is your monthly basic salary? ");
/*output function printf() displays the text in the double
quotes as it is on screen*/
scanf("%f", &msalary);
/*input function scanf() reads a decimal value from input
terminal and it is assigned to msalary*/
printf("Amount of festival allowance you have got in this"
"year? ");
/*function printf() displays the text in double quotations as
it is on the screen*/
scanf("%f", &fallowance);
/*scanf() reads a decimal value from input terminal and it is
assigned to fallowance*/
printf("Amount of any other allownces you have got in this"
"year? ");
/*function printf() displays the text in double quotations as
it is on the screen*/
scanf("%f", &oallowance);
/*scanf() reads a decimal value from input terminal and it is
assigned to oallowance*/
printf("Amount of any other income/month (house rent, business,"
"etc.)? ");
/*printf() displays the text in the double quotations as it is
on the screen; here long string was broken into multiple lines
using two double quotes (““)*/
ProgReference.com
Flow Control ◾ 99
scanf("%f", &oincome);
/*scanf() reads a decimal value from input terminal and ite is
assigned to oincome*/
printf("Amount of provident fund per month you have to pay? ");
/*printf() displays the text in double quotations as it is on
the screen*/
scanf("%f", &pfund);
/*scanf() reads a decimal value from input terminal and it is
assigned to pfund*/
printf("Amount of life insurance premium you have to pay? ");
/*function printf() displays the text in the double quotations
as it is on the screen*/
scanf("%f", &linsurance);
/*scanf() takes a decimal value from input terminal and it is
assigned to linsurance*/
printf("Amount of your investment in share market? ");
/*function printf() displays the text in the double quotations
as it is on the screen*/
scanf("%f", &share);
/*scanf() reads a decimal value from input terminal and it is
assigned to share*/
printf("Amount of your other investment (DPS, Prizebond etc.)? ");
/*function printf() displays the text in the double quotations
as it is on the screen*/
scanf("%f", &oinvest);
/*scanf() reads a decimal value from input terminal and it is
assigned to oinvest*/
printf("Amount of any other tax paid to the government? ");
/*function printf() displays the text in the double quotations
as it is on the screen*/
scanf("%f", &otaxp);
/*scanf() reads a decimal value from input terminal and it is
assigned to otaxp*/
tallowance=fallowance+oallowance;
/*total allowance in the year is calculated by summing festival
and other allownces*/
tincome=(msalary+oincome)*12+tallowance;
/*total annual income is computed from monthly salaries and
other sources of income, as well as total allowance*/
taxincome=tincome−tallowance;
/*taxable income is calculated by deducting nontaxable allowance
from total income*/
tinvest=pfund*12+linsurance+share+oinvest;
/*total annual investment is calculated from monthly provident
fund, life insurance premium, share debenture and other
investments, if any*/
ProgReference.com
100 ◾ Learn Programming with C
rebate=tinvest*15/100;
/*tax rebate is calculated from total investment*/
printf("\nTotal Income: %0.2f taka", tincome);
/*this printf() function displays the text inside double
quotations as it is on the screen except for a newline replaces
\n and the format specifier %0.2f is replaced by the value of
tincome with two decimal points precision*/
printf("\nTotal Allowances: %0.2f taka", tallowance);
/*this printf() function displays the text inside double
quotations as it is on the screen except for a newline replaces
\n and format specifier %0.2f is replaced by the value of
tallowance with two decimal points precision*/
printf("\nTotal Taxable Income: %0.2f taka", taxincome);
/*this printf() function displays the text inside the double
quotations as it is on the screen except for a newline replaces
\n and the format specifier %0.2f is replaced by the value of
taxincome with two decimal points precision*/
printf("\nTotal Investment: %0.2f taka", tinvest);
/*this printf() function displays the text inside the double
quotations as it is on the screen except for a newline replaces
\n and the format specifier %0.2f is replaced by the value of
tinvest with two decimal points precision*/
if (taxincome<=220000)
/*if the taxable income falls into the lowest income bracket,
the condition is true, and the next statement is executed*/
income1=taxincome;
/*total income is assigned to income1; income2 to income5
remain unchanged at 0.0*/
else if (taxincome<=520000){
/*if the taxable income exceeds the lowest slab but falls within
the second, the else..if condition is true, and the following
statements are executed to divide the taxable income into two
parts*/
income1=220000;
/*first 220000 income is assigned to income1*/
income2=taxincome−220000;
/*remaining income is allocated to income2; income3 through
income5 remain unchanged at 0.0*/
}
/*this is the end of else..if with condition (taxincome<=520000)*/
else if (taxincome<=920000){
/*if the taxable income exceeds the 2nd slab but falls within
the 3rd, the else..if condition is true and the following
statements are executed to divide the taxable income into three
parts*/
income1=220000;
/*first 220000 income is assigned to income1*/
ProgReference.com
Flow Control ◾ 101
income2=300000;
/*next 300000 income is assigned to income2*/
income3=taxincome−520000;
/*remaining income is assigned to income3; income4 and
income5 remain unchanged at 0.0*/
}
/*this is the end of else..if with condition (taxincome<=920000)*/
else if (taxincome<=1420000){
/*if the taxable income exceeds the 3rd slab but falls within
the 4th, the else..if condition is true and the following
statements are executed to divide the taxable income into four
parts*/
income1=220000;
/*first 220000 income is assigned to income1*/
income2=300000;
/*next 300000 income is assigned to income2*/
income3=400000;
/*next 400000 income is assigned to income3*/
income4=taxincome−920000;
/*remaining is assigned to income4; income5 remains unchanged
at 0.0*/
}
/*this is the end of else..if with condition (taxincome<=1420000)*/
else{
/*if taxable income exceeds the 4th slab, the condition of
else..if is true and following statements are executed to divide
the taxable income into five parts*/
income1=220000;
/*first 220000 income is assigned to income1*/
income2=300000;
/*next 300000 income is assigned to income2*/
income3=400000;
/*next 400000 income is assigned to income3*/
income4=500000;
/*next 500000 income is assigned to income4*/
income5=taxincome−1420000;
/*remaining income is assigned to income5*/
}
/*this is the end of body of the above else*/
tax2=income2*10/100;
/*the tax amount for the 2nd income level is computed; if the
taxable income falls within the 1st slab, the tax amount is 0.00
(income2=0.0)*/
tax3=income3*15/100;
/*the tax amount for the 3rd income level is computed; it is
0.00 if the taxable income falls inside the 2nd slab, since
income3=0.0*/
ProgReference.com
102 ◾ Learn Programming with C
tax4=income4*20/100;
/*the tax amount for the 4th income level is computed; it is
0.00 if the taxable income falls inside the 3rd slab, since
income4=0.0*/
tax5=income5*25/100;
/*the tax amount for the 5th income level is computed; if the
taxable income falls within the 4th slab, the tax amount is 0.00
(income5=0.0)*/
taxtot=tax2+tax3+tax4+tax5;
/*the total tax amount is calculated by adding all of the
previous tax amounts together*/
taxpaid=taxtot−rebate−otaxp;
/*the amount of tax that must be paid is calculated by subtracting
the tax rebate and any other taxes that have been paid from the
total tax amount*/
printf("\n\nCalculation of Tax Liabilities");
/*this printf() function displays the text inside the double
quotations as it is on the screen except for a newline replaces
\n*/
printf("\nOn the first Tk220000 @0%% (%0.2f): 0.00", income1);
/*this printf() function displays the text inside the double
quotations as it is on the screen except for a newline replaces
\n and the format specifier %0.2f is replaced by value of
income1 with two decimal points precision*/
printf("\nOn the next Tk300000 @10%% (%0.2f): %0.2f", income2,
tax2);
/*printf() function displays the text inside the double quotes
as it is on the screen except for a newline replaces \n; 1st
format specifier %0.2f is replaced by the value of income2 with
two decimal points precision while 2nd %0.2f by the value of
tax2*/
printf("\nOn the next Tk400000 @15%% (%0.2f): %0.2f", income3,
tax3);
/*printf() function displays the text inside the double quotes
as it is on the screen except for a newline replaces \n; 1st
format specifier %0.2f is replaced by the value of income3 with
two decimal points precision while 2nd %0.2f by value of tax3*/
printf("\nOn the next Tk500000 @20%% (%0.2f): %0.2f", income4,
tax4);
/*printf() function displays the text inside the double quotes
as it is on the screen except for a newline replaces \n; 1st
format specifier %0.2f is replaced by the value of income4 with
two decimal points precision while 2nd %0.2f by value of tax4*/
printf("\nOn the balance amount @25%% (%0.2f): %0.2f", income5,
tax5);
/*printf() function displays the text inside the double quotes
as it is on the screen except for a newline replaces \n; 1st
ProgReference.com
Flow Control ◾ 103
ProgReference.com
104 ◾ Learn Programming with C
PROBLEM-13
Write a program to generate random numbers between a given range. Te minimum
and maximum ranges and number of random numbers to be generated are input
interactively.
ProgReference.com
Flow Control ◾ 105
Step-1: Start
Step-2: Read values of num1, min, and max
Step-3: srand(time(NULL))
Step-4: Initialize cnt←0
Step-5: If (cnt<num1)
5.1: num←min+((rand()%10)/9.0)×(max−min)
5.2: Display value of num
5.3: cnt←cnt+1
5.4: Go to Step-5
Step-6: Stop
ProgReference.com
106 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 107
ProgReference.com
108 ◾ Learn Programming with C
}
/*this closing curly brace specifies the end of the for loop*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-14
Write a program to compute the value of PI using the Monte Carlo method.
Step-1: Start.
Step-2: Defne SEED←time(NULL)
ProgReference.com
Flow Control ◾ 109
Step-3: srand(SEED).
Step-4: Initialize count←0
Step-5: Read value of iter.
Step-6: Initialize i←0
Step-7: If i<iter
7.1: x←(double)rand()/RAND_MAX
7.2: y←(double)rand()/RAND_MAX
7.3: z←sqrt(x2+y2)
7.4: If z<=1
7.4.1: count←count+1
7.5: pi←(double)count/iter×4
7.6: Go to Step-7
Step-8: Display value of pi.
Step-9: Stop.
ProgReference.com
110 ◾ Learn Programming with C
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-15
Write a program to fnd the root of a nonlinear equation using the Newton–Raphson
method.
Step-1: Start.
Step-2: Defne f(x)←5x+2sin(x)−cos(x)
Step-3: Defne g(x)←5+2cos(x)+sin(x)
Step-4: Initialize step←1
Step-5: Read value of x0, err, and iter
Step-6: g0←g(x0)
Step-7: f0←f(x0)
Step-8: If (g0=0.0)
8.1: Display ‘error’
8.2: Go to Step-17
Step-9: x1←x0-f0/g0
Step-10: Display values of step, x0, f0, x1, and f1
Step-11: x0←x1
Step-12: step←step+1
Step-13: If (step>iter)
13.1: Display ‘not convergent’
13.2: Go to Step-17
Step-14: f1←f(x1)
Step-15: If (fabs(f1)>err)
15.1: Go to Step-6
Step-16: Display value of x1
Step-17: Stop.
ProgReference.com
114 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 115
#include <math.h>
/*header file math.h contains prototypes of the library functions
fabs(), sin() and cos(); the header file must be included using
preprocessor directive #include before the functions are called in
the program*/
#include<stdlib.h>
/*header file stdlib.h contains prototype of the library function
exit(); the header file must be included using preprocessor directive
#include before the function is called in the program*/
#define f(x) 5*x+2*sin(x)−cos(x)
/*#define is a preprocessor directive that defines a constant
variable; in this case, f(x) is the constant variable that holds
the value of the expression 5x+2sinx−cosx at x=x1*/
#define g(x) 5+2*cos(x)+sin(x)
/*the #define preprocessor directive is used to define another
constant variable, g(x), which takes the value of the expression
f/(x)=5+2cosx+sinx at x=x1*/
int main(){
/*here main() function returns an integer and parameters/
arguments of the main() function also remain void; execution of
the program starts with main() function; no statement before
opening curly brace of the main() function is executed by the
compiler*/
float x0, x1, f0, f1, g0, err;
/*six float type variables are declared; required memory spaces
are allocated for each of the variables*/
int step=1, iter;
/*integer type variables step and iter are declared; required
memory spaces are allocated for each of the variables; variable
step is initialized to 1*/
printf("Enter initial guess: ");
/*output function printf() displays text in the double quotations
as it is on the screen*/
scanf("%f", &x0);
/*input function scanf() reads a decimal value from the keyboard
and stores it in the memory spaces assigned for x0*/
printf("Enter tolerable error: ");
/*output function printf() displays text in double quotations
as it is on the screen*/
scanf("%f", &err);
/*function scanf() reads a decimal value from the keyboard and
assigns it to err*/
printf("Enter maximum iteration: ");
/*function printf() displays text in the double quotations as
it is on the screen*/
scanf("%d", &iter);
/*input function scanf() reads an integer from the keyboard and
stores the value in the memory spaces assigned for iter*/
ProgReference.com
116 ◾ Learn Programming with C
printf("\nStep\tx0\t\tf(x0)\t\tx1\t\tf(x1)\n");
/*printf() function displays text in the double quotations as
it is on the screen except for a newline replaces \n and a tab
replaces \t*/
do{
/*following statements, enclosed within the curly braces,
repeatedly execute as long as the condition in the following
while remains true*/
g0 = g(x0);
/*value of the derivative of the equation at x=x0 is computed
and assigned to g0*/
f0 = f(x0);
/*value of the equation at x=x0 is calculated and assigned
to f0*/
if (g0==0.0){
/*if the function’s derivative at x=x0 is 0, then above
condition is true and following statements execute*/
printf("Error, exiting . . . ");
/*printf() displays text in the double quotations as it
is on the screen*/
exit(0);
/*if g0=0, we can’t divide the value f0 by g0 in the
next statement, which is required to calculate a new
approximate root using the Newton-Raphson method,
therefore exit() is used to terminate the program
early*/
}
/*this closing curly brace specifies the end of 'if' with
condition (g0==0.0)*/
x1 = x0−f0/g0;
/*from the previous guess x0 and the values of the function
and its derivative at x=x0, we compute a better approximation
of the root x1*/
printf("%d\t%f\t%f\t%f\t%f\n", step, x0, f0, x1, f1);
/*printf() displays the results of this step on the screen;
value of step is displayed in place of the first format
specifier %d, x0 in place of first %f, f0 in place of second
%f, x1 in place of third %f, f1 in place of fourth %f, a
newline in place of \n and a tab in place of \t*/
x0 = x1;
/*calculated better estimate value x1 is assigned to x0
so that in the following iteration of the loop, a better
approximation than x1 can be computed*/
step = step+1;
/*the number of steps required to obtain the approximate
root of the function is counted by incrementing the value
of step by 1*/
ProgReference.com
Flow Control ◾ 117
if (step>iter){
/*if the number of steps exceeds the maximum number of
iteration, the above condition is true, and the next two
statements are executed*/
printf("Not convergent, exiting . . . ");
/*printf() displays text in the double quotations as it
is on screen*/
exit(0);
/*if step>iter and we still don’t get a root within
our limit of error, the function isn’t converging fast
enough, so we terminate the program early with exit();
exit(0) specifies an error-free program termination;
we may need more iterations to achieve the desired
outcome*/
}
/*this closing curly brace specifies the end of 'if' with
condition (step>iter)*/
f1 = f(x1);
/*value of the function is calculated at a new approximate
root x=x1 and assigned to f1*/
}while (fabs(f1)>err);
/*absolute value of f(x) at x=x1 is compared with our limit
of tolerable error; if the approximate root does not give us
function value within our limit of tolerable error, the above
condition of while is true, and the statements in the body of
do..while are executed again; these steps continue until we
get the root that gives us function value within our limit of
tolerable error*/
printf("\nRoot is: %0.3f", x1);
/*printf() function displays the text in the double-quotes as
it is on the screen, with the exception that the value of x1
replaces the format specifier %0.3f with three decimal points
precision and a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-16
Write a program to fnd the roots of a nonlinear equation using the Secant method.
ProgReference.com
118 ◾ Learn Programming with C
Step-1: Start.
Step-2: Defne f(x)←x3–2x−5
Step-3: Initialize step←1
Step-4: Read values of min, max, err, and iter.
ProgReference.com
Flow Control ◾ 119
Step-5: fmin←f(min)
Step-6: fmax←f(max)
Step-7: If (fmin=fmax)
7.1: Display ‘error’
7.2: Go to Step-19
Step-8: new1←max−(max−min)×fmax/(fmax−fmin)
Step-9: fnew←f(new1)
Step-10: Display values of step, min, max, new1, and fnew.
Step-11: min←max
Step-12: fmin←fmax
Step-13: max←new1
Step-14: fmax←fnew
Step-15: step←step+1
Step-16: If (step>iter)
16.1: Display ‘not convergent’
16.2: Go to Step-19
Step-17: If (fabs(fnew)>err)
17.1: Go to Step-5
Step-18: Display value of new1
Step-19: Stop
ProgReference.com
120 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 121
ProgReference.com
122 ◾ Learn Programming with C
scanf("%f", &err);
/*scanf() takes a decimal value from keyboard and assigns the
value to err*/
printf("Enter maximum iteration: ");
/*output function printf() displays text in the double quotations
as it is on the screen*/
scanf("%d", &iter);
/*input function scanf() reads an integer from keyboard and
stores the value in the memory spaces assigned for iter*/
printf("\nStep\tmin\t\tmax\t\tnew\t\tf(new)\n");
/*printf() function displays text in the double quotations as
it is on the screen except for a newline replaces \n and a tab
replaces \t*/
do{
/*following statements enclosed in curly braces are executed
repeatedly as long as the condition in the while loop remains
true*/
fmin = f(min);
/*value of the function f(x) at x=min is calculated and
assigned to fmin*/
fmax = f(max);
/*value of the function f(x) at x=max is calculated and
assigned to fmax*/
if (fmin==fmax){
/*if the values of f(x) at x=min and x=max are the same,
the condition above is true, and the following statements
are executed*/
printf("Mathematical error, exiting . . . ");
/*printf() displays text in the double quotations as it
is on the screen*/
exit(0);
/*if fmin=fmax, we can’t divide fmax by (fmax−fmin) in
the next statement, which is required to compute a new
approximate root using the Secant method, therefore we
call the built-in library function exit() to terminate
the program prematurely*/
}
/*this closing curly brace specifies the end of 'if' with
condition (fmin==fmax)*/
new1 = max−(max−min)*fmax/(fmax−fmin);
/*we derive a new approximate root from prior minimum and
maximum guesses, as well as values of f(x) at x=min and
x=max*/
fnew = f(new1);
/*the value of f(x) at a new approximation, x=new1, is
computed and assigned to fnew*/
ProgReference.com
Flow Control ◾ 123
ProgReference.com
124 ◾ Learn Programming with C
}while (fabs(fnew)>err);
/*absolute value of f(x) at x=new is compared with our limit of
tolerable error; if the approximate root does not give us function
value within our limit of tolerable error, the above condition of
while is true, and the statements in the body of do..while are
executed again; these steps continue until we get root that gives
us function value within our limit of tolerable error*/
printf("\nRoot is: %0.3f", new1);
/*printf() function displays the text in the double quotations
as it is on the screen except for the value of new replaces the
format specifier %0.3f with three decimal points precision, and
a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-17
Write a program to fnd the value of an unknown function from a discrete set of known
data points using the Lagrange interpolation formula.
[note: please address this problem afer completing Chapter 3, as its solution relies on
the use of arrays]
Step-1: Start.
Step-2: Initialize dum←‘y’
Step-3: Read value of num.
Step-4: Initialize i←0
Step-5: If i<num
5.1: Input x[i] and y[i]
5.2: i←i+1
5.3: Go to Step-5
Step-6: Initialize i←0
Step-7: If i<num
ProgReference.com
Flow Control ◾ 125
8.3: If i<num
8.3.1: p←1, j←0
8.3.2: If j<num
8.3.2.1: If j≠i
8.3.2.1.1: p←p×(vox−x[j])/(x[i]−x[j])
8.3.2.2: j←j+1
8.3.2.3: Go to Step-8.3.2
8.3.3: voy←voy+p×y[i]
8.3.4: i←i+1
8.3.5: Go to Step-8.3
8.4: Display values of vox and voy.
8.5: dum←getche()
8.6: Go to Step-8
Step-9: Stop.
ProgReference.com
Flow Control ◾ 127
ProgReference.com
128 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 129
ProgReference.com
130 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 131
PROBLEM-18
Write a program to solve ordinary diferential equations using Euler’s method.
ProgReference.com
132 ◾ Learn Programming with C
Step-1: Start.
Step-2: Defne f(x,y)←(y2−x2)/(y2+x2)
Step-3: Read values of x0, y0=f(x0), xn, and num.
Step-4: step←(xn−x0)/num
Step-5: Initialize i←0
Step-6: If i<num
6.1: slope←f(x0, y0)
6.2: yn←y0+step×slope
6.3: Display values of x0, y0, slope, and yn
6.4: y0←yn
6.5: x0←x0+step
6.6: i←i+1
ProgReference.com
Flow Control ◾ 133
6.7: Go to Step-6
Step-7: Display values of xn and yn
Step-8: Stop.
ProgReference.com
134 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 135
scanf("%d", &num);
/*function scanf() reads an integer from input terminal and
stores the value in the memory spaces assigned for num*/
step = (xn−x0)/num;
/*step-size is calculated from calculation point, initial point
and number of steps*/
printf("\nx0\ty0\tslope\tyn\n");
/*printf() function displays the text in double quotations as
it is on the screen except for a newline replaces \n and a tab
replaces \t*/
for (i=0; i<num; i++){
/*this for loop is used to calculate f(xn) from f(x0), with each
iteration takes a small step forward to calculate f(x0+i*step);
i=0 is initialization, i<num is condition and i++ is increment;
the initialization is done once at the beginning of the loop;
after that, the condition is tested, if it is true, the statements
in the body are executed, and the value of i is incremented by
one before the condition is re-checked; these procedures are
repeated until the condition becomes false at which point the
program flow exits the loop*/
slope = f(x0, y0);
/*slope to the curve at x0 is computed from the differential
equation, f(x0, y(x0))=f(x0, y0) [value of f(x, y) at x=x0
and y=y0=y(x0)]*/
yn = y0+step*slope;
/*next slope to the curve at a point small step forward
from x0 is calculated from y0=y(x0), step size and slope at
previous point*/
printf("%0.3f\t%0.3f\t%0.3f\t%0.3f\n", x0, y0, slope, yn);
/*results of this step are displayed on screen using output
function printf(); value of x0 is displayed in place of
first format specifier %0.3f with three decimal points
precision, y0 in place of second %0.3f, slope in place of
third %0.3f and yn in place of fourth %0.3f; other text is
displayed as it is except for a newline replaces \n and a
tab replaces \t*/
y0 = yn;
/*calculated slope value yn is assigned to y0 so that it
can be used to compute slope at the next point in the next
iteration of the loop*/
x0 = x0+step;
/*next point is calculated by stepping a small step forward;
this value is used to compute slope at the next point in the
next iteration of the loop*/
}
/*this closing curly brace specifies the end of for loop*/
ProgReference.com
136 ◾ Learn Programming with C
PROBLEM-19
Write a program to approximate the defnite integral of a continuous function using
Simpson’s 1/3 rule.
ProgReference.com
Flow Control ◾ 137
Step-1: Start.
Step-2: Defne f(x)←(1+x)/(1+x2)
Step-3: Read values of low, up, and sub.
Step-4: step←(up-low)/sub
Step-5: in←f(low)+f(up)
Step-6: Initialize i←1
Step-7: If i<=sub−1
7.1: k←low+i×step
7.2: If i%2=0
7.2.1: in←in+2×f(k)
7.2.2: Go to Step-7.4
7.3: in←in+4×f(k)
7.4: i←i+1
7.5: Go to Step-7
Step-8: in←in×step/3
Step-9: Display value of in
Step-10: Stop.
ProgReference.com
138 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 139
scanf("%f", &up);
/*scanf() reads a decimal value from the input terminal and
stores the value in the memory space allocated for variable
up*/
printf("Enter number of sub-intervals: ");
/*output function printf() displays the text in the quotations
as it is on the screen*/
scanf("%d", &sub);
/*scanf() reads an integer from the input terminal and stores
the value in the memory space allocated for variable sub*/
step = (up−low)/sub;
/*step size is calculated from upper limit, lower limit and no.
of sub-intervals
Simpson’s 1/3 rule-
° °
step ˙
˜ f(x2i-1)+f(up)˘ˇ /
up sub/2-1 sub/2
f(x)dx = f(low) + 2 f(x2i)+4
low 3 ˆˆ =1
i= i=1 ˘
in = f(low)+f(up);
/*values of function at x=up and atbx=low are calculated and
their summation is assigned to in*/
for (i=1; i<=sub−1; i++){
/*this for loop is used to compute the two summation terms in
the Simpson’s 1/3 rule; i=1 is initialization, i<=sub−1 is
condition and i++ is increment; the condition is checked once
at the beginning of the loop; if it is true, statements in
the body are executed and the value of i is incremented by 1
before the condition is re-checked; these steps continue until
the condition becomes false at which point the program flow
exits the loop; for i=0, k=low and for i=sub, k=up; values of
the f(x) at these two points f(low) and f(up) were considered
before that loop; hence this loop starts with i=1 and ends at
i=sub−1*/
k = low+i*step;
/*next point x=k is calculated from the lower limit and
step size*/
if (i%2==0)
/*if i is an even number, following statement is executed
and skipped the next else statement*/
in = in+2*f(k);
/*first summation term of the Simpson’s 1/3 rule is
calculated and added to in*/
else
/*if i is an odd number, following statement is executed
skipping the previous if statement*/
in = in+4*f(k);
/*second summation term of the Simpson’s 1/3 rule is
calculated and added to in*/
ProgReference.com
140 ◾ Learn Programming with C
}
/*this closing curly brace specifies the end of the for loop*/
in = in*step/3;
/*integral value of the function is calculated by multiplying
the total summation in by 1/3rd of the step size*/
printf("Required value of integration is: %0.3f", in);
/*printf() displays the text in the quotations as it is on the
screen except for the value of in replaces format specifier
%0.3f with three decimal points precision*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
EXERCISES
B) break statement
C) leave statement
D) quit statement
5) Choose a correct statement about the break statement.
A) A single break statement can force execution control to come out of only one
loop
B) A single break statement can force execution control to come out of a maxi-
mum of two nested loops
C) A single break statement can force execution control to come out of a maxi-
mum of three nested loops
D) None of the above
6) break statement is used to _______.
A) Quit a program
B) Quit the current iteration
C) Both A and B
D) None of the above
7) Which of the following is a C conditional operator?
A) ?:
B) :?
C) :<
D) <:
8) Which of the following is the correct syntax of the ternary operator?
A) condition? expression1: expression2
B) condition: expression1? expression2
C) condition? expression1 < expression2
D) condition < expression1? expression2
9) Which of the following is a valid statement regarding if..else statement?
A) else..if is compulsory to use with if statement
B) else is compulsory to use with if statement
C) else or else..if is optional with if statement
D) None of the above
ProgReference.com
142 ◾ Learn Programming with C
ProgReference.com
Flow Control ◾ 143
B) 0
C) 1
D) 55
[Ans. D, A, A, B, A, B, A, A, C, B, C, B, C, A]
5) What is a loop control statement? What are the loop control statements available
in C?
Ans. Te loop control statement changes the typical execution sequence. break,
continue, and goto are the loop control statements available in C.
ProgReference.com
144 ◾ Learn Programming with C
Ans. Te while loop always tests the condition before executing the while loop’s
statements, whereas the do..while loop tests the condition afer executing the loop’s
statements. As a result, even if the condition is false, the statements in the do..while
loop are executed at least once.
14) What is the output of the following program fragment?
if (4>5)
printf("Atiq . . .");
printf("Ahad . . .");
Ans. Ahad . . .
Te frst printf() statement is not executed because the ‘if’ condition is false, and the
second printf() statement displays the text Ahad . . . on the screen.
15) What is the output of the following program fragment?
if (10>9)
printf("Dhaka . . .");
else if (6%3==0)
printf("Karachi . . .");
printf("Delhi . . .");
Ans. Dhaka . . . Delhi . . .
Because the if condition is true, the frst printf() is executed, displaying Dhaka
. . . on the screen, and the else..if condition is not entered, so the second printf()
is not executed. Te third printf() function displays the text Delhi . . . on the
screen.
16) What is the output of the following program fragment?
while (true){
printf("Singapore . . .");
break;}
Ans. Because TRUE or true is not a keyword, the while statement fails and causes a
compilation error.
17) What is the output of the following program fragment?
int num=5;
while (num=12){
printf("nothing . . .");
break;}
ProgReference.com
146 ◾ Learn Programming with C
Ans. nothing . . .
Because while (num=12) == while (12) == while (non-zero) == true, printf()
displays nothing . . . on the screen and the break statement terminates the loop
immediately.
18) What is the output of the following program fragment?
int num=40;
do{
printf("%d . . .", num);
num++;} while (num<=30);
Ans. 40 . . .
Because statements in the “do” are executed at least once before the while condition
is checked, the result is 40 . . .. Te false condition is now checked, and the loop is
terminated.
19) What is the output of the following program fragment?
for (i=1, j=10; i<=5; i++)
printf("%d, ", i+j);
Ans. 11, 12, 13, 14, 15,
Initialization is done once at the beginning of the loop, i=1, j=10. Because condition
i<=5 is true, printf() displays i+j=1+10=11 on the frst iteration, and the value of i
is incremented by 1 (i++→i=i+1=1+1=2). Because condition i<=5 is true again in the
second iteration, the number 12 is displayed, and so on. Te number 15 is displayed,
and i becomes i=5+1=6 in the ffh iteration; the condition i<=5 is false, and the loop
ends afer the ffh iteration.
20) What is the output of the following program fragment?
int num=10;
while (num<15){
num++;
if (num>=12 && num<=14)
continue;
printf("%d, ", num);}
Ans. 11, 15,
ProgReference.com
Flow Control ◾ 147
Because the “if” condition is true and the continue statement is executed between
12 and 14, the printf() statement in the loop skips during that period.
21) What is the output of the following program fragment?
int x=0, y=0;
while (++x<4)
printf("%d, ", x);
while (y++<4)
printf("%d, ", y);
Ans. 1, 2, 3, 1, 2, 3, 4,
Te value of x is incremented frst in the frst ‘while’ loop, and then the condition
is tested. Te second ‘while’ loop, on the other hand, checks the condition frst and
then increments the value of y.
22) What is the output of the following program fragment?
int num=3;
switch (num){
case 1: printf("1, ");
case 3: printf("3, ");
case 5: printf("5, ");
default: printf("default, ");}
Ans. 3, 5, default,
Because there is no break statement afer matching and executing the case 3 state-
ment, program control immediately moves to case 5 and default.
23) What is the output of the following program fragment?
int num=0;
switch (num){
case 1: printf("1, ");
case 3: printf("3, ");
case 5: printf("5, ");
default: printf(“default, ”);}
Ans. default,
ProgReference.com
148 ◾ Learn Programming with C
Because there is no case match in the switch statement, program control goes to
default case automatically.
24) What is the output of the following program fragment?
char code='s';
switch (code){
case 's': printf(“sun, ”); break;
case 'a': printf(“apple, ”); break;
case 't': printf(“tire, ”); break;
default: printf(“default, ”);}
Ans. sun,
Because the switch statement’s case ‘s’ matches, the corresponding printf() displays
sun on the screen because of the break statement, program control exits the switch,
ignoring all other cases.
25) What is the output of the following program fragment?
int num=32;
switch (num){
case 16: printf(“16, ”); break;
case 32: printf(“32, ”); break;
case 16*2: printf(“16×2, ”); break;
default: printf(“default, ”);}
Ans. A compilation error will occur. Because C prohibits the use of duplicate case
constants in switch statements.
26) What is the output of the following program fragment?
int num=3;
switch (num){
case 1: printf(“1, ”); break;
case 3: printf(“3, ”); break;
case 5: printf(“5, ”); continue;
default: printf(“default, ”);}
Ans. A compilation error will occur. Because the continue statement is not allowed
in a switch..case statement as it is not a loop.
ProgReference.com
Flow Control ◾ 149
Problems to Practice
ax 2 + bx + c = 0
Te program should request the values of the constants a, b, and c and display the
values of the roots.
9) Write a program to compute the sum of individual digits of a given positive integer
number.
10) Develop a program to implement a calculator. Te program should request the user
to input two numbers and display one of the following as per the desire of the user
(consider the operators “+”, “−”, “*”, “/”, “%” and use “switch” statement):
(a) Sum of the numbers
(b) Diference of the numbers
ProgReference.com
150 ◾ Learn Programming with C
Income Tax
First tk 2,20,000.00 Nil
Next tk 3,00,000.00 10%
Next tk 4,00,000.00 15%
Next tk 5,00,000.00 20%
Rest amount 25%
Minimum payable tax is tk 3,000.00
Provident funds, life insurance, and share investment are considered personal
investments, and the taxpayer gets a 15% rebate on his total investment. Festival
allowance and other allowances are exempted from the tax.
13) Write a program to generate random numbers between a given range. Te mini-
mum and maximum ranges and number of random numbers to be generated are
input interactively.
14) Write a program to compute the value of PI using the Monte Carlo method.
15) Write a program to fnd the root of a nonlinear equation using the Newton–Raphson
method.
16) Write a program to fnd the roots of a nonlinear equation using the Secant method.
17) Write a program to solve ordinary diferential equations using Euler’s method.
18) Write a program to approximate the defnite integral of a continuous function
using Simpson’s 1/3 rule.
ProgReference.com
Flow Control ◾ 151
ProgReference.com
CHAPTER 3
I n C, an array is used to hold multiple values of the same data type. The array could be
one-dimensional, two-dimensional, or three-dimensional. On the other hand, pointer
variables are used to hold addresses rather than values of variables. In terms of memory
access, arrays and pointers are synonymous. The first element of an array is referred to by
its name, whereas the value of a pointer points to any memory location.
3.1 ARRAYS
An array is a collection of data types that are all of the same kind. A single array variable
can store, access, and handle a large amount of data. In the following C code, for example,
int num[100];
num is an integer type array with a total of 100 elements. Starting at 0 and continuing
until n-1, each array element can be retrieved using appropriate indexing. The 4th, 5th,
and 6th elements of the above num array, for example, are accessed with num[3], num[4],
and num[5].
We initialize the array in the same way that we would for any other data type variable.
or,
int num[4];
num[4] = {5, 10, 9, 19};
ProgReference.com
Arrays and Pointers ◾ 153
or,
(3) Interactively by the user afer running the program. In that case, we usually use any
of the C loops to access each element of the array. Example:
int i, num[4];
for (i=0; i<4; i++)
scanf(“%d”, &num[i]);
When any array is declared, the array is organized such that all the array elements occupy
contiguous space in memory. If the size of the integer data type is 4 bytes, then the memory
organization of the array num[4] is as follows:
3.2 2D ARRAYS
A two-dimensional array is an array of arrays. It is also known as a matrix in C and is
defned as a set of rows and columns. Te following expression represents an integer type
2D array of matrix 2 × 4.
int num[2][4];
When declaring or initializing a 2D array, we must specify the size of the second dimen-
sion or the number of columns. Te 2D array items are initialized as follows:
ProgReference.com
154 ◾ Learn Programming with C
int multi[2][3][4];
int multi[2][3][4] = {
{{1, 2, 3, 4}, {5, 7, 9, 11}, {−3, 13, 23, 31}},
{{2, 4, 6, 8}, {6, 7, −8, 9}, {4, 12, 23, −3}}};
The 24 elements of the 3D array can be entered as follows from a standard input
terminal:
int i, j, k;
for (i=0; i<2; i++)
for (j=0; j<3; j++)
for (k=0; k<4; k++)
scanf(“%d”, &multi[i][j][k]);
int i, j, k;
for (i=0; i<2; i++)
for (j=0; j<3; j++)
for (k=0; k<4; k++)
printf(“multi[%d][%d][%d]=%d\n”, i, j,
k, multi[i][j][k]);
ProgReference.com
Arrays and Pointers ◾ 155
3.4 STRING
A string is a series of characters that end with the null terminator ‘\0’. As an example, a
string is declared as follows:
ProgReference.com
156 ◾ Learn Programming with C
3.6 POINTERS
In C, when a variable is declared, it is instantly assigned a memory location. Another vari-
able known as the pointer holds the variable’s address. A pointer’s data type must match
the data type of the variable whose address the pointer holds. Integer type pointers, for
example, only hold the address of integer type variables, while double type pointers only
retain the address of double type variables. Example:
In the above example, the address of the memory region assigned to the abc variable is pt,
and the value stored in that memory location is *pt. Te value at the address is known as *.
Like malloc(), calloc() allocates a specifc number of bytes in memory, but it also initializes
all bits to zero. Te syntax and an example of calloc() are as follows:
If the previous allocation size is not appropriate (either insufcient or more than required),
realloc() changes the previously allocated memory space size. Syntax:
Te free() function is used to manually free the memory space that has been dynamically
allocated. Syntax:
free(ptr);
ProgReference.com
Arrays and Pointers ◾ 157
3.8 EXAMPLES
PROBLEM-01
Write a program to input and print the elements of array using pointer.
ProgReference.com
158 ◾ Learn Programming with C
PROBLEM-02
Write a program to fnd the number of elements in an array.
ProgReference.com
Arrays and Pointers ◾ 159
ProgReference.com
160 ◾ Learn Programming with C
PROBLEM-03
Write a program to calculate the average of array elements.
ProgReference.com
Arrays and Pointers ◾ 161
ProgReference.com
162 ◾ Learn Programming with C
PROBLEM-04
Write a program to fnd the length of a string with and without strlen().
ProgReference.com
Arrays and Pointers ◾ 163
PROBLEM-05
Write a program to print a string using pointer.
ProgReference.com
164 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 165
PROBLEM-06
Write a program to fnd the frequency of a character in a string.
ProgReference.com
166 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 167
if (str[i]==ch)
/*In each iteration, the 'if' condition compares the character
ch with the array element str[]; when any character matches with
ch the condition is true and following statement is executed*/
count++;
/*if ch matches any of the character in the string, the
value of count is incremented by 1*/
printf("%c is occurred in the string %d times.", ch, count);
/*output function printf() displays the text inside the quotations
as it is on the screen except for the character ch replaces the
format specifier %c and the value of count replaces %d*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-07
Write a program to copy a string with and without using strcpy().
ProgReference.com
168 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 169
strcpy(str3, str1);
/*strcpy() function is called to copy the string str1[] as it
is in str3[]*/
printf("Copied string without using library function:\n");
/*this displays the text inside the double quotations as it is
on the screen followed by a newline in place of \n*/
puts(str2);
/*puts() function is called to display the string str2[] as it
is on the output screen*/
printf("Copied string using library function:\n%s", str3);
/*printf() function displays the text inside the double quotes
as it is on the screen except for a newline replaces \n and
string str3[] replaces the format specifier %s*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-08
Write a program to fnd both the largest and smallest numbers of an array of integers.
Step-1: Start
Step-2: Initialize SIZE←10
Step-3: Read value of value[0]
Step-4: Initialize large←value[0], small←value[0] and i←1
Step-5: if i<SIZE
5.1: Read value of value[i]
5.2: If value[i]>large
7.2.1: large←value[i]
5.3: If value[i]<small
7.3.1: small←value[i]
ProgReference.com
170 ◾ Learn Programming with C
5.4: i←i+1
5.5: Go to Step-5
Step-6: Display values of large and small
Step-7: Stop
ProgReference.com
Arrays and Pointers ◾ 171
large=value[0];
/*value of the 1st array element value[0] is assigned to variable
large which is used to store the largest number*/
small=value[0];
/*value of the 1st array element value[0] is assigned to variable
small which is used to store the smallest number*/
for (i=1; i<SIZE; i++){
/*i=1 is the initialization, i<SIZE is the condition and i++
is the increment; initialization is done once at the beginning
of the loop; then the condition is checked, if it is true,
statements in the body are executed and the value of i is
incremented by 1 before the condition is re-checked; these
steps continue until the condition becomes false at which point
the program flow exits the loop*/
scanf("%d", &value[i]);
/*this scanf() function reads an integer from input
terminal and stores the value to array value[i]; because
this statement is executed in each iteration, value[1] is
input in the 1st iteration, value[2] in the 2nd iteration
and so on*/
if (value[i]>large)
/*the input value is compared to the value of large in
each iteration; if the input value is greater than large,
the condition is true, and the following statement is
executed*/
large=value[i];
/*if the input value is larger than large, the value
of large is updated to the input value, ensuring that
large always contains the largest value*/
if (value[i]<small)
/*the input value is compared to the value of small in
each iteration; if the input value is smaller than small,
the condition is true, and the following statement is
executed*/
small=value[i];
/*if the input value is smaller than small, the value
of small is updated to the input value, ensuring that
small always contains the smallest value*/
}
/*the for loop comes to an end with this closing curly brace*/
printf("Largest value of the array is: %d\n", large);
/*output function printf() displays the text inside the double
quotations as it is on the screen except for the value of
large replaces the format specifier %d and a newline replaces
\n*/
printf("Smallest value of the array is: %d\n", small);
/*output function printf() displays text inside the double
quotations as it is on the screen except for the value of
ProgReference.com
Arrays and Pointers ◾ 173
PROBLEM-09
Write a program to generate the frst n terms of a Fibonacci sequence. Also, check
whether a given integer is a Fibonacci number or not.
Step-1: Start
Step-2: Initialize dm←1
Step-3: Read value of n between 3 and 25
Step-4: Initialize fn[0]←0, fn[1]←1 and i←2
Step-5: If i<n
5.1: fn[i]←fn[i−1]+fn[i−2]
5.2: i←i+1
5.3: Go to Step-5
Step-6: Initialize i←0
Step-7: If i<n−1
7.1: Display value of fn[i]
7.2: i←i+1
7.3: Go to Step-7
Step-8: Display value of fn[i]
Step-9: Read value of ck
Step-10: If ck=0
10.1: Go to Step-11
ProgReference.com
174 ◾ Learn Programming with C
Step-11: If ck=1
11.1: dm←0
11.2: Display ‘Fibonacci number’
11.3: Jump to Step-14
Step-12: Initialize fnck[0]←0, fnck[1]←1 and i←2
Step-13: If fnck[i−1]<ck
13.1: fnck[i]←fnck[i−1]+fnck[i−2]
13.2: If fnck[i]=ck
13.2.1: Display ‘Fibonacci number’
13.2.2: dm←0
13.2.3: Go to Step-14
13.3: i←i+1
13.4: Go to Step-13
Step-14: If dm=1
14.1: Display ‘not Fibonacci number’
Step-15: Stop
ProgReference.com
176 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 177
ProgReference.com
178 ◾ Learn Programming with C
printf("%d\n", fn[i]);
/*this printf() function displays the value of last array
element fn[n−1] in place of format specifier %d followed by a
newline in place of \n*/
/*following part of the program will check whether a given
number is a Fibonacci*/
printf("Enter an integer to check: ");
/*printf() function displays the text in double quotations as
it is on the screen*/
scanf("%d", &ck);
/*scanf() function reads an integer from input terminal and
stores it in the memory spaces location allocated for ck; we
want to check if ck is a Fibonacci number*/
if (ck==0 || ck==1){
/*if the input number ck is either 0 or 1, the condition is
true, and the statements, enclosed by curly braces, in the body
of the 'if' are executed*/
printf("%d is a Fibonacci number.\n", ck);
/*this printf() function displays the text in double quotes
as it is on the screen except for the value of ck replaces
the format specifier %d and a newline replaces \n*/
dm=0;
/*value 0 if assigned to dm*/
}
/*this is the end of 'if' with condition ck==0||ck==1*/
else{
/*if ck is neither 0 nor 1, that is, both conditions in the above
'if' are false, statements in the body of this else are executed*/
fnck[0]=0;
/*first Fibonacci number, 0, is saved in the 1st element of
the array fnck[0]*/
fnck[1]=1;
/*second Fibonacci number, 1, is saved in the 2nd element
of the array fnck[1]*/
for (i=2; fnck[i−1]<ck; i++){
/*this for loop sequentially computes 3rd, 4th, 5th, . . .
Fibonacci numbers; i=2 is the initialization, fnck[i−1]<ck
is the condition and i++ is the increment; initialization is
done once at the beginning of the loop; then the condition is
checked, and if it is true, statement in the body is executed;
now, the value of i is incremented by 1 before the condition
is re-checked; this process continues until the condition
becomes false at which point the program flow exits the loop*/
fnck[i]=fnck[i−1]+fnck[i−2];
/*by adding two previous Fibonacci numbers, the next
Fibonacci number is generated and saved in the array fnck[]*/
ProgReference.com
Arrays and Pointers ◾ 179
if (ck==fnck[i]){
/*this if compares the Fibonacci number fnck[i],
generated in previous statement, with the given
number ck; if they match than the condition is true
and following statements in the body of 'if' are
executed*/
printf("%d is a Fibonacci number.\n", ck);
/*this printf() function displays the text in the
double quotes as it is on the screen except for the
value of ck replaces the format specifier %d and a
newline replaces \n*/
dm=0;
/*this sets the value of dm to 0 */
break;
/*we don’t need to continue the loop if ck matches
the generated Fibonacci number in any iteration;
thus, this break forces the program control flow to
exit the for loop*/
}
/*this is the end of 'if' with condition ck==fnck[i]*/
}
/*the 'for' loop ends with this closing curly brace*/
}
/*this is the end of 'else' corresponding to 'if' with condition
ck==0||ck==1*/
if (dm==1)
/*if ck does not match any Fibonacci number then dm=1 and the
condition is true, so following statement is executed*/
printf("%d is not a Fibonacci number.\n", ck);
/*this printf() displays the text in double quotations as
it is on the screen except for the value of ck replaces the
format specifier %d and a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-10
Write a program to fnd the 2’s complement of a given binary number.
ProgReference.com
180 ◾ Learn Programming with C
Step-1: Start
Step-2: Read value of a
Step-3: len←strlen(a)
Step-4: Initialize k←0
Step-5: If a[k]≠‘\0’
5.1: If a[k]≠‘0’
5.1.1: If a[k]≠‘1’
5.1.1.1: Display ‘incorrect number’
5.1.1.2: Go to Step-11
5.2: k←k+1
5.3: Go to Step-5
ProgReference.com
Arrays and Pointers ◾ 181
ProgReference.com
182 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 183
ProgReference.com
184 ◾ Learn Programming with C
before the last '1' in the string; then the condition is checked,
and if true, the statements in the body are executed; before the
condition is re-checked, the index value j is decremented by
one; these steps are repeated until the first character of the
string is reached, at which point the condition becomes false
and the program flow exits the loop*/
if (a[j]=='1')
/*this 'if' checks if the bit a[j] is 1, if it is true,
following statement is executed*/
a[j]='0';
/*this statement flips the bit a[j] from 1 to 0*/
else
/*if the checked bit is not '1', then the condition of above
'if' is false and following statement is executed*/
a[j]='1';
/*this statement flips the bit a[j] from 0 to 1*/
printf("2's complement: %s\n", a);
/*this printf() function displays the text inside the double
quotations as it is on the screen except for string a replaces
the format specifier %s, a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*this closing curly brace specifies the end of main() function; no
statement is executed after that point*/
PROBLEM-11
Write a program to calculate and print transpose of a given matrix.
Step-1: Start
Step-2: Defne ROW←4 and COL←4
Step-3: Initialize i←0
Step-4: If i<ROW
4.1: Initialize j←0
4.2: If j<COL
ProgReference.com
Arrays and Pointers ◾ 185
ProgReference.com
186 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 187
ProgReference.com
188 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 189
ProgReference.com
190 ◾ Learn Programming with C
}
/*this closing curly brace specifies the end of 'for (i=0;
i<ROW; i++)' loop*/
printf("\nTranspose of the matrix is:\n");
/*output function printf() displays the text in the quotations
as it is on the screen except for a newline replaces \n*/
for (i=0; i<ROW; i++){
/*this for loop executes following for loops ROW times; i=0
is the initialization, i<ROW is the condition and i++ is the
increment; initialization is done once at the beginning of the
loop; then condition is checked, if it is true, following for
loop is executed and value of i is incremented by 1 before
the condition is re-checked; these steps continue till the
condition becomes false at which point the program flow exits
the loop; thus in first iteration all elements of first row are
displayed, in second iteration all elements of second row are
displayed, and so on */
for (j=0; j<COL; j++)
/*j=0 is the initialization, j<COL is the condition and
j++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if it
is true, statements in the body are executed and value of
j is incremented by 1 before the condition is re-checked;
these steps continue until the condition becomes false at
which point the program flow exits the loop*/
printf("%d\t", mat2[i][j]);
/*function printf() displays the value of array element
mat2[i][j] in place of format specifier %d on the screen
followed by a tab in place of \t*/
printf("\n");
/*this statement is in the body of first for loop; hence, a
newline is displayed on the screen in each iteration of the
first for loop; that is, a newline is displayed after each
row of the 2-D matrix mat2[][] is displayed*/
}
/*this is the end of 'for (i=0; i<ROW; i++)' loop*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*this closing curly brace specifies the end of main() function; no
statement is executed after that point*/
PROBLEM-12
Write a program to search an item from an array of n items. Te value of n, n items,
and the target item should be given from the keyboard. Te program will display the
target item and its position in the array.
ProgReference.com
Arrays and Pointers ◾ 191
Step-1: Start
Step-2: Read value of num
Step-3: Initialize i←0
Step-4: If i<num
4.1: Read value of array[i]
4.2: i←i+1
4.3: Go to Step-4
ProgReference.com
192 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 193
ProgReference.com
194 ◾ Learn Programming with C
scanf("%d", &num);
/*scanf() function reads an integer from input terminal
and stores the value in the memory spaces allocated for
the num*/
printf("Enter %d items (separated by space):\n", num);
/*printf() function displays the text in the quotation as
it is on the screen except for the value of num replaces the
format specifier %d and a newline replaces \n*/
for (i=0; i<num; i++)
/*i=0 is the initialization, i<num is the condition and i++
is the increment; the initialization is done once at the
beginning of the loop; then the condition is checked, if it
is true, statement in the body is executed and the value of
i is incremented by 1 before the condition is re-checked;
these steps continue until the condition becomes false at
which point the program flow exits the loop*/
scanf("%d", &array[i]);
/*this scanf() function reads an integer from the input
terminal and stores the value in the memory spaces allocated
for the array[]; array[0] is read in the 1st iteration,
array[1] is read in the 2nd iteration, and so on*/
do{
/*the statements, enclosed by curly braces, in the body are
executed; now the condition is checked, if it is true then
the body is executed before the condition is re-checked;
these steps continue until the condition becomes false at
which point the program flow exits the loop*/
check=−1;
/*value of the variable check is initialized to −1,
means the item has not found yet; value of check is
changed only if the item is found in the array*/
printf("\nEnter the item you want to find: ");
/*printf() function displays the text in the quotations
as it is on screen except for a newline replaces \n*/
scanf("%d", &item);
/*function scanf() reads an integer from input terminal
and stores the value in the memory spaces allocated for
the item*/
for (i=0; i<num; i++)
/*i=0 is the initialization, i<num is the condition and
i++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if
it is true, statement in the body is executed and value of
i is incremented by 1 before the condition is re-checked;
these steps continue until the condition becomes false at
which point the program flow exits the loop*/
ProgReference.com
Arrays and Pointers ◾ 195
if (array[i]==item){
/*if item matches with the array element then the
condition is true, and the following statements,
enclosed in the curly braces, are executed; item is
compared with array[0] at 1st iteration, array[1] at
2nd iteration and so on*/
check=0;
/*if the item is found in the array then the
condition of 'if' is true and the value of
check is changed to 0 from −1*/
printf("%d is found in position %d of the"
"array.\n", item, i+1);
/*printf() function displays the text in the
quotations as it is on the screen except for
the value i+1 replaces the format specifier %d
and a newline replaces \n*/
}
/*this closing curly brace specifies the end of
'if' condition*/
if (check==−1)
/*if item is not found in the array, then check=−1; so, the
condition is true and following statement is executed*/
printf("%d is not in the array.\n", item);
/*printf() function displays the text in the quotation
as it is on the screen except for format specifier %d is
replaced by the value of item and \n by a newline*/
printf("Do you want to look for another item? (y/n): ");
/*printf() function displays the text in the quotation as
it is on the screen*/
ch=getche();
/*getche() function reads a character from keyboard, the
character is echoed on the screen without waiting for enter
to be pressed and it is assigned to ch*/
printf("\n");
/*this printf() function displays a newline on the screen
in place of \n*/
}while (ch!='n');
/*do..while loop ends here with condition ends with semicolon;
if the condition is true, the body in the loop is executed
before the condition is re-checked*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*this closing curly brace specifies the end of main() function; no
statement is executed after that point*/
ProgReference.com
196 ◾ Learn Programming with C
PROBLEM-13
Write a program which will read a text and count all occurrences of a particular
character.
Step-1: Start
Step-2: Initialize count←0
Step-3: Read a line of text or character string and save it to array str[]
Step-4: Read a character value of ch
ProgReference.com
Arrays and Pointers ◾ 197
ProgReference.com
198 ◾ Learn Programming with C
int main(){
/*all C program must have a main() function with return type void
or int; here there is no parameter of the main() function and it
returns an integer; opening curly brace specifies start of the
main() function and no statement before that curly brace is executed
by the compiler*/
char str[80], ch;
/*character type array str[] of size 80 and a variable ch are
declared; required memory spaces are allocated for them*/
int count=0, i;
/*integer type variable count is declared and initialized to 0;
integer type variable i is declared; count is used to calculate
and store total number of a particular character in the text;
if the variable is not initialized to 0 then the memory spaces
allocated for the variable may contain some garbage value
which is added in their first summation and gives an incorrect
result*/
printf("Enter a line of text:\n");
/*output function printf() displays the text in the quotations
as it is on the screen except for a newline replaces \n*/
gets(str);
/*function gets() reads a character string or any text from
input terminal and assigned it to the array str[]; gets()
function reads any character from the keyboard including
space, tab, etc. and stops reading as soon as enter is
pressed*/
printf("Enter the character you want to count: ");
/*output function printf() displays the text in the quotations
as it is on the screen*/
scanf("%c", &ch);
/*function scanf() reads a character from input terminal and
stores it in the memory spaces allocated for ch*/
for (i=0; str[i]!='\0'; i++)
/*i=0 is the initialization, str[i]!='\0' is the condition
and i++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if it
is true, statement in the body is executed and value of i is
incremented by 1 before the condition is re-checked; these
steps continue until the condition becomes false at which point
the program flow exits the loop; here the condition remains true
till we reach end of the string or text*/
if(str[i]==ch)
/*if ch matches with the character of the string or text
then the condition is true, and the following statement is
executed; ch is compared with 1st character str[0] at 1st
iteration, 2nd character str[1] at 2nd iteration and so
on*/
ProgReference.com
Arrays and Pointers ◾ 199
count++;
/*if character ch is found in the string or text then
the condition of 'if' is true and the value of count is
incremented by 1*/
printf("The character %c occurs %d times in the string.\n", ch,
count);
/*printf() function displays the text in the quotations as it
is on the screen except for character ch replaces the format
specifier %c, value count replaces %d and a newline replaces
\n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*this closing curly brace specifies the end of main() function; no
statement is executed after that point*/
PROBLEM-14
Write a program to count the number of lines, words, and characters in a given text.
Step-1: Start
Step-2: Initialize end←0, chnm←0, word←0, and line←0
Step-3: If end=0
3.1: Initialize k←0
3.2: Read value of ch
3.3: If ch≠‘\n’
3.3.1: str[k]←ch
3.3.2: Read value of ch
3.3.3: k←k+1
3.3.4: Go to Step-3.3
3.4: str[k]←‘\0’
3.5: If str[0]=‘\0’
3.5.1: Go to Step-4
ProgReference.com
200 ◾ Learn Programming with C
3.6: word←word+1
3.7: Initialize i←0
3.8: If str[i]≠‘\0’
3.8.1: If str[i]=‘ ’
3.8.1.1: Go to Step-3.8.2.1
ProgReference.com
Arrays and Pointers ◾ 201
3.8.2: If str[i]=‘\t’
3.8.2.1: word←word+1
3.8.3: i←i+1
3.8.4: Go to Step-3.8
3.9: line←line+1
3.10: chnm←chnm+strlen(str)
Step-4: Display value of line, word, and chnm
Step-5: Stop
Programming Code of the Solution:
ProgReference.com
202 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 203
ProgReference.com
204 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 205
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*this closing curly brace specifies the end of main() function; no
statement is executed after that point*/
EXERCISES
C) 10
D) None of the above
6) How many bytes are skipped if an integer array pointer is incremented by one to
reach the location of the next element?
A) 1
B) 2
C) 8
D) None of the above
7) Which function is used to allocate memory to an array at run time and initialize
each array element to 0?
A) calloc()
B) malloc()
C) palloc()
D) kalloc()
8) Which function is used to allocate memory to an array at run time without initial-
izing the array elements?
A) calloc()
B) malloc()
C) palloc()
D) kalloc()
9) What is the size of array foat ary[15]?
A) 17
B) 64
C) 16
D) 60
10) What is the dimension of the array ary[5][6]?
A) 5
B) 6
C) 2
D) 30
ProgReference.com
Arrays and Pointers ◾ 207
ProgReference.com
208 ◾ Learn Programming with C
C) It is a formal parameter
D) All of the above
17) Choose a correct statement about a C multidimensional array.
A) First dimension size is optional when initializing the array at the same time
B) Te last dimension size is optional when initializing the array at the same time
C) It is a must to specify all dimensions of a multidimensional array
D) Memory locations of elements of a multidimensional array are not sequential
18) What is a string in C language?
A) A string is a new data type in C
B) A string is an array of characters with a null character as the last element of the
array
C) A string is an array of characters with a null character as the frst element
D) A string is an array of integers with 0 as the last element of the array
19) Which one is the correct statement about array char ary[]=“hello world . . .”?
A) Array ary[] is a string
B) Ary[] has no null character at the end
C) Array size is not mentioned
D) A string cannot contain special characters
20) What is the format specifer used to display string in the C printf() function?
A) %c
B) %C
C) %s
D) %w
21) A char type array is defned as char str[]={‘a’,’t’,‘i’,‘q’}; How do you convert this to
string?
A) str[4] = 0;
B) str[4] = ‘\0’
C) str[]={‘a’,’t’,’i’,’q’,’\0’};
D) All of the above
ProgReference.com
Arrays and Pointers ◾ 209
22) Which of the following function is more appropriate to read multi-word string?
A) scanf()
B) gets()
C) getc()
D) fnds()
23) What is the ASCII value of NULL or ‘\0’?
A) 0
B) 1
C) 10
D) 49
24) A C string elements are always stored in
A) Random memory locations
B) Alternate memory locations
C) Sequential memory locations
D) None of the above
25) What does strcmp() function return if the two strings are identical?
A) 1
B) 0
C) −1
D) True
26) What is actually passed to printf() or scanf() function?
A) Value of string
B) Address of string
C) End address of the string
D) Integer equivalent value of the string
27) What happens if the array size is less than the number of initializers?
A) Generates an error text
B) Extra values are ignored
ProgReference.com
210 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 211
A) strstr()
B) strnstr()
C) strcat()
D) strapp()
34) Which of the following function is used to fnd the frst occurrence of a given sub-
string in another string?
A) strchr()
B) strrchr()
C) strstr()
D) strnset()
35) Which of the following function is used to fnd the last occurrence of a given sub-
string in another string?
A) laststr()
B) strstr()
C) strnstr()
D) strrchr()
36) Which of the following function free the allocated memory?
A) remove(var-name);
B) free(var-name);
C) delete(var-name);
D) dalloc(var-name);
[Ans. B, C, D, B, A, B, A, B, D, C, A, D, C, A, A, D, A, B, A, C, D, B, A, C, B, B, A, D, A, B,
A, A, C, C, D, B]
ProgReference.com
212 ◾ Learn Programming with C
ProgReference.com
Arrays and Pointers ◾ 213
char *ptr=’\0’;
int *ptr=NULL;
ProgReference.com
214 ◾ Learn Programming with C
Problems to Practice
1) Write a program to input and print the elements of an array using pointer.
2) Write a program to fnd the number of elements in an array.
3) Write a program to calculate the average of array elements.
4) Write a program to fnd the length of a string with and without strlen().
5) Write a program to print a string using pointer.
6) Write a program to fnd the frequency of a character in a string.
7) Write a program to copy a string with and without using strcpy().
8) Write a program to fnd both the largest and smallest numbers of an array of
integers.
9) Write a program to generate the frst n terms of a Fibonacci sequence. Also, check
whether a given integer is a Fibonacci number or not.
10) Write a program to fnd the 2’s complement of a given binary number.
11) Write a program to calculate and print transpose of a given matrix.
ProgReference.com
Arrays and Pointers ◾ 215
12) Write a program to search an item from an array of n items. Te value of n, n items,
and the target item should be given from the keyboard. Te program will display
the target item and its position in the array.
13) Write a program which will read a text and count all occurrences of a particular
character.
14) Write a program to count the number of lines, words, and characters in a given text.
15) Write a program to read n number of values in an array and display it in reverse
order.
16) Write a program to copy elements of an array into another array.
17) Write a program to count the total number of duplicate elements in an array.
18) Write a program to insert a new value in a sorted list of arrays.
19) Write a program to delete an element at the desired position from an array.
20) Write a program to fnd the sum of the right diagonals of a matrix.
21) Write a program to fnd the sum of rows and columns of a matrix.
22) Write a program to calculate the determinant of a square matrix.
23) Write a program to check whether a given matrix is an identity matrix.
24) Write a program to check whether an array is a subset of another array.
25) Write a program to swap two numbers using pointers.
26) Write a program to fnd the largest of three numbers using pointers.
27) Write a program to store n elements in an array and print the elements using a
pointer.
28) Write a program to print a string using pointers.
29) Write a program to convert all lowercase vowels to uppercase in a string.
30) Write a program to convert a string from uppercase and lowercase and vice versa.
31) Write a program to sort a set of strings in ascending alphabetic order.
32) Write a program to count vowels and constants in a string using pointers.
33) Write a program that concatenates two strings without using strcat().
34) Write a program to print individual characters of a string in reverse order.
35) Write a program to count each character in a given string.
ProgReference.com
216 ◾ Learn Programming with C
36) Write a program to fnd the maximum between two given numbers using pointers.
37) Write a program to display all the alphabet in English using pointers.
38) Write a program to insert an element at the end of an array.
39) Write a program to display the highest frequency character in a string.
40) Write a program to remove all blank spaces in a string.
41) Write a program that allocates memory for 500 integers using calloc() and then
stores frst 500 natural numbers in that spaces.
42) Write a program to fnd the value of an unknown function from a discrete set
of known data points using the Lagrange interpolation formula. [see Chapter 2,
Problem-17, page 124 for the solution]
ProgReference.com
CHAPTER 4
Functions
A function is a set of statements that performs a specific task. Every C program must
have at least one main() function, but any additional functions can be defined and
used. This chapter presents and discusses two types of functions: library and user-defined.
(1) Library functions: The standard library functions are predefined in the library
(.lib) and declared in several header files (.h). We can call these functions anytime
we need to do the task that that function defines. printf(), scanf(), gets(), puts(),
etc., are some examples. Because functions printf() and scanf() are declared in the
stdio.h header file, the header file must be included before they can be called in a C
program using the preprocessor directive #include. Example is #include stdio.h>
(2) User-defined functions: These functions are defined by the programmer and after-
ward reused as needed.
return_type function_name(argument_list){
//blocks of valid C statements
}
return_type can be any valid data type like int, char, long int, float, double, etc. It can also
be void if the function returns nothing.
Except for any keywords, function name can be any single alphanumeric word, prefer-
ably meaningful.
ProgReference.com
218 ◾ Learn Programming with C
argument_list is a list of variables and their data types that are passed to the func-
tion as input. Te formal parameter refers to the parameters that appear in the function
declaration, whereas the actual parameter refers to the parameters that appear in the
function call.
For example, the following function
takes two foating numbers, a and b, as its arguments and returns the total a+b. Here, a and
b are the formal parameters, whereas x and y are the real parameters in the addition(x, y)
function call.
addition(array_name, array_size); or
addition(num, 4);
ProgReference.com
Functions ◾ 219
Example:
4.7 EXAMPLES
PROBLEM-01
Write a program to swap two numbers using pointers and function.
ProgReference.com
220 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 221
PROBLEM-02
Write a program to calculate the power of a number using function.
ProgReference.com
222 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 223
ProgReference.com
224 ◾ Learn Programming with C
num2 = num2−1;
/*if num1=4 and num2=3 then
after 1st iteration: result=1×4=4, num2=3−1=2
after 2nd iteration: result=4×4=16, num2=2−1=1
after 3rd iteration: result=16×4=64, num2=1−1=0*/
}
/*this closing curly brace specifies the end of while loop*/
return result;
/*this statement returns the final result, which is an integer,
from the user-defined function power() to the point where the
function power() was called*/
}
/*the closing curly brace specifies the end of the definition of
the power() function*/
PROBLEM-03
Write a program to calculate the area of an equilateral triangle using function.
ProgReference.com
Functions ◾ 225
#include <math.h>
/*math.h header file contains the declaration of function sqrt();
the header file must be included using preprocessor directive
#include before the function is called in the program*/
float area(int x);
/*this is the prototype (or declaration) of the user-defined
function area() that must end with a semicolon; area() takes an
integer argument, performs some predefined operations, and returns
a decimal number*/
int main(){
/*all C program must have a main() function with return type void
or int; here there is no parameter of the main() function and it
returns an integer; opening curly brace specifies start of the
main() function and no statement before that curly brace is executed
by the compiler*/
int len;
/*integer type variable len is declared; required memory spaces
are allocated for the variable*/
printf("Enter length of the side of a triangle: ");
/*this displays the text inside the double quotations as it is
on the screen*/
scanf("%d", &len);
/*input function scanf() reads an integer from the keyboard and
stores the value in the memory spaces allocated for the variable
len*/
printf("Area of the equilateral triangle is: %0.2f", area(len));
/*user-defined function area() is called with real parameter
len; the program control flow shifts to the definition of
area(); the function returns a decimal number which is displayed
in place of the format specifier %0.2f with two decimal points
precision; function printf() displays other text inside the
quotations as it is on the screen*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
float area(int x){
/*this is the header for the user-defined function area(), which
must be identical to the function prototype except for no semicolon
is used; the function is defined within the curly braces; in this
definition the value of len replaces the virtual parameter x*/
ProgReference.com
226 ◾ Learn Programming with C
float ar;
/*float type variable ar is declared; required memory spaces
are allocated for the variable; variable ar is local to the
function area() and is not visible outside the function*/
ar = (sqrt(3)/4)*x*x;
/*area of the triangle is calculated and assigned to the variable
ar; library function sqrt() returns √3 which is a decimal
number; hence the result in the right side is a decimal number
though x is an integer*/
return ar;
/*this statement returns the value of ar, which is a decimal
number, from the user-defined function area() to the point
where the function area() was called*/
}
/*this closing curly brace specifies the end of the definition of
the area() function*/
PROBLEM-04
Write a program that displays the prime numbers from 1 to n. Te value of n should be
given interactively through the terminal.
Step-1: Start
Step-2: Read value of n
Step-3: If n<=1
3.1: Display ‘invalid entry’
3.2: Read value of n
3.3: Go to Step-3
Step-4: Display 2
Step-5: Initialize i←3
Step-6: If i<=n
6.1: Call function prime(i)
6.2: If prime(i)=1
6.2.1: Display value of i
6.3: i←i+2
6.4: Go to Step-6
Step-7: Display newline
Step-8: Stop
Algorithm for the function prime(x):
Step-1: Initialize j←2
Step-2: If j<=x/2
2.1: If x%j=0
ProgReference.com
228 ◾ Learn Programming with C
2.1.1: Return 0
2.2: j←j+1
2.3: Go to Step-2
Step-3: Return 1
Programming Code of the Solution:
ProgReference.com
Functions ◾ 229
ProgReference.com
230 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 231
if ((x%j)==0)
/*here, the modulus operator % gives remainder of the
division; number x is divided by the value of j; if remainder
of the division operation is 0, the condition is true and
the following statement is executed*/
return 0;
/*if the condition is true then the function
immediately returns 0 to the point where the function
was called*/
return 1;
/*here the function prime() returns 1 to the point from where
the function was called; this statement is executed only if
there is no j for which the above if condition is true*/
}
/*this closing curly brace specifies the end of prime() function
definition*/
PROBLEM-05
Write a program to calculate the standard deviation of an array of values. Te array
elements are read from the terminal. Use functions to calculate the standard deviation
and mean.
ProgReference.com
232 ◾ Learn Programming with C
Step-1: Start
Step-2: Defne SIZE←5
Step-3: Initialize i←0
Step-4: If i<SIZE
4.1: Read value of value[i]
4.2: i←i+1
4.3: Go to Step-4
Step-5: Call function std_dev(value, SIZE)
Step-6: Stop
ProgReference.com
Functions ◾ 233
ProgReference.com
234 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 235
int i;
/*an integer type variable is declared and required memory
space is allocated for i*/
printf("Please enter any %d values (separated by" "space):\n",
SIZE);
/*function printf() displays the text in the quotations as it is
on the screen except for the value of SIZE replaces the format
specifier %d and a newline replaces \n*/
for(i=0; i<SIZE; i++)
/*this for loop reads SIZE number data; here i=0 is the
initialization, i<SIZE is the condition and i++ is the increment;
initialization is done once at the beginning of the loop; then
the condition is checked, if it is true, statement in the body
is executed and the value of i is incremented by 1 before
the condition is re-checked; these steps continue until the
condition becomes false at which point the program flow exits
the loop*/
scanf("%f", &value[i]);
/*scanf() function reads a decimal number from the input
terminal and stores the value in the memory spaces
allocated for the array; value[0] is read in the 1st
iteration, value[1] is read in the 2nd iteration, and
so on*/
printf("Standard deviation is: %0.2f\n", std_dev(value,
SIZE));
/*here std_dev() function takes the array and SIZE as its real
parameters and program control flow shifts to the function
definition; the function does some predefined operations and
returns a floating-point number that is displayed in place of
the format specifier %0.2f with two decimal points precision;
other text in the quotations is displayed as it is on the screen
except for a newline replaces \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*this closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
float std_dev(float x[], int n){
/*this is the header for the user-defined function std_dev(),
which must be identical to the function prototype except for
no semicolon is used; the function is defined within the curly
braces*/
float z, sum=0.0;
/*a float type variable z is declared; another float type
variable sum is declared and initialized to 0.0; if sum is
ProgReference.com
236 ◾ Learn Programming with C
not initialized to 0.0 then the memory space allocated for the
variable may contain some garbage value which is added in the
first summation operation and gives incorrect result*/
int j;
/*an integer type variable is declared; compiler allocates
required spaces in memory for the variable*/
z=mean(x, n);
/*user-defined function mean() is called with real parameters x
and n where x is an array and n is its size; the program control
flow shifts to the definition of the mean() function; the
function does some predefined operations and returns a decimal
number that is assigned to z*/
for (j=0; j<n; j++)
/*j=0 is the initialization, j<n is the condition and j++ is the
increment; initialization is done once at the beginning of the
loop; then the condition is checked, if it is true, statement
in the body is executed and the value of j is incremented by 1
before the condition is re-checked; these steps continue until
the condition becomes false at which point the program flow
exits the loop*/
sum+=(z−x[j])*(z−x[j]);
/*this operation is equivalent to sum=sum+(z−x[j])2; each
iteration considers a single array element x[j], therefore
the iteration begins with the first array element x[0] and
ends with the last array member x[n−1]*/
return sqrt(sum/n);
/*at that point, function std_dev() returns square-root of the
division sum/n to the point where the function was called*/
}
/*this closing curly brace specifies the end of the definition of
function std_dev()*/
float mean(float x[], int n){
/*this is the header for the user-defined function mean(), which
must be identical to the function prototype except for no semicolon
is used; the function is defined within the curly braces*/
float sum=0.0;
/*a float type variable sum is declared and initialized to 0.0;
if sum is not initialized to 0.0 then the memory space allocated
for the variable may contain some garbage value that is added
in the first summation operation and gives incorrect result*/
int k;
/*an integer type variable is declared; compiler assigns required
spaces in memory for the variable*/
for (k=0; k<n; k++)
/*this for loop sequentially adds all array elements; k=0 is the
initialization, k<n is the condition and k++ is the increment;
ProgReference.com
Functions ◾ 237
PROBLEM-06
Write a program that computes and displays the factorial for any given number m
using a loop and recursive function.
ProgReference.com
238 ◾ Learn Programming with C
Step-1: Start
Step-2: Initialize num←1
Step-3: Read value of m
Step-4: Display value of fact(m)
Step-5: Initialize n←1
Step-6: If n<=m
6.1: num←num×n
6.2: n←n+1
6.3: Go to Step-6
Step-7: Display values of m and num
Step-8: Stop
Step-1: If y=0
1.1: Return 1
Step-2: p←y×fact(y−1) [call function fact()]
Step-3: Return p
ProgReference.com
Functions ◾ 239
ProgReference.com
240 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 241
PROBLEM-07
Write a program to fnd the GCD (greatest common divisor) of two given integers
using both recursive function and loop.
ProgReference.com
242 ◾ Learn Programming with C
Step-1: Start
Step-2: Read values of a and b
Step-3: If a>b
3.1: max←b
3.2: Go to Step-5
Step-4: max←a
Step-5: Initialize i←1
ProgReference.com
Functions ◾ 243
Step-6: If i<=max
6.1: If a%i=0
6.1.1: If b%i=0
6.1.1.1: gcd←i
6.2: i←i+1
6.3: Go to Step-6
Step-7: Display value of gcd and gcdf(a, b) [call function gcdf()]
Step-8: Stop
Step-1: If d>c
1.1: Return gcdf(d, c)
Step-2: If d=0
2.1: Return c
Step-3: Return gcdf(d, c%d)
ProgReference.com
244 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 245
max=a;
/*this statement assigns the smaller value a to max, if a=b
then also value of a is assigned to max*/
for (i=1; i<=max; i++){
/*this for loop computes the gcd of the two variables; i=1 is
the initialization, i<=max is the condition and i++ is the
increment; initialization is done once at the beginning of the
loop; then condition is checked, if it is true, statement in the
body is executed and the value of i is incremented by 1 before
the condition is re-checked; these steps continue until the
condition becomes false at which point the program flow exits
the loop*/
if (a%i==0 && b%i==0)
/*if both a and b are divisible by same number I, the
statement in the body of 'if' is executed; in 1st iteration
both a and b is divided by i=1, in 2nd iteration both a and
b is divided by i=1, and so on*/
gcd=i;
/*if both a and b are divisible by same number i then
the value of i is assigned to gcd*/
}
/*this closing curly brace specifies the end of the 'for'
loop*/
printf("\nUsing non-recursive:\nGCD of %d and %d is: %d\n", a,
b, gcd);
/*this printf() displays the text in the double quotations as it
is on the screen except for the value of a replaces the first
format specifier %d, the value of b replaces the second %d, the
value of gcd replaces the third %d and a newline replaces the
\n*/
printf("\nUsing recursive function:\nGCD of %d and %d is:"
"%d\n\n", a, b, gcdf(a, b));
/*user-defined function gcdf() is called with real parameters a
and b, program control flow shifts to the definition of gcdf()
function, gcdf() does some predefined operation, and returns an
integer that is displayed in place of the third format specifier
%d; output function printf() displays the text in the double
quotes as it is on the screen except for the value of a replaces
the first %d, value of b replaces the second %d and a newline
replaces the \n*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
ProgReference.com
246 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 247
PROBLEM-08
Write a program to sort n number of integers in ascending order. Te program will
display the data before sorting and afer sorting.
Step-1: Start
Step-2: Defne SIZE←10
Step-3: Initialize i←0
Step-4: If i<SIZE
4.1: Read value of marks[i]
4.2: i←i+1
4.3: Go to Step-4
Step-5: Initialize i←0
Step-6: If i<SIZE
6.1: Display value of marks[i]
6.2: i←i+1
6.3: Go to Step-6
Step-7: Call function sort(marks, SIZE)
Step-8: Initialize i←0
Step-9: If i<SIZE
9.1: Display value of marks[i]
9.2: i←i+1
9.3: Go to Step-9
Step-10: Stop
ProgReference.com
Functions ◾ 249
2.2.1.3: x[j]←temp
2.2.2: j←j+1
2.2.3: Go to Step-2.2
2.3: i←i+1
2.4: Go to Step-2
Step-3: Return
ProgReference.com
250 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 251
ProgReference.com
252 ◾ Learn Programming with C
int i, j, temp;
/*three integer type variables are declared; required memory
spaces are allocated for these variables; these variables are
local to the function sort() and are not accessible outside that
function*/
/*bubble sort algorithm is used to sort the data; body of 1st
for loop contains the 2nd for loop; 2nd for loop sequentially
compares each array element with other elements and saves the
largest number in the last array element x[m−1], this is the
first iteration of 1st 'for' loop; in the 2nd iteration of 1st
'for' loop, 2nd 'for' loop sequentially compares each array
element with others except for the last array element and
the 2nd largest element is positioned in x[m−2]; these steps
continue until the smallest element is placed in the first array
position x[0]*/
for (i=1; i<=m−1; i++)
/*i=1 is the initialization, i<m−1 is the condition and i++ is
the increment; initialization is done once at the beginning of
the loop; then the condition is checked, if it is true, statement
in the body is executed and the value of i is incremented by 1
before the condition is re-checked; these steps continue until
the condition becomes false at which point the program flow
exits the loop*/
for (j=1; j<=m−i; j++)
/*each iteration of the 1st for loop places a single array
element in its proper position; as a result, the number of
elements to compare is reduced by 1 after each iteration;
here j=1 is the initialization, j<m−i is the condition and
j++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if it
is true, statement in the body is executed and the value of
j is incremented by 1 before the condition is re-checked;
these steps continue until the condition becomes false at
which point the program flow exits the loop*/
if (x[j−1]>=x[j]){
/*two contiguous array elements are compared, if the
larger number stays above the smaller one, the condition
is true and following statements are executed to swap
them to keep the smaller number above the larger
one*/
temp=x[j−1];
/*array element x[j−1] is assigned to the variable
temp*/
x[j−1]=x[j];
/*array element x[j] is stored in the array element
x[j−1]*/
ProgReference.com
Functions ◾ 253
x[j]=temp;
/*value of temp(=x[j−1]) is stored in the array
element x[j]*/
}
/*this closing curly brace specifies the end of 'if'*/
}
/*the closing curly brace specifies the end of the sort() function’s
body; the program control flow, at this point, returns to the point
where the function was called*/
PROBLEM-09
Write a program to produce a matrix that is the sum of two given matrices of same size.
Also produce a matrix that is the product of two given matrices by checking compatibility.
ProgReference.com
254 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 255
Step-1: Start
Step-2: Defne ROW1←3, COL1←4, ROW2←4 and COL2←5
Step-3: Initialize i←0
Step-4: If i<ROW1
4.1: Initialize j←0
4.2: If j<COL1
4.2.1: Read value of mat1[i][j]
4.2.2: j←j+1
4.2.3: Go to Step-4.2
ProgReference.com
256 ◾ Learn Programming with C
4.3: i←i+1
4.4: Go to Step-4
Step-5: Initialize i←0
Step-6: If i<ROW1
6.1: Initialize j←0
6.2: If j<COL1
6.2.1: Read value of mat2[i][j]
6.2.2: j←j+1
6.2.3: Go to Step-6.2
6.3: i←i+1
6.4: Go to Step-6
Step-7: Initialize i←0
Step-8: If i<ROW2
8.1: Initialize j←0
8.2: If j<COL2
8.2.1: Read value of mat3[i][j]
8.2.2: j←j+1
8.2.3: Go to Step-8.2
8.3: i←i+1
8.4: Go to Step-8
Step-9: Call function addition(mat1, mat2, sum, ROW1)
Step-10: Initialize i←0
Step-11: If i<ROW1
11.1: Initialize j←0
11.2: If j<COL1
11.2.1: Display value of sum[i][j]
11.2.2: j←j+1
11.2.3: Go to Step-11.2
ProgReference.com
Functions ◾ 257
ProgReference.com
258 ◾ Learn Programming with C
Step-1: If COL1=row2
1.1: Initialize i←0
1.2: If i<row1
1.2.1: Initialize j←0
1.2.2: If j<COL2.
1.2.2.1: matrix3[i][j]←0
1.2.2.2: Initialize k←0.
1.2.2.3: If k<COL1
1.2.2.3.1: matrix3[i][j]← matrix3[i][j]+matrix1[i][k]×matrix2[k][j]
1.2.2.3.2: k←k+1
1.2.2.3.3: Go to Step-1.2.2.3
1.2.2.4: j←j+1
1.2.2.5: Go to Step-1.2.2
1.2.3: i←i+1
1.2.4: Go to Step-1.2
1.3: Go to Step-4
Step-2: Display ‘not permissible size’
Step-3: Stop.
Step-4: Return.
ProgReference.com
Functions ◾ 259
ProgReference.com
260 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 261
ProgReference.com
262 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 263
ProgReference.com
264 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 265
printf("\n");
/*this printf() is in the body of the 1st for loop; hence
a newline is displayed on the screen after each row of the
2-D matrix sum[][] is displayed*/
}
/*this closing curly brace specifies the end of the 1st for
(i=0; i<ROW1; i++) loop*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
void addition(int matrix1[][COL1], int matrix2[][COL1], int
matrix3[][COL1], int row){
/*this is the header for the user-defined function addition(),
which must be identical to the function prototype except for
no semicolon is used; the function is defined within the curly
braces*/
int i, j;
/*two integer type variables are declared; required memory
spaces are allocated for these variables*/
for (i=0; i<row; i++)
/*i=0 is the initialization, i<row is the condition and i++ is
the increment; initialization is done once at the beginning of
the loop; then the condition is checked, if it is true following
for loop is executed and the value of i is incremented by 1
before the condition is re-checked; these steps continue until
the condition becomes false at which point the program flow
exits the loop; at 1st iteration we access all elements of the
1st row, at 2nd iteration we access all elements of the 2nd row,
and so on*/
for (j=0; j<COL1; j++)
/*j=0 is the initialization, j<COL1 is the condition and
j++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if
it is true, statements in the body are executed and the
value of j is incremented by 1 before the condition is re-
checked; these steps continue until the condition becomes
false at which point the program flow exits the loop*/
matrix3[i][j]=matrix1[i][j]+matrix2[i][j];
/*here corresponding elements of matrix1 and matrix2
are added and the sum is placed in the corresponding
position of matrix3; for example-
At 1st iteration- matrix3[0][0]=matrix1[0][0]+matrix2[0]
[0]
ProgReference.com
266 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 267
ProgReference.com
268 ◾ Learn Programming with C
PROBLEM-10
Write a program that uses functions to insert a substring into a given main-string
from a given position. Also, defne a function to delete n characters from a given
position in a given string.
ProgReference.com
Functions ◾ 269
(Continued)
FIGURE 4.7
ProgReference.com
270 ◾ Learn Programming with C
Step-1: Start
Step-2: Read values of mnstr, sbstr, and psn
Step-3: Call function insert(mnstr, sbstr, restr, psn)
Step-4: Display string restr
Step-5: Read value of psn and numch
Step-6: Call function delet(restr, psn, numch)
Step-7: Display string restr
Step-8: Stop
Step-1: len←strlen(str1)
Step-2: Initialize b←pos+num−1 and a←pos−1
Step-3: If i<len-num
3.1: str1[a]←str1[b]
3.2: b←b+1
3.3: a←a+1
3.4: Go to Step-3
Step-4: str1[a]←‘\0’
Step-5: Return.
ProgReference.com
272 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 273
ProgReference.com
Functions ◾ 275
str3[i]=str1[i];
/*at 1st iteration str3[0]=str1[0], at 2nd iteration
str3[1]=str1[1], and so on*/
k=i;
/*when i=pos−1, the program exits the previous 'for' loop;
i=pos−1 is assigned to k that is used as index of str1[] to
identify rest of the characters in the string to copy*/
for (i=pos−1; i<pos+len2−1; i++){
/*this for loop copies the sub-string str2[] at the end of
str3[] in which first pos characters of str1[] was copied; here
i=pos−1 is the initialization, i<pos+len2−1 is the condition
and i++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if it is
true, following statement in the body is executed and the value
of i is incremented by 1 before the condition is re-checked;
these steps continue until the condition becomes false at which
point the program flow exits the loop*/
str3[i]=str2[j];
/*at 1st iteration str3[pos−1]=str2[0], at 2nd iteration
str3[pos]=str2[1], at 3rd iteration str3[pos+1]=str2[2],
and so on*/
j+=1;
/*index value of str2[] is incremented by 1 in each iteration
of the loop*/
}
/*this closing curly brace specifies the end of the for loop
body*/
for (i=pos+len2−1; i<len1+len2; i++){
/*this for loop copies rest of the string str1[] (pos−1 to end)
at the end of str3[] in which first pos (0 to pos−1) characters
of str1[] was copied and then str2[] was concatenated; here
i=pos+len2−1 is the initialization, i<len1+len2 is the
condition and i++ is the increment; initialization is done
once at the beginning of the loop; then the condition is
checked, if it is true, following statement in the body
is executed and the value of i is incremented by 1 before
the condition is re-checked; these steps continue until the
condition becomes false at which point the program flow exits
the loop*/
str3[i]=str1[k];
/*at 1st iteration str3[pos+len2−1]=str1[pos−1],
at 2nd iteration str3[pos+len2]=str1[pos],
at 3rd iteration str3[pos+len2+1]=str2[pos+1], and so on*/
k=k+1;
/*index value of str1[] is incremented by 1 in each iteration
of the loop*/
ProgReference.com
276 ◾ Learn Programming with C
}
/*this closing curly brace specifies the end of the for loop
body*/
str3[i]='\0';
/*last character of array str3[] is set to NULL to define it
as string*/
}
/*the closing curly brace specifies the end of the insert() function’s
body; the program control flow, at this point, returns to the point
where the function was called*/
void delet(char str1[], int pos, int num){
/*this is the header for the user-defined function delet(), which
must be identical to the function prototype except for no semicolon
is used; the function is defined within the curly braces*/
int len, a, b;
/*three integer type variables len, a and b are declared;
required memory spaces are allocated for these variables*/
len=strlen(str1);
/*built-in library function strlen() returns length of the
string str1 that is assigned to len*/
/*to delete a sub-string of size num that starts at position
pos−1, we keep the string str1[] unchanged from 0 to pos−2;
after that we copy characters from position pos−1+num to the end
(=len−num−1), skipping all characters in the middle*/
b=pos+num−1;
/*b is initialized to pos+num−1*/
for (a=pos−1; a<len−num; a++){
/*a=pos−1 is the initialization, a<len−num is the condition
and a++ is the increment; initialization is done once at the
beginning of the loop; then the condition is checked, if it is
true, following statement in the body is executed and the value
of a is incremented by 1 before the condition is re-checked;
these steps continue until the condition becomes false at which
point the program flow exits the loop*/
str1[a]=str1[b];
/*at 1st iteration str1[pos−1]=str1[pos+num−1],
at 2nd iteration str1[pos]=str1[pos+num],
at 3rd iteration str1[pos+1]=str1[pos+num+1], and so on*/
b=b+1;
/*index value of source array is incremented by 1 in each
iteration of the loop*/
}
/*this closing curly brace specifies the end of the for loop
body*/
str1[a]='\0';
/*last character of array str1[] is set to NULL to define it
as string*/
ProgReference.com
Functions ◾ 277
}
/*the closing curly brace specifies the end of the delet() function’s
body; the program control flow, at this point, returns to the point
where the function was called*/
PROBLEM-11
Using pointers, write a function that receives a character string and word as arguments
and deletes all occurrences of this word in the string.
Step-1: Start
Step-2: Read values of txt and wrd
Step-3: lnh←strlen(wrd)
Step-4: x←index(txt, wrd) [call function index()]
Step-5: If x≠0
5.1: Call delet(txt, x−1, lnh)
5.2: x←index(txt, wrd) [call function index()]
5.3: Go to Step-5
Step-6: Display string txt
Step-7: Stop
ProgReference.com
278 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 279
ProgReference.com
280 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 281
ProgReference.com
282 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 283
ProgReference.com
284 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 285
ProgReference.com
286 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 287
PROBLEM-12
Write a program to solve a polynomial equation and its derivative.
Step-1: Start.
Step-2: Read value of deg.
Step-3: Initialize i←0
ProgReference.com
288 ◾ Learn Programming with C
Step-4: If i<=deg
4.1: Read value of coef[i]
4.2: i←i+1
4.3: Go to Step-4
Step-5: Read value of x
Step-6: y←poly(coef, deg, x) [call function poly()]
Step-7: dy←deriv(coef, deg, x) [call function deriv()]
Step-8: Display values of x, y and dy
Step-9: Stop.
Algorithm for the function poly(foat coef1[], int deg1, foat x1):
Step-1: res←coef1[deg1]
Step-2: Initialize j←deg1
Step-3: If j>=1
3.1: res←(coef1[j−1]+x1*res)
3.2: j←j−1
3.3: Go to Step-3
Step-4: Return value of res.
ProgReference.com
Functions ◾ 289
Algorithm for the function deriv(foat coef1[], int deg1, foat x1):
2.2: dp←(deg1−k)×coef1[deg1−k]×ps;
2.3: sum←sum+dp
2.4: k←k+1
2.5: Go to Step-2
ProgReference.com
290 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 291
ProgReference.com
292 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 293
ProgReference.com
294 ◾ Learn Programming with C
dp = (deg1−k)*coef1[deg1−k]*ps;
/*for the function f(x)=2x3+3x−1
At 1st iteration, dp=(3−0)×coef1[3−0]×ps=3×2×x12=6x12
At 2nd iteration, dp=(3−1)×coef1[3−1]×ps=2×0×x1=0
At 3rd iteration, dp=(3−2)×coef1[3−2]×ps=1×3×x10=3*/
sum = sum+dp;
/*for the function f(x)=2x3+3x−1
At 1st iteration, sum=0+6x12=6x12
At 2nd iteration, sum=6x12+0=6x12
At 3rd iteration, sum=6x12+3 which is the derivative of
2x3+3x−1 at x1*/
}
return sum;
/*function deriv() returns the value of sum to the point where
the function was called*/
}
/*this closing curly brace specifies the end of poly() function
definition*/
EXERCISES
void main(){
int num=10;
printf(“%d”, num);}
ProgReference.com
Functions ◾ 295
A) extern
B) auto
C) register
D) static
4) Which of the following is not a valid storage class?
A) auto
B) extern
C) dynamic
D) register
5) Prototype of a function means _______.
A) Name of function
B) Parameters of function
C) Declaration of function
D) All of the above
6) Which of the following will not return a value?
A) void
B) int
C) null
D) char
7) Which of the following return-type cannot be used for a function in C?
A) char *
B) struct
C) void
D) None of the above
8) Which operator is used to receive the variable number of arguments for a function?
A) Ellipses (…)
B) Backward slash (\)
C) Backward slash and asterisk (\*)
D) Semicolon (;)
ProgReference.com
296 ◾ Learn Programming with C
9) How many values can a function return to the caller using the return keyword?
A) It cannot return any value
B) Only one
C) Only two
D) Multiple
10) Recursive functions are executed in a _______.
A) FIFO order
B) Load balancing
C) Parallel
D) LIFO order
11) How many functions can be called in a function?
A) Any function can call only a single function
B) A function cannot call any other function
C) Any function can call one or more functions
D) A function cannot call any user-defned function
[Ans. B, B, B, C, D, A, D, A, B, D, C]
ProgReference.com
Functions ◾ 297
ProgReference.com
298 ◾ Learn Programming with C
ProgReference.com
Functions ◾ 299
Problems to Practice
ProgReference.com
300 ◾ Learn Programming with C
19) Write a program to calculate the sum of numbers from 1 to n using recursion.
20) Write a program to display Fibonacci Series using recursion.
21) Write a program to fnd the sum of digits of a number using recursion.
22) Write a program to reverse a string using recursion.
23) Write a program to multiply two matrices using recursion.
24) Write a program to check whether a number can be expressed as the sum of two
prime numbers.
25) Write a program that converts a binary number to decimal and vice versa.
26) Write a function to fnd square root of a number.
27) Write a function to display Hot or Cold depending on the temperature entered by a
user.
ProgReference.com
CHAPTER 5
T he structure is a collection of variables under a single name that can be of the same
type or different types. A union is an object similar to a structure that allows storing
different data types, but all its members share the same memory location.
5.1 STRUCTURE
Structure is a group of different variables of the same or different data types under a single
name. Syntax of creating a struct variable is as follows:
struct struct_name{
data_type member1;
data_type member2;
data_type member3;
};
struct keyword is short form of structured data type used to create a structure in C.
struct_name is the name of the structure and can be any word other than any keyword.
All the data type inside the curly braces can be of same type or of different types.
Variable of a structure can be declared as follows:
Members of the structured data type can be accessed through dot (.) operator as follows:
var_name1.member1, var_name2.member3, var_name1.member2
Examples are as follows:
ProgReference.com
302 ◾ Learn Programming with C
Members of the structured data type can also be accessed through arrow (->) operator. To
do that, we frst have to create pointer to structure. Example:
One or more structures can be used inside another structure known as the nested struc-
ture. Members of the nested structures are accessed through the chain of dot (.) operator.
5.2 UNION
A union is a user-defned data type that may consist of same or diferent multiple data
types. Te main diference between structure and union is that structures allocate enough
memory space for all of its members, whereas union hold the memory space equal to the
size of its largest element and share the same memory for all of its members. Example:
Like structures, union members can also be accessed using dot (.) or pointer operator.
Example:
5.3 ENUM
Te enum data type consists of integral constants. Te element’s values are 0, 1, 2, . . ., but
the default values can be changed during declaration if needed. Examples are as follows:
ProgReference.com
Structure and Union ◾ 303
(1) Linear data structure: Data are placed in sequential order in a linear data structure.
Tey are simple to implement since the elements are arranged in a specifc order.
Some famous linear data structures are as follows:
(a) Array data structure: An array’s elements are all of the same data type, and they
are stored in continuous memory.
(b) Stack data structure: Te LIFO (last in, frst out) principle governs the storage
of elements, which means that the last element in a stack is removed frst.
(c) Queue data structure: Te FIFO (frst in, frst out) principle governs the storage
of elements; that is, the frst element in a queue is removed frst.
(d) Linked list data structure: A series of nodes connects data elements, and each
node contains data items as well as the addresses of the next and prior nodes.
(2) Nonlinear data structure: Data elements in nonlinear data structures are not placed
in any particular order. Instead, they are organized in a hierarchical fashion, with
one element connected to one or more others. Graph and tree-based data structures
are two types of nonlinear data structures.
ALGORITHM
A set of well-defned instructions for solving a particular problem is known as an algo-
rithm. Tat is, an algorithm is a step-by-step procedure to get the desired output. A good
algorithm may have the following qualities:
(d) Programming code should not be included in an algorithm. Instead, the algorithm
should be designed in a way that allows it to be used in a variety of programming
languages.
From the data structure point of view, the following are some important categories of
algorithms:
• A data item
• An address of another node
Te address of the frst node is usually specifed as head, and the next portion of the last
node always points to NULL. Te following example shows how a linked list is created
using the structure of a linked list node.
ProgReference.com
Structure and Union ◾ 305
A linked list can break the chain, rejoin it, insert a new node to the chain, delete any node
from the chain, etc.
(a) Singly linked list: It is the most common type of linked list. Each node contains data
and a pointer to the next node. Tat type of node is represented as follows:
(b) Doubly linked list: A doubly linked list can be traversed in both forward and back-
ward directions. Each node of a doubly linked list contains data and two pointers
– one to the next node and another to the previous node. Tat type of node is repre-
sented as follows:
(c) Circular linked list: Singly linked circular linked list is a variation of a singly linked
list in which the next pointer of the last item points to the frst item.
ProgReference.com
306 ◾ Learn Programming with C
A doubly linked circular linked list is a variation of a doubly linked list in which the next
pointer of the last item points to the frst item and the previous pointer of the frst item
points to the last item.
5.7 EXAMPLES
PROBLEM-01
Write a program to read and display information of a student using structure.
ProgReference.com
Structure and Union ◾ 307
ProgReference.com
308 ◾ Learn Programming with C
PROBLEM-02
Write a program to read and display information of n number of students (roll no.,
name, and marks) using structure and dynamic memory allocation.
ProgReference.com
Structure and Union ◾ 309
ProgReference.com
310 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 311
ProgReference.com
312 ◾ Learn Programming with C
PROBLEM-03
Write a program to add two complex numbers using structure.
ProgReference.com
Structure and Union ◾ 313
ProgReference.com
314 ◾ Learn Programming with C
scanf("%f", &num1.imag);
/*scanf() function reads a decimal value from the input terminal
and stores it in the 2nd member of the num1 structure which is
accessed through dot (.) operator num1.imag*/
printf("Enter 2nd complex number:\nreal: ");
/*this displays the text inside the double quotations as it is
on the screen except for a newline replaces \n*/
scanf("%f", &num2.real);
/*function scanf() reads a decimal value from the input terminal
and stores it in the 1st member of the num2 structure which is
accessed through dot (.) operator num2.real*/
printf("imaginary: ");
/*this displays the text inside the double quotation as it is
on the screen*/
scanf("%f", &num2.imag);
/*scanf() function reads a decimal value from the input terminal
and stores it in the 2nd member of the num2 structure which is
accessed through dot (.) operator num2.imag*/
sum.real = num1.real + num2.real;
/*using dot (.) operator we access members of the struct complex
type variables; real parts of both num1 and num2 are added and
the result is stored in member real of the struct complex type
variable sum*/
sum.imag = num1.imag + num2.imag;
/*imaginary parts of both num1 and num2 are added and the result
is stored in member imag of the struct complex type variable
sum*/
printf("%.2f+j%.2f + %.2f+j%.2f = %.2f+j%.2f", num1.real,
num1.imag, num2.real, num2.imag, sum.real, sum.imag);
/*output function printf() displays the text as it is on
the screen except for the value of num1.real replaces the
1st format specifier %.2f with two decimal points precision,
value of num1.imag replaces the 2nd %.2f, value of num2.real
replaces the 3rd %.2f, value of num2.imag replaces the 4th
%.2f, value of sum.real replaces the 5th %.2f, and the value
of sum.imag replaces 6th %.2f; all the variables are members
of the struct complex type variable, and accessed using dot
(.) operator*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
ProgReference.com
Structure and Union ◾ 315
PROBLEM-04
Write a program to create and display a singly linked list of n nodes.
ProgReference.com
316 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 317
ProgReference.com
318 ◾ Learn Programming with C
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
void create(int n){
/*definition of create() function starts here with function header and
body; function header is same as function prototype without semicolon;
body of the function is enclosed in curly braces; real argument that is
passed during the function call replaces virtual parameter n*/
struct node *fnNode, *tmp;
/*two struct node type pointers are declared; fnNode and tmp
are the addresses of two struct node type variables each has
two members- num to store an integer and next to store address
of another struct node type variable*/
int nm, i;
/*two integer type variables are declared; required memory spaces
are allocated for the variables; these variables are local to the
function create() and is not visible outside that function*/
stnode = (struct node *)malloc(sizeof(struct node));
/*sizeof() function computes the size of struct node type data,
needed to store an integer and address of another node; required
memory spaces are dynamically allocated by malloc(); address
of the memory space is assigned to struct node type pointer
variable stnode*/
if (stnode == NULL)
/*if memory cannot be assigned successfully malloc() returns
a NULL to stnode; if the condition of if is true following
statement is executed*/
printf("Memory cannot be allocated.");
/*printf() function displays the text in the quotations as
it is on the screen*/
else{
/*if the above condition of if is false, following statements,
enclosed in the curly braces, are executed*/
printf("\nInput data for node #1: ");
/*printf() function displays the text in the double
quotations as it is on the screen except for a newline
replaces \n*/
scanf("%d", &nm);
/*scanf() function reads an integer from input terminal
and stores the value in the memory spaces allocated for
the nm*/
stnode->num = nm;
/*value of nm is assigned to the member num of the first
node stnode of the linked list*/
stnode->next = NULL;
/*next pointer of the first node is set to NULL; there is
no more node after that in the linked list*/
ProgReference.com
Structure and Union ◾ 319
tmp = stnode;
/*struct node type pointer tmp refers to the first node of
the linked list stnode*/
for (i=2; i<=n; i++){
/*this for loop creates other nodes of the linked list
other than the first node; here i=2 is initialization, i<=n
is condition and i++ is increment; initialization is done
once at the beginning of the loop; then the condition is
checked, if it is true statements in the body, enclosed by
curly braces, are executed and value of i is incremented by
1 before the condition is re-checked; these steps continue
until the condition becomes false in which case the program
control flow exits the loop*/
fnNode = (struct node *)malloc(sizeof(struct node));
/*sizeof() function computes the size of struct node
type data, needed to store an integer and address of
another node; required memory spaces are dynamically
allocated by malloc(); address of the memory space
is assigned to struct node type pointer variable
fnNode*/
if (fnNode == NULL){
/*if memory cannot be assigned successfully malloc()
returns a NULL to fnNode; if the condition of if is true
following statements, enclosed in the curly braces, are
executed*/
printf("Memory cannot be allocated.");
/*output function printf() displays the text in the
quotations as it is on the screen*/
break;
/*as memory cannot be allocated for the node, the
program control flow immediately exits the loop*/
}
/*this closing curly brace specifies the end of 'if'
with condition (fnNode == NULL)*/
else{
/*if the above condition of if is false, memory is
successfully allocated for the node and the following
statements, enclosed in the curly braces, are executed*/
printf("Input data for node #%d: ", i);
/*output function printf() displays the text in the
quotations as it is on the screen except for the
value of i replaces the format specifier %d*/
scanf("%d", &nm);
/*scanf() function reads an integer from input
terminal and stores the value in the memory spaces
allocated for the nm*/
fnNode->num = nm;
ProgReference.com
320 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 321
PROBLEM-05
Write a program to create a doubly linked list of n nodes and display it in reverse order.
ProgReference.com
322 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 323
ProgReference.com
324 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 325
ProgReference.com
326 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 327
ProgReference.com
328 ◾ Learn Programming with C
PROBLEM-06
Write a program to insert a new node at the beginning of a circular linked list.
ProgReference.com
Structure and Union ◾ 329
ProgReference.com
330 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 331
/*new data type struct node is created using keyword struct; members
of struct node are declared in the curly braces*/
int item;
/*integer type variable item is declared, this is a member of
the data type struct node*/
struct node *next;
/*struct node type pointer next is declared as second member
of the data type struct node; next contains address of another
node*/
} *stnode;
/*definition of the structured data type must end with a semicolon;
struct node type pointer stnode of the defined data type is declared
here*/
void create(int n);
/*this is the prototype (or declaration) of the user-defined
function create() that must end with a semicolon; create() takes
an integer as parameter, performs some predefined operations, and
returns nothing*/
void insert(int nm);
/*this is the prototype (or declaration) of the user-defined
function insert() that must end with a semicolon; insert() takes
an integer as parameter, performs some predefined operations, and
returns nothing*/
void display(int a);
/*this is the prototype (or declaration) of the user-defined
function display() that must end with a semicolon; display() takes
an integer as parameter, performs some predefined operations, and
returns nothing*/
int main(){
/*all C program must have a main() function with return type void
or int; here there is no parameter of the main() function and it
returns an integer; opening curly brace specifies start of the
main() function and no statement before that curly brace is executed
by the compiler*/
int num1, num2, num3;
/*three integer type variabls are declared; required memory
spaces are allocated for each of the variables*/
stnode = NULL;
/*NULL value is assigned to the starting node stnode*/
printf("Input the number of nodes: ");
/*printf() function displays the text in the quotations as it
is on the screen*/
scanf("%d", &num1);
/*scanf() function reads an integer from input terminal and
stores the value in the memory spaces allocated for the num1*/
create(num1);
ProgReference.com
332 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 333
/*two struct node type pointers are declared; prev and newn are
the addresses of two struct node type variables each has two
members- item to store an integer and next to store address of
another struct node type variable*/
stnode = (struct node *)malloc(sizeof(struct node));
/*sizeof() function computes the size of struct node type data,
needed to store an integer and address of another node; required
memory spaces are dynamically allocated by malloc(); address
of the memory space is assigned to struct node type pointer
variable stnode*/
if (stnode == NULL)
/*if memory cannot be assigned successfully malloc() returns
a NULL to stnode; if the condition of if is true following
statement is executed*/
printf("Memory cannot be allocated.");
/*printf() function displays the text in the quotations as
it is on the screen*/
else{
/*if the above condition of if is false, following statements,
enclosed in the curly braces, are executed*/
printf("\nInput data for node #1: ");
/*printf() function displays the text in the double
quotations as it is on the screen except for a newline
replaces \n*/
scanf("%d", &num4);
/*scanf() function reads an integer from input terminal and
stores the value in the memory spaces allocated for the num4*/
stnode->item = num4;
/*value of num4 is assigned to the member item of the first
node stnode of the linked list*/
stnode->next = NULL;
/*next pointer of the first node is set to NULL; there is
no more node after that in the linked list*/
prev = stnode;
/*struct node type pointer prev refers to the first node of
the linked list stnode*/
for (i=2; i<=n; i++){
/*this for loop creates other nodes of the linked list
other than the first node; here i=2 is initialization, i<=n
is condition and i++ is increment; initialization is done
once at the beginning of the loop; then the condition is
checked, if it is true statements in the body, enclosed by
curly braces, are executed and value of i is incremented by
1 before the condition is re-checked; these steps continue
until the condition becomes false in which case the program
control flow exits the loop*/
ProgReference.com
334 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 335
ProgReference.com
336 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 337
ProgReference.com
338 ◾ Learn Programming with C
PROBLEM-07
Write a program to display the truth table of three input EX-OR gate.
Step-1: Start
Step-2: Defne struct exor with members a, b, c, and res
Step-3: Initialize i←0
ProgReference.com
Structure and Union ◾ 339
Step-4: If i<8
4.1: c[i]←i%2
4.2: b[i]←(i/2)%2
4.3: a[i]←(i/2)/2
4.4: res[i]←a[i] b[i] c[i]
4.5: i←i+1
4.6: Go to Step-5
Step-5: Initialize j←0
Step-6: If j<8
6.1: Display values of a[j], b[j], c[j], res[j]
6.2: j←j+1
6.3: Go to Step-6
Step-7: Stop
ProgReference.com
340 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 341
ProgReference.com
342 ◾ Learn Programming with C
PROBLEM-08
Write a program that uses functions to perform the following operations:
ProgReference.com
Structure and Union ◾ 343
Step-1: Start
Step-2: Defne struct complex with members real and imag
Step-3: op1←read() [call function read()]
Step-4: op2←read() [call function read()]
Step-5: Read value of ch
ProgReference.com
344 ◾ Learn Programming with C
Step-6: If ch=‘+’
6.1: op3←add(op1, op2) [call function add()]
6.2: Call function write(op3)
6.3: Go to Step-10
Step-7: If ch=‘*’
7.1: op3←mul(op1, op2) [call function mul()]
7.2: Call function write(op3)
7.3: Go to Step-10
Step-8: Display ‘wrong choice’
Step-9: Stop
Step-1: If num1.imag>0
ProgReference.com
Structure and Union ◾ 345
ProgReference.com
346 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 347
ProgReference.com
348 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 349
ProgReference.com
350 ◾ Learn Programming with C
printf(" * ");
/*printf() function displays the text inside the double
quotations as it is on the screen*/
write(op2);
/*user-defined function write() is called with op2 passed
to the function as real parameter; program control flow
shifts to the definition of function write()*/
printf(" = ");
/*printf() function displays the text inside the double
quotations as it is on the screen*/
write(op3);
/*user-defined function write() is called with op3 passed
to the function as real parameter; program control flow
shifts to the definition of function write()*/
printf("\n");
/*this printf() function displays a newline on the
screen*/
break;
/*this break statement causes the program control flow
exits the switch..case without executing any of the
following statements inside the switch..case*/
default:
/*if ch equals neither '+' nor '*', then any of the above
cases does not match and statement under this default is
executed*/
printf("Entered wrong choice, quitting . . . ");
/*printf() function displays text inside the double
quotations as it is on the screen; as default is
the last level to be executed, after this statement,
program control flow immediately exits the switch..
case*/
}
/*this closing curly brace specifies the end of switch..
case*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
struct complex read(){
/*definition of read() function starts here with function header
and body; function header is same as function prototype without
semicolon; body of the function is enclosed in curly braces*/
struct complex num;
ProgReference.com
Structure and Union ◾ 351
ProgReference.com
352 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 353
PROBLEM-09
Te marks distribution for attendance of the Department of EEE, Dhaka University, is
given below:
Attendance Marks Attendance Marks
90% and above 5.0 70% to <75% 3.0
80% to <90% 4.5 65% to <70% 2.5
70% to <80% 4.0 60% to <65% 2.0
60% to <70% 3.5 Less than 60% 0.0
ProgReference.com
354 ◾ Learn Programming with C
Tere were 30 classes of EEE-1102 in the current session. Calculate the obtained atten-
dance marks of the following n students:
Class Roll No. of Classes Class Roll No. of Classes
101 27 106 28
102 15 107 12
103 21 108 27
104 19 109 9
105 12 110 28
Flowchart of the Solution:
Figure 5.3 shows the fowcharts followed to solve this problem.
ProgReference.com
Flowchart followed to solve the problem.
FIGURE 5.3
Structure and Union ◾ 355
Step-1: Start
Step-2: Defne struct atten with members roll, classno, classper and mark
Step-3: Read values of numstd and classtot
Step-4: Initialize i←0
Step-5: If i<numstd
5.1: Read values of stud[i].roll and stud[i].classno
5.2: stud[i].classper←(stud[i].classno)/classtot)×100
5.3: If stud[i].classper>=90.0
5.3.1: stud[i].mark←5.0
5.3.2: Go to Step-6.11
5.4: If stud[i].classper>=85.0
5.4.1: stud[i].mark←4.5
5.4.2: Go to Step-6.11
5.5: If stud[i].classper>=80.0
5.5.1: stud[i].mark←4.0
5.5.2: Go to Step-6.11
5.6: If stud[i].classper>=75.0
5.6.1: stud[i].mark←3.5
5.6.2: Go to Step-6.11
5.7: If stud[i].classper>=70.0
5.7.1: stud[i].mark←3.0
5.7.2: Go to Step-6.11
5.8: If stud[i].classper>=65.0
5.8.1: stud[i].mark←2.5
5.8.2: Go to Step-6.11
5.9: If stud[i].classper>=60.0
5.9.1: stud[i].mark←2.0
5.9.2: Go to Step-6.11
ProgReference.com
356 ◾ Learn Programming with C
5.10: stud[i].mark←0.0
5.11: i←i+1
5.12: Go to Step-5
Step-6: Display values of classes and classtot
Step-7: Initialize i←0
Step-8: If i<numstd
8.1: Display values of stud[i].roll, stud[i].classno, stud[i].classper, and stud[i].mark
8.2: i←i+1
8.3: Go to Step-8
Step-9: Stop
ProgReference.com
Structure and Union ◾ 357
ProgReference.com
358 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 359
scanf("%d", &stud[i].roll);
/*function scanf() reads an integer from input terminal and
stores it in the member roll of struct atten type array
element stud[]; in each iteration roll number of individual
student is read*/
printf("Enter number of classes attended: ");
/*output function printf() displays the text in the
quotations as it is on the screen*/
scanf("%d", &stud[i].classno);
/*function scanf() reads an integer from input terminal
and stores it in the member classno of struct atten type
array element stud[]; in each iteration number of classes
attended for individual student is read*/
stud[i].classper=((stud[i].classno)/((float) classtot))*100;
/*this arithmetic operation calculates percentage of classes
attended by a student in each iteration; here classtot is
converted to float so that the division operation gives
decimal result rather than integer*/
if (stud[i].classper>=90.0)
/*if the condition is true, means class percentage of a
particular student is greater than or equal to 90, following
statement is executed*/
stud[i].mark=5.0;
/*if class percentage of a student is greater than or
equal to 90 then his mark is 5.0*/
else if (stud[i].classper>=85.0)
/*if the condition is true, means class percentage of a
particular student is between 85 and 90, following statement
is executed*/
stud[i].mark=4.5;
/*value 4.5 is assigned to member mark of a particular
student*/
else if (stud[i].classper>=80.0)
/*if the condition is true, means class percentage of a
particular student is between 80 and 85, following statement
is executed*/
stud[i].mark=4.0;
/*value 4.0 is assigned to member mark of a particular
student*/
else if (stud[i].classper>=75.0)
/*if the condition is true, means class percentage of a
particular student is between 75 and 80, following statement
is executed*/
stud[i].mark=3.5;
/*value 3.5 is assigned to member mark of a particular
student*/
ProgReference.com
360 ◾ Learn Programming with C
else if (stud[i].classper>=70.0)
/*if the condition is true, means class percentage of a
particular student is between 70 and 75, following statement
is executed*/
stud[i].mark=3.0;
/*value 3.0 is assigned to member mark of a particular
student*/
else if (stud[i].classper>=65.0)
/*if the condition is true, means class percentage of a
particular student is between 65 and 70, following statement
is executed*/
stud[i].mark=2.5;
/*value 2.5 is assigned to member mark of a particular
student*/
else if (stud[i].classper>=60.0)
/*if the condition is true, means class percentage of a
particular student is between 60 and 65, following statement
is executed*/
stud[i].mark=2.0;
/*value 2.0 is assigned to member mark of a particular
student*/
else
/*if all the above condition is false, means class percentage
of a particular student is less than 60, following statement
executed*/
stud[i].mark=0.0;
/*value 0.0 is assigned to member mark of a particular
student*/
}
/*this closing curly brace specifies the end of 'for' loop*/
printf("\nTotal number of classes: %d\n", classtot);
/*output function printf() displays the text in the quotations
as it is on the screen except for the value of classtot replaces
the format specifier %d and a newline replaces \n*/
printf("Roll No. \tAttended Class \tPercentage \tObtained”
" Marks\n");
/*output function printf() displays the text in the quotations
as it is on the screen except for a newline replaces \n and a
tab replaces \t*/
printf("-------------------------------------------------\n");
/*output function printf() displays the text in the quotations
as it is on the screen except for a newline replaces \n*/
for (i=0; i<numstd; i++)
/*here i=0 is initialization, i<numstd is condition and i++ is
increment; initialization is done once at the beginning of the
ProgReference.com
Structure and Union ◾ 361
PROBLEM-10
Answer scripts of final examination of the Department of EEE, Dhaka University,
have been examined by two examiners independently. The obtained final marks of
any course will be average of the two marks. But, if their marks for any particular
script differ by 20% or more, then the script is evaluated by another independent
third examiner. And the obtained final marks of that course will be average of the
two marks of the examiners whose marks are closer. Write a program to read the
following data and determine:
Roll No. 1st Examiner 2nd Examiner Roll No. 1st Examiner 2nd Examiner
1001 65 58 1004 68 48
1002 55 54 1005 50 52
1003 40 30 1006 15 32
ProgReference.com
362 ◾ Learn Programming with C
ProgReference.com
Flowcharts followed to solve the problem.
FIGURE 5.4
Structure and Union ◾ 363
Step-1: Start
Step-2: Defne struct marks with members roll, marks1, marks2, marks3, third and
marksfnal
Step-3: Initialize ind←0
Step-4: Read values of numstd and markstot
Step-5: Initialize i←0
Step-6: If i<numstd
ProgReference.com
364 ◾ Learn Programming with C
11.1.5.2: Go to Step-11.2
11.1.6: min←minfn(dif12, dif23, dif31)
11.1.6.1: If min=dif12
11.1.6.1.1: stud[i].marksfnal←(stud[i].marks1+ stud[i].
marks2)/2
11.1.6.1.1: Go to Step-11.2
11.1.6.2: If min=dif23
11.1.6.2.1: stud[i].marksfnal←(stud[i].marks2+ stud[i].
marks3)/2
11.1.6.2.2: Go to Step-11.2
11.1.6.3: stud[i].marksfnal←(stud[i].marks3+ stud[i].marks1)/2
11.2: i←i+1
11.3: Go to Step-11
Step-12: Initialize i←0
Step-13: If i<numstd
13.1: If stud[i].third=1
13.1.1: Display values of stud[i].roll, stud[i].marks1, stud[i].marks2, stud[i].
marks3, and stud[i].marksfnal
13.1.2: Go to Step-14.3
13.2: Display values of stud[i].roll, stud[i].marks1, stud[i].marks2, and stud[i].
marksfnal
13.3: i←i+1
13.4: Go to Step-13
Step-14: Stop
ProgReference.com
Structure and Union ◾ 367
ProgReference.com
368 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 369
ProgReference.com
370 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 371
ProgReference.com
372 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 373
ProgReference.com
374 ◾ Learn Programming with C
stud[i].marksfinal=stud[i].marks3;
/*this statement sets the marksfinal to 3rd
examination marks of that student*/
else{
/*if condition of above 'if' is false, means 3drd
examination marks is not in the middle of 1st and
2nd examination marks, following statements inside
the curly braces are executed*/
min=minfn(diff12, diff23, diff31);
/*minfn() is called with real parameters diff12,
diff23 and diff31, program control flow shifts
to the function definition; function minfn()
does some defined operations and returns an
integer that is assigned to min*/
if (min==diff12)
/*if this condition is true, means 1st and
2nd examination marks are closest, following
statement is executed*/
stud[i].marksfinal=ceil((stud[i].marks1+
(float) stud[i].marks2)/2);
/*final marks of a particular student is
calculated as average of the marks- marks1
and marks2; ceil() function computes nearest
integer greater than its parameter*/
else if (min==diff23)
/*if condition of above 'if' (min==diff12) is false but
this condition is true, means 2nd and 3rd examination
marks are closest, following statement is executed*/
stud[i].marksfinal=ceil((stud[i].marks2+
(float) stud[i].marks3)/2);
/*final marks of a particular student is
calculated as average of the marks- marks2
and marks3; ceil() function computes nearest
integer greater than its parameter*/
else
/*if both conditions of 'if' (min==diff12) and
'else if' (min==diff23) are false, means 3rd
and 1st examination marks are closest, following
statement is executed*/
stud[i].marksfinal=ceil((stud[i].marks3+
(float) stud[i].marks1)/2);
/*final marks of a particular student is
calculated as average of the marks- marks3
and marks1; ceil() function computes nearest
integer greater than its parameter*/
}
ProgReference.com
Structure and Union ◾ 375
ProgReference.com
376 ◾ Learn Programming with C
PROBLEM-11
Te annual examination results of n students are tabulated as follows:
Roll No. EEE-1101 EEE-1102 EEE-1103
101 69 56 89
102 80 65 91
103 45 36 68
ProgReference.com
378 ◾ Learn Programming with C
Step-1: Start
Step-2: Defne struct subject with members mark, point, and letter
Step-3: Defne struct exam with members roll, sub[100], total, gpa, and pos
Step-4: Read values of numstd and numsub
Step-5: Initialize i←0
Step-6: If i<numstd
6.1: Read value of stud[i].roll
6.2: Initialize stud[i].total←0, totgrd←0 and j←0
6.3: If j<numsub
6.3.1: Read value of stud[i].sub[j].mark
6.3.2: If stud[i].sub[j].mark>=90
6.3.2.1: stud[i].sub[j].point←4.00
6.3.2.2: stud[i].sub[j].letter←“A+”
6.3.2.3: Go to Step-6.3.9
6.3.3: If stud[i].sub[j].mark>=80
6.3.3.1: stud[i].sub[j].point←3.50
6.3.3.2: stud[i].sub[j].letter←“A”
6.3.3.3: Go to Step-6.3.9
6.3.4: If stud[i].sub[j].mark>=70
6.3.4.1: stud[i].sub[j].point←3.00
6.3.4.2: stud[i].sub[j].letter←“B”
6.3.4.3: Go to Step-6.3.9
6.3.5: If stud[i].sub[j].mark>=60
7.4.5.1: stud[i].sub[j].point←2.50
7.4.5.2: stud[i].sub[j].letter←“C”
7.4.5.3: Go to Step-6.3.9
6.3.6: If stud[i].sub[j].mark>=50
ProgReference.com
380 ◾ Learn Programming with C
6.3.6.1: stud[i].sub[j].point←2.00
6.3.6.2: stud[i].sub[j].letter←“D”
6.3.6.3: Go to Step-6.3.9
6.3.7: stud[i].sub[j].point←0.00
6.3.8: stud[i].sub[j].letter←“F”
6.3.9: stud[i].total← stud[i].total+stud[i].sub[j].mark
6.3.10: totgrd←totgrd+stud[i].sub[j].point
6.3.11: j←j+1
6.3.12: Go to Step-6.3
6.4: stud[i].gpa←totgrd/numsub
6.5: i←i+1
6.6: Go to Step-6
Step-7: Initialize i←1
Step-8: If i<=numstd−1
8.1: Initialize j←1
8.2: If j<=numstd−i
8.2.1: If stud[j−1].gpa<stud[j].gpa
8.2.1.1: temp←stud[j−1]
8.2.1.2: stud[j−1]←stud[j]
8.2.1.3: stud[j]←temp
8.2.1.4: Go to Step-8.2.3
8.2.2: If stud[j−1].gpa=stud[j].gpa
8.2.2.1: If stud[j−1].total<stud[j].total
8.2.2.1.1: temp←stud[j−1]
8.2.2.1.2: stud[j−1]←stud[j]
8.2.2.1.3: stud[j]←temp
8.2.3: j←j+1
8.2.4: Go to Step-8.2
8.3: i←i+1
ProgReference.com
Structure and Union ◾ 381
8.4: Go to Step-8
Step-9: Initialize i←0
Step-10: If i<numstd
10.1: stud[i].pos←i+1
10.2: i←i+1
10.3: Go to Step-10
Step-11: Initialize i←0
Step-12: If i<numstd
12.1: Display value of stud[i].roll
12.2: Initialize j←0
12.3: If j<numsub
12.3.1: Display values of stud[i].sub[j].letter, stud[i].sub[j].point, stud[i].gpa
and stud[i].pos
12.3.2: j←j+1
12.3.3: Go to Step-12.3
12.4: i←i+1
12.5: Go to Step-12
Step-13: Initialize i←1
Step-14: If i<=numstd−1
14.1: Initialize j←1
14.2: If j<=numstd−i
14.2.1: If stud[j−1].roll>stud[j].roll
14.2.1.1: temp←stud[j−1]
14.2.1.2: stud[j−1]←stud[j]
14.2.1.3: stud[j]←temp
14.2.2: j←j+1
14.2.3: Go to Step-14.2
14.3: i←i+1
14.4: Go to Step-14
ProgReference.com
382 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 383
ProgReference.com
384 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 385
ProgReference.com
386 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 387
ProgReference.com
388 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 389
stud[i].sub[j].point=3.50;
/*point is a member of struct subject type array
sub[] which in turn is a member of struct exam type
array stud[]; point is accessed using double dot
(.) operators and assigned a value 3.50*/
stud[i].sub[j].letter="A";
/*character type pointer letter is a member of
struct subject type array sub[] which in turn is
a member of struct exam type array stud[], hence
variable point is accessed using double dot (.)
operators and assigned a string A*/
}
/*this closing curly brace specifies end of else if
(stud[i].sub[j].mark>=80)*/
else if (stud[i].sub[j].mark>=70){
/*if the condition is true, means marks of a particular
subject of a particular student is between 70 and 80,
then following two statements are executed*/
stud[i].sub[j].point=3.00;
/*point is a member of struct subject type array
sub[] which in turn is a member of struct exam type
array stud[]; point is accessed using double dot
(.) operators and assigned a value 3.00*/
stud[i].sub[j].letter="B";
/*character type pointer letter is a member of
struct subject type array sub[] which in turn is
a member of struct exam type array stud[], hence
variable point is accessed using double dot (.)
operators and assigned a string B*/
}
/*this closing curly brace specifies end of else if
(stud[i].sub[j].mark>=70)*/
else if (stud[i].sub[j].mark>=60){
/*if the condition is true, means marks of a particular
subject of a particular student is between 60 and 70,
then following two statements are executed*/
stud[i].sub[j].point=2.50;
/*point is a member of struct subject type array
sub[] which in turn is a member of struct exam type
array stud[]; point is accessed using double dot
(.) operators and assigned a value 2.50*/
stud[i].sub[j].letter="C";
/*character type pointer letter is a member of
struct subject type array sub[] which in turn is
a member of struct exam type array stud[], hence
ProgReference.com
390 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 391
ProgReference.com
392 ◾ Learn Programming with C
stud[j−1]=stud[j];
/*array element stud[j] is stored in array element
stud[j−1]*/
stud[j]=temp;
/*value of temp is stored in array element stud[j],
that is stud[j−1] now becomes stud[j]*/
}
/*this closing curly brace specifies the end of 'if'*/
else if (stud[j−1].gpa==stud[j].gpa)
/*if above 'if' condition is false then this 'else
if' condition is checked; if this condition is true,
means gpa of two contiguous students are equal then
following 'if' condition is executed to sort students
according to their obtained total marks in ascending
order*/
if (stud[j−1].total<stud[j].total){
/*if this condition is true then following
statements, enclosed in the curly braces, are
executed; here total of two contiguous students
are compared, if the larger total stays above the
smaller one then they are swapped*/
temp=stud[j−1];
/*array element stud[j−1] is stored in
variable temp*/
stud[j−1]=stud[j];
/*array element stud[j] is stored in array
element stud[j−1]*/
stud[j]=temp;
/*value of temp is stored as array element
stud[j], that is stud[j−1] now becomes
stud[j]*/
}
/*this closing curly brace specifies the end of
'if' with condition*/
for (i=0; i<numstd; i++)
/*this for loop is used to set position of individual student
according to sorted gpa; here i=0 is initialization, i<numstd
is condition and i++ is increment; initialization is done once
at the beginning of the loop; then the condition is checked, if
it is true statement in the body is executed and the value of i
is incremented by 1 before the condition is re-checked; these
steps continue until the condition becomes false in which case
the program flow exits the loop*/
stud[i].pos=i+1;
/*member pos of struct exam type array stud[] is set to i+1;
at 1st iteration position of 1st student is set to stud[0].
ProgReference.com
Structure and Union ◾ 393
ProgReference.com
394 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 395
ProgReference.com
396 ◾ Learn Programming with C
PROBLEM-12
Write a program to create a linear linked list interactively and delete a specifed node
from the list. Te program will display all the items before and afer deletion.
ProgReference.com
Structure and Union ◾ 397
ProgReference.com
398 ◾ Learn Programming with C
Step-1: Start
Step-2: Defne struct list node with members num and next
Step-3: Call function create(head)
Step-4: Call function print(head)
Step-5: If head->num≠−99
5.1: head←delet(head) [call function delet()]
5.2: Call function print(head)
Step-6: Display enter
Step-7: Stop
ProgReference.com
Structure and Union ◾ 399
Step-1: If pt->num=−99
1.1: Display ‘empty list’
1.2: Go to Step-4
Step-2: If pt->next=0
2.1: Display value of pt->num
2.2: Go to Step-4
Step-3: Display value of pt->num
Step-4: Return.
Step-1: If pt->next=0
1.1: If pt->num≠key
1.1.1: Go to Step-3.1
Step-2: If pt->next->num=key
2.1: Return value of pt
Step-3: If pt->next->next=0
3.1: Return 0
Step-4: Call function fnd(pt->next, key)
ProgReference.com
400 ◾ Learn Programming with C
2.5: Go to Step-9
Step-3: ptr←fnd(pt, key) [call function fnd()]
Step-4: If ptr=0
4.1: Display ‘key not found’
4.1: Go to Step-9
Step-5: If ptr->next->next=0
5.1: free(ptr->next)
5.2: ptr->next←0
5.3: Go to Step-9
Step-6: temp←ptr->next->next
Step-7: free(ptr->next)
Step-8: ptr->next→temp
Step-9: Return value of pt
ProgReference.com
Structure and Union ◾ 401
ProgReference.com
402 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 403
ProgReference.com
404 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 405
print(head);
/*user-defined function print() is called with real
parameter head that refers to the first node of the linked
list; program control flow shifts to the definition of the
function*/
}
/*this closing curly brace specifies the end of 'if'*/
printf("\n");
/*this printf() displays a newline on the screen*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
void create(node *pt){
/*definition of create() function starts here with function header
and body; function header is same as function prototype without
semicolon; body of the function is enclosed in curly braces; real
argument that is passed during the function call replaces virtual
parameter pt*/
int key;
/*an integer type variable key is declared; required memory
space is allocated for the variable; this variable is local
to the function create() and is not visible outside that
function*/
static int count=0;
/*an integer type variable count is declared and initialized to
0; the variable is declared as static, means the value of count
is preserved between the function calls and until the end of
the program execution*/
static node *head1;
/*a node type pointer head1 is declared; the pointer is declared
as static, means this pointer is alive until the end of the
program execution; this is done so that address of a created
node is preserved between function calls*/
printf("Input a number (−99 to end): ");
/*printf() function displays the text in the double quotations
as it is on the screen*/
scanf("%d", &key);
/*scanf() function reads an integer from input terminal and
stores the value in the memory spaces allocated for the key*/
if (key==−99){
/*if key is −99, we do not want to add anymore node in the
linked list, and the statements in the body of 'if', enclosed
by curly braces, are executed*/
ProgReference.com
406 ◾ Learn Programming with C
if (count==0){
/*if count equals 0, the linked list is empty, and
following statements, enclosed in the curly braces, are
executed*/
pt->num=−99;
/*value of the member num of first node of the linked
list is set to −99*/
pt->next=0;
/*next pointer of the first node is set to 0; there is
no more node after that in the linked list*/
}
/*this is the end of 'if' with condition (count==0)*/
else{
/*if key=−99 but count≠0, the linked list is not empty and
we do not want to add anymore node to the linked list, and
following statements, enclosed in the curly braces, are
executed*/
head1->next=0;
/*next pointer of the last node is set to 0, here is no
more node after that in the linked list*/
free(pt);
/*memory space allocated for node pt is freed*/
}
/*this is the end of above 'else' with condition (count==0)*/
}
/*this is the end of 'if' with condition (key==−99)*/
else{
/*if key≠−99, we want to add more node in the linked list
and following statements, enclosed by curly braces, are
executed*/
count++;
/*value of 'count' is incremented by 1 to count the number
of node added in the linked list*/
head1=pt;
/*node pointer pt, passed as argument in the function call,
is assigned to head1; that is, head1 always refer to the
last node of the linked list*/
pt->num=key;
/*value of key, entered by user, is assigned to member num
of the last node pt*/
pt->next=(node *)malloc(sizeof(node));
/*a new node is created whose address is assigned to the
member next of last node pt of the linked list, hence next
of pt points to another node; sizeof() function calculates
the size of node type data, needed to store an integer
and address of another node; required memory spaces are
dynamically allocated by malloc()*/
ProgReference.com
Structure and Union ◾ 407
create(pt->next);
/*user-defined function create() is called again to define
the newly created node; program control flow shifts to
definition of the function create()*/
}
/*this is the end of else with condition (key==−99)*/
}
/*this closing curly brace specifies the end of definition of
create() function; program control flow returns to the point where
the function was called*/
void print(node *pt){
/*definition of print() function starts here with function header
and body; function header is same as function prototype without
semicolon; body of the function is enclosed in curly braces; real
argument that is passed during the function call replaces virtual
parameter pt*/
if (pt->num==−99)
/*if value of the member num of first node pt is −99, the linked
list is empty, and following statement is executed*/
printf("The list is empty.");
/*printf() function displays the text in the quotations as
it is on the screen*/
else if (pt->next==0)
/*if pt->num≠−99, linked list is not empty, and we check if pt
is the last node; if pt is the last node of the linked list
then condition of 'else if' is true and following statement is
executed*/
printf("%d, ", pt->num);
/*printf() function displays the value of num of last node
pt on the screen in place of format specifier %d*/
else{
/*if pt->num≠−99, linked list is not empty, and pt->next≠0, pt is
not the last node, in that case, following statements are executed*/
printf("%d, ", pt->num);
/*printf() function displays the value of num of current
node pt on the screen in place of format specifier %d*/
print(pt->next);
/*user-defined function print() is called with real
parameter pt->next that refers to the next node of the
linked list; program control flow shifts to the definition
of the function*/
}
/*this closing curly brace specifies the end of else*/
}
/*this closing curly brace specifies the end of the definition of
print() function; program control flow returns to the point where
the function was called*/
ProgReference.com
408 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 409
ProgReference.com
410 ◾ Learn Programming with C
else{
/*if key is not found in the first node then following
statements in the body of 'else', enclosed in curly braces, are
executed*/
ptr=find(pt, key);
/*user-defined function find() is called with argument pt
and key; program control flow shifts to the definition of
the function; find() searches the linked list for key, if
key is not found it returns 0 that is assigned to ptr; if
key is found in the next node of pt then pointer pt is
returned that is assigned to ptr*/
if (ptr==0)
/*if key is not found in the linked list then above condition
is true and following statement is executed*/
printf("Key not found.\n");
/*printf() function displays the text in the quotations
as it is on the screen except for a newline replaces
\n*/
else if (ptr->next->next==0){
/*if key is found in the last node then above condition of
'else if' is true and following statements, enclosed in the
curly braces, are executed to delete the last node*/
free(ptr->next);
/*library function free() is called to free next node
of ptr, which is the last node of the linked list where
the key was found*/
ptr->next=0;
/*make the current node ptr as the last node by setting
its 'next' value to 0*/
}
/*this is the end of 'else if' with condition (ptr->next-
>next==0)*/
else{
/*if key is found in the next node of ptr, but the node is not
the last one of the linked list then following statements,
enclosed in curly braces, are executed to delete the next
node of ptr; this operation is more understandable if we
consider ptr as the 3rd node, ptr->next refers to 4th node
and ptr->next->next refers to 5th node; here we need to
delete the 4th node*/
temp=ptr->next->next;
/*next node of the node ptr->next (5th node) is saved
to node type pointer temp; temp now refers to the 5th
node of the linked list*/
free(ptr->next);
/*library function free() is called to free next node
of ptr, which is the 4th node of the linked list where
the key was found*/
ProgReference.com
Structure and Union ◾ 411
ptr->next=temp;
/*5th node is linked with the 3rd node; previously next
of the 3rd node (ptr->next) holds the address of the
4th node and now ptr->next holds the address of the 5th
node*/
}
/*this is the end of 'else' with condition (ptr==0)*/
}
/*this is the end of 'else' with condition (pt->num==key)*/
return pt;
/*pointer of the first node pt of the linked list is returned
to the point where the function was called*/
}
/*this closing curly brace specifies the end of the definition of
delet() function*/
PROBLEM-13
Write a program to create a linear linked list interactively and insert a given item before
and afer a specifed node of the list. Te program will display all the items before and
afer insertion.
ProgReference.com
412 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 413
Step-1: Start
Step-2: Defne struct list node with members num and next
Step-3: Call function create(head)
Step-4: Call function print(head)
Step-5: If head->num≠−99
5.1: head←insert(head) [call function insert()]
5.2: Call function print(head)
Step-6: Display enter
Step-7: Stop
ProgReference.com
414 ◾ Learn Programming with C
3.1: If count=0
3.1.1: pt->num←−99
3.1.2: pt->next←0
3.1.3: Go to Step-8
3.2: head1->next←0
3.3: free(pt)
3.4: Go to Step-8
Step-4: count←count+1
Step-5: head1←pt
Step-6: pt->num←key
Step-7: Call function create(pt->next)
Step-8: Return.
Step-1: If pt->num=−99
1.1: Display ‘empty list’
1.2: Go to Step-4
Step-2: If pt->next=0
2.1: Display value of pt->num
2.2: Go to Step-4
Step-3: Display value of pt->num
Step-4: Return.
Step-1: If pt->next=0
1.1: If pt->num≠key
1.1.1: Go to Step-3.1
Step-2: If pt->next->num=key
2.1: Return value of pt
ProgReference.com
Structure and Union ◾ 415
Step-3: If pt->next->next=0
3.1: Return 0
Step-4: Call function fnd(pt->next, key)
ProgReference.com
416 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 417
ProgReference.com
418 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 419
ProgReference.com
420 ◾ Learn Programming with C
if (head->num!=−99){
/*member of structured data type variable is accessed using
pointer operator; pointer head refers to the first node of
the linked list; if value of member num of first node head is
any integer other than −99, then the linked list is not empty,
and following statements, enclosed in the curly braces, are
executed*/
head=insert(head);
/*user-defined function insert() is called with real
parameter head that refers to the first node of the linked
list; program control flow shifts to the definition of the
function that does some pre-defined operation and returns a
node type pointer that is assigned to head*/
printf("List of items after deletion:\n");
/*printf() function displays the text in the double
quotations as it is on the screen except for a newline
replaces \n*/
print(head);
/*user-defined function print() is called with real
parameter head that refers to the first node of the linked
list; program control flow shifts to the definition of the
function*/
}
/*this closing curly brace specifies the end of 'if'*/
printf("\n");
/*this printf() displays a newline on the screen*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
void create(node *pt){
/*definition of create() function starts here with function header
and body; function header is same as function prototype without
semicolon; body of the function is enclosed in curly braces; real
argument that is passed during the function call replaces virtual
parameter pt*/
int key;
/*an integer type variable key is declared; required memory
space is allocated for the variable; this variable is local
to the function create() and is not visible outside that
function*/
static int count=0;
/*an integer type variable count is declared and initialized
to 0; the variable is declared as static, means the value of
ProgReference.com
Structure and Union ◾ 421
count is preserved between the function calls and until the end
of the program execution*/
static node *head1;
/*a node type pointer head1 is declared; the pointer is declared
as static, means this pointer is alive until the end of the
program execution; this is done so that address of a created
node is preserved between function calls*/
printf("Input a number (−99 to end): ");
/*printf() function displays the text in the double quotations
as it is on the screen*/
scanf("%d", &key);
/*scanf() function reads an integer from input terminal and
stores the value in the memory spaces allocated for the
key*/
if (key==−99){
/*if key is −99, we do not want to add anymore node in the
linked list, and the statements in the body of 'if', enclosed
by curly braces, are executed*/
if (count==0){
/*if count equals 0, the linked list is empty, and
following statements, enclosed in the curly braces, are
executed*/
pt->num=−99;
/*value of the member num of first node of the linked
list is set to −99*/
pt->next=0;
/*next pointer of the first node is set to 0; there is
no more node after that in the linked list*/
}
/*this is the end of 'if' with condition (count==0)*/
else{
/*if key=−99 but count≠0, the linked list is not empty and
we do not want to add anymore node to the linked list, and
following statements, enclosed in the curly braces, are
executed*/
head1->next=0;
/*next pointer of the last node is set to 0, here is no
more node after that in the linked list*/
free(pt);
/*memory space allocated for node pt is freed*/
}
/*this is the end of above 'else' with condition (count==0)*/
}
/*this is the end of 'if' with condition (key==−99)*/
else{
/*if key≠−99, we want to add more node in the linked list and
following statements, enclosed by curly braces, are executed*/
ProgReference.com
422 ◾ Learn Programming with C
count++;
/*value of 'count' is incremented by 1 to count the number
of node added in the linked list*/
head1=pt;
/*node pointer pt, passed as argument in the function call,
is assigned to head1; that is, head1 always refer to the
last node of the linked list*/
pt->num=key;
/*value of key, entered by user, is assigned to member num
of the last node pt*/
pt->next=(node *)malloc(sizeof(node));
/*a new node is created whose address is assigned to the
member next of last node pt of the linked list, hence next
of pt points to another node; sizeof() function calculates
the size of node type data, needed to store an integer
and address of another node; required memory spaces are
dynamically allocated by malloc()*/
create(pt->next);
/*user-defined function create() is called again to define
the newly created node; program control flow shifts to
definition of the function create()*/
}
/*this is the end of else with condition (key==−99)*/
}
/*this closing curly brace specifies the end of definition of
create() function; program control flow returns to the point where
the function was called*/
void print(node *pt){
/*definition of print() function starts here with function header
and body; function header is same as function prototype without
semicolon; body of the function is enclosed in curly braces; real
argument that is passed during the function call replaces virtual
parameter pt*/
if (pt->num==−99)
/*if value of the member num of first node pt is −99, the linked
list is empty, and following statement is executed*/
printf("The list is empty.");
/*printf() function displays the text in the quotations as
it is on the screen*/
else if (pt->next==0)
/*if pt->num≠−99, linked list is not empty, and we check if pt
is the last node; if pt is the last node of the linked list
then condition of 'else if' is true and following statement is
executed*/
printf("%d, ", pt->num);
/*printf() function displays the value of num of last node
pt on the screen in place of format specifier %d*/
ProgReference.com
Structure and Union ◾ 423
else{
/*if pt->num≠−99, linked list is not empty, and pt->next≠0, pt
is not the last node, in that case, following statements are
executed*/
printf("%d, ", pt->num);
/*printf() function displays the value of num of current
node pt on the screen in place of format specifier %d*/
print(pt->next);
/*user-defined function print() is called with real
parameter pt->next that refers to the next node of the
linked list; program control flow shifts to the definition
of the function*/
}
/*this closing curly brace specifies the end of else*/
}
/*this closing curly brace specifies the end of the definition of
print() function; program control flow returns to the point where
the function was called*/
node *find(node *pt, int key){
/*definition of the user-defined function find() begins with the
function header and body of the function; function header is exactly
same as the function prototype except for no semicolon is used,
and body of the function is enclosed in curly braces; here pt and
key are the virtual parameters which are replaced by real arguments
passed during function call*/
if (pt->next==0 && pt->num!=key)
/*if pt is the last node and value of num is not the key,
the item is not found in the linked list, and the following
statement is executed*/
return 0;
/*this statement returns 0 to the point where the function
was called*/
else if (pt->next->num==key)
/*if pt is not the last node or key is not found in the current
node, then we check the value of num of the next node; if
the value of num of the next node of pt equals key following
statement is executed*/
return pt;
/*if the key is found in the next node of pt, then this
statement returns the pointer of node pt to the point where
the function was called*/
else if (pt->next->next==0)
/*if pt is not the last node or key is not found in the current
node or the next node, and next node is the last node following
statement is executed*/
return 0;
ProgReference.com
424 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 425
temp=(node *)malloc(sizeof(node));
/*a new node temp is created; sizeof() function calculates
the size of node type data, needed to store an integer and
address of another node, and required memory spaces are
dynamically allocated by malloc(); address of the memory
space is assigned to node type pointer temp*/
temp->num=nmb;
/*value of nmb is stored in num of the node temp*/
temp->next=pt;
/*newly created node temp is linked with the first node pt,
member next of node temp now refers to the first node pt of
the linked list*/
pt=temp;
/*newly created node temp is now assigned to pt that makes
pt the first node of the linked list*/
}
/*this is the end of 'if' with condition (pt->num==key)*/
else{
/*if key is not found in the first node, following statements
in the body of 'else', enclosed in the curly braces, are
executed*/
ptr=find(pt, key);
/*user-defined function find() is called with argument pt
and key; program control flow shifts to the definition of
the function; find() searches the linked list for key, if
key is not found it returns 0 which is assigned to ptr;
if key is found in the next node of pt then pointer pt is
returned which is assigned to ptr*/
if (ptr==0)
/*if key is not found in the linked list, above condition
is true and following statement is executed*/
printf("Key not found. Item cannot be inserted.\n");
/*printf() function displays the text in the quotations
as it is on the screen except for a newline replaces
\n*/
else{
/*if key is found in the next node of ptr, then following
statements are executed to insert the new node after ptr;
this operation is more understandable if we consider ptr as
the 3rd node and ptr->next refers to 4th node; here we need
to insert the new node before the 4th node*/
temp=(node *)malloc(sizeof(node));
/*a new node temp is created; sizeof() function computes
the size of node type data, needed to store an integer
and address of another node, and required memory spaces
are dynamically allocated by malloc(); address of the
memory space is assigned to node type pointer temp*/
ProgReference.com
426 ◾ Learn Programming with C
temp->num=nmb;
/*value of nmb is assigned to num of the node temp*/
temp->next=ptr->next;
/*newly created node temp is linked with the 4th node,
member next of node temp now refers to the 4th node
(next node of ptr)*/
ptr->next=temp;
/*newly created node temp is now assigned to member
next of ptr (next of 3rd node) that makes temp the 4th
node and old 4th node the 5th node of the linked list*/
}
/*this is the end of 'else' with condition (ptr==0)*/
}
/*this is the end of 'else' with condition (pt->num==key)*/
return pt;
/*pointer of the first node pt of the linked list is returned
to the point where the function was called*/
}
/*this closing curly brace specifies the end of the definition of
delet() function*/
EXERCISES
ProgReference.com
Structure and Union ◾ 427
ProgReference.com
428 ◾ Learn Programming with C
ProgReference.com
Structure and Union ◾ 429
C) Array
D) None of the above
15) Which of the following structure declaration will throw an error?
A) struct temp{}s;
B) struct temp{}; struct temp s;
C) struct temp s; struct temp{};
D) None of the above
16) Number of bytes in memory taken by the below structure is as follows:
struct test{int n; char c;};
A) Multiple of integer size
B) Integer size + character size
C) Depends on the platform
D) Multiple of word size
17) What is the similarity between a structure, union, and enumeration?
A) All of them let us defne new values
B) All of them let us defne new data types
C) All of them let us defne new pointers
D) All of them let us defne new structures
18) Size of a union is determined by the size of
A) First member in the union
B) Last member in the union
C) Biggest member in the union
D) Sum of the sizes of all members
19) Members of a union are accessed as
A) union-name.member
B) union-pointer->member
C) Both union-name.member & union-pointer->member
D) None of the above
ProgReference.com
430 ◾ Learn Programming with C
20) Which of the following user-defned data type shares its memory with each other?
A) structure
B) union
C) class
D) array
21) Which of the following share a similarity in syntax?
(1) union, (2) structure, (3) arrays, and (4) pointers
A) 3 and 4
B) 1 and 2
C) 1 and 3
D) 1, 3 and 4
[Ans. B, B, C, A, A, D, B, B, A, B, B, D, B, B, D, C, B, C, C, B, B]
1) Defne structure.
Ans. Te structure is a user-defned datatype in the C programming language that
combines diferent data types. Structure aids in the creation of a more meaningful
complex data type. It is comparable to an array; however, an array only retains the
same data type. Structure, on the other hand, may store diferent data types, making
it more practical.
2) Can the structure variable be initialized as soon as it is declared?
Ans. Structure variables can be initialized when they are declared. Tis procedure
is similar to that for initializing arrays. Te structure declaration is followed by an
equal sign and a list of initialization values with respect to the order of structure
elements only, separated by commas and enclosed in braces. For example, look at
the following statements for initializing the values of the members of the complex
structure variable.
struct num{
int real;
int imag;
} complex = {10, 15};
ProgReference.com
Structure and Union ◾ 431
struct num{
int real=10;
int imag=15;
};
Te reason for the error is simple; when a datatype is declared, no memory is allo-
cated for it. Memory is allocated only when variables are created.
4) Is there a way to compare two structure variables?
Ans. In c, it is not permitted to check or compare structure variables directly with
logical operators. We need to compare element by element of the structure variables.
5) What is a stack? What is the method to save data in a stack?
Ans. A stack is a linear data structure. Te First In Last Out (FILO) technique is
used to store data in the stack data structure type. At any given time, just the top of
the stack is accessible. A PUSH is a storage mechanism, whereas a POP is a retrieval
mechanism.
6) Describe dynamic data structure in C programming language?
Ans. Dynamic data structures are those that expand and contract as needed.
Dynamic data structures allocate memory blocks from the heap as required and use
pointers to connect those blocks into some data structure. When a data structure
no longer requires a memory block, it returns it to the heap for reuse. Tis recycling
makes very efcient use of memory.
7) What is a nested structure?
Ans. In C, a nested structure is a structure within a structure. As we defne structure
members inside a structure, one structure can be declared inside another structure.
For example, the college structure is declared inside the student structure in the fol-
lowing structure declarations:
struct college{
int colid;
char colname[50];
};
struct student{
int stid;
char stname[20];
float cgpa;
struct college;
} stdata;
ProgReference.com
432 ◾ Learn Programming with C
with one or more pointers. In dynamic data structures such as trees, linked lists,
and so on, the self-referential structure is widely used. A linked list of the same
struct type will be used to point to the next node of a node. In the example below,
the pointer next refers to a structure of type node. As a result, the structure node is
a self-referential structure with the referencing pointer next.
struct node{
int data;
struct node *next;
};
ProgReference.com
Structure and Union ◾ 433
Binary trees are an extension of the concept of linked lists. A binary tree is a nonlin-
ear data structure of the tree type with a maximum of two children for each parent.
Along with the data element, every node in a binary tree has a lef and right refer-
ence. Te root node is the node at the very top of a tree’s hierarchy. Te parent nodes
are the nodes that include additional subnodes. Te lef child and right child are the
two child nodes of a parent node.
13) What is a heap? What are the advantages and disadvantages of a heap?
Ans. A heap is a customized tree-based data structure that is essentially an almost
complete tree that satisfes the heap property: in a max-heap, the key of parent node
P is larger than or equal to the key of child node C for any given node C. Te key of
P in a min-heap is less than or equal to the key of C.
It takes longer to store data on the heap than it does on the stack. Te main beneft
of employing the heap, though, is its adaptability. Tis is because the memory in this
structure can be allocated and removed in any sequence. If an algorithm is well-
designed and implemented, it can compensate for the slowness in a heap.
Problems to Practice
ProgReference.com
434 ◾ Learn Programming with C
Tere were 30 classes of EEE-1102 in the current session. Calculate the obtained
attendance marks of the following n students:
Class Roll No. of Classes Class Roll No. of Classes
101 27 106 28
102 15 107 12
103 21 108 27
104 19 109 9
105 12 110 28
10) Answer scripts of fnal examination of the Department of EEE, Dhaka University,
have been examined by two examiners independently. Te obtained fnal marks of
any course will be average of the two marks. But, if their marks for any particular
script difer by 20% or more, then the script is evaluated by another independent
third examiner. And the obtained fnal marks of that course will be average of the
two marks of the examiners whose marks are closer. Write a program to read the
following data and determine:
(a) Whether third examination is necessary for a particular answer script.
(b) Obtained fnal marks (out of 70) by each student of a particular course afer
third examination if necessary.
Roll No. 1st Examiner 2nd Examiner Roll No. 1st Examiner 2nd Examiner
1001 65 58 1004 68 48
1002 55 54 1005 50 52
1003 40 30 1006 15 32
ProgReference.com
Structure and Union ◾ 435
ProgReference.com
436 ◾ Learn Programming with C
ProgReference.com
CHAPTER 6
File Management
A file is a memory space where some data is stored. C provides various functions to
deal with the file. This chapter provides mechanisms/operations how to manipulate
files, known as the file management.
(1) Text file: any text editor or .txt file. All the contents are in plain text and can be easily
edited or deleted.
(2) Binary file: any .bin file. All the contents are in binary form (0’s and 1’s) and cannot
be easily edited and hence provide better security.
ProgReference.com
438 ◾ Learn Programming with C
Example:
We should always check whether the fle was opened successfully before using the
fle or any fle operation is performed. Te following code will do the job:
(2) Reading a fle: A fle frst needs to open in reading mode. Afer that fgetc() function
reads the characters sequentially one afer another until EOF (end of fle) is reached.
Example:
ProgReference.com
File Management ◾ 439
fputs() function is used to write a string to the fle. Example: fputs(str, fpw);
(4) Closing a fle: fclose() function is used to close an opened fle. Syntax: fclose(fpw);
Calling fclose() function ensures fle descriptor is properly disposed of and output
bufer fushed so that data written to the fle will be saved in the fle. If anyone failed
to do so, operating system properly closes the fle before termination of the program.
To read or write in a binary, we need to change the fle name and mode of operation as
shown below:
6.3 PREPROCESSORS
Preprocessor allows defning macros and transforms the source code before compilation.
Te directives instruct the preprocessor to do something. Some common uses of prepro-
cessing directives are as follows:
(1) Including header fle: #include <stdio.h>, this will replace the contents of the header
fle stdio.h while transformation.
(2) Macros using #defne: #defne PI 3.14, this will replace 3.14 in place of PI during
transformation.
(3) Function like macros: #defne CIRCLE(rad) 3.14*rad*rad, this will replace 3.14*arg*
arg every time the program encounters CIRCLE(arg).
ProgReference.com
440 ◾ Learn Programming with C
2) #if expression
//block of codes
//these codes will be included if the value of
//expression is non-zero
#endif
3) #if expression
//block of codes
//these codes will be included if the value of
//expression is non-zero
#else
//block of codes
//these codes will be included if the value of
//expression is zero
#endif
4) #if expression
//block of codes
//these codes will be included if the value of
//expression is non-zero
#elif expression1
//block of codes
//codes will be included if the value of the
//expression1 is non-zero
#elif expression2
//block of codes
//codes will be included if the value of the
//expression2 is non-zero
#else
//block of codes
//codes will be included if values of all the
//above expressions are zero
#endif
6.5 EXAMPLES
PROBLEM-01
Write a program to read name and marks of a student and store them in a fle.
ProgReference.com
File Management ◾ 441
ProgReference.com
442 ◾ Learn Programming with C
ProgReference.com
File Management ◾ 443
/*the closing curly brace indicates the end of the body of main()
function and the end of the program. No statement will execute after
that curly brace*/
PROBLEM-02
Write a program to open the fle created in the last problem, read name and marks
of a student, and append them in the fle.
ProgReference.com
444 ◾ Learn Programming with C
and the program execution starts from the first statement just
after this brace*/
char name[50];
/*char type array is declared which can take only characters.
Size of the array is 50, means it can take up to 50 characters.
Each array elements can be accessed using indexes starting from
0 to 49, that is- str[0], str[1], . . ., str[49]*/
float mark;
/*float type variable is declared which can take and store any
decimal value*/
FILE *fptr;
/*FILE is a structured data type defined in stdio.h header file.
Here a FILE type pointer is declared to refer any file*/
fptr = fopen("C:\\Intel\\student.txt", "a");
/*fopen() function opens a text file named student.txt in the
address C:\\Intel\\ with append mode, indicated by “a”, and
returns a FILE type pointer. Anything written into the file will
be appended after the previous information*/
if (fptr == NULL){
/*after opening a file in C, we must always check whether
the file opens successfully. To do that we check the pointer
returned by fopen() function. If it is NULL then file could not
open. Hence, here if the file failed to open the condition is
true and following two statements will be executed */
printf("Error in opening the file, exiting . . .");
/*output function printf() will display the message inside
the double quotation as it is on the screen*/
exit(1);
/*exit(1) function causes abnormal termination of the
program. All buffers, temporary files, streams are deleted
or cleared before the termination*/
}
/*this closing curly brace indicates the end of the if body*/
printf("Enter name of the student:");
/*output function printf() will display the message inside the
double quotation as it is on the screen*/
gets(name);
/*gets() is an input function that can take any string or
array of characters, including space, tab, etc., end with
NULL character \0 and store the string to its parameter
name*/
printf("Enter marks of the student:");
/*output function printf() will display the message inside the
double quotation as it is on the screen*/
scanf("%f", &mark);
/*scanf() function takes a decimal value from the standard
input terminal and store the float value to the variable
ProgReference.com
File Management ◾ 445
mark*/
fprintf(fptr, "\nName: %s\nMarks: %0.2f\n", name, mark);
/*fprintf() function will write information inside the double
quotation as it is in the file referred by the pointer fptr.
Here enter is written in place of new line character, string
name in place of %s format specifier and decimal value mark in
place of %0.2f format specifier with 2 point precision. As fptr
referred to a file opened as mode “a”, these information will
be written after the existing information in the file*/
fclose(fptr);
/*once a file is open in C, it is a good practice to close the
file before end of the program to properly flush the output
buffer. This is done here by the fclose() function which close
the file referred by its argument fptr*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace indicates the end of the body of main()
function and the end of the program. No statement will execute after
that curly brace*/
PROBLEM-03
Write a program to open the fle created in the last problem, read information from the
fle, and display them on the screen.
ProgReference.com
446 ◾ Learn Programming with C
ProgReference.com
File Management ◾ 447
ProgReference.com
448 ◾ Learn Programming with C
PROBLEM-04
Te annual examination results of n students are tabulated as follows:
Step-1: Start
Step-2: Defne struct subject with members mark, point, and letter
Step-3: Defne struct exam with members roll, sub[100], total, gpa, and pos
Step-4: Read values of numstd and numsub
Step-5: Initialize i←0
ProgReference.com
File Management ◾ 449
ProgReference.com
450 ◾ Learn Programming with C
Step-6: If i<numstd
6.1: Read value of stud[i].roll
6.2: Initialize stud[i].total←0, totgrd←0 and j←0
6.3: If j<numsub
6.3.1: Read value of stud[i].sub[j].mark
6.3.2: If stud[i].sub[j].mark>=90
6.3.2.1: stud[i].sub[j].point←4.00
6.3.2.2: stud[i].sub[j].letter←“A+”
6.3.2.3: Go to Step-6.3.9
6.3.3: If stud[i].sub[j].mark>=80
6.3.3.1: stud[i].sub[j].point←3.50
6.3.3.2: stud[i].sub[j].letter←“A”
ProgReference.com
6.3.3.3: Go to Step-6.3.9
File Management ◾ 451
6.3.4: If stud[i].sub[j].mark>=70
6.3.4.1: stud[i].sub[j].point←3.00
6.3.4.2: stud[i].sub[j].letter←“B”
6.3.4.3: Go to Step-6.3.9
6.3.5: If stud[i].sub[j].mark>=60
6.3.5.1: stud[i].sub[j].point←2.50
6.3.5.2: stud[i].sub[j].letter←“C”
6.3.5.3: Go to Step-6.3.9
6.3.6: If stud[i].sub[j].mark>=50
6.3.6.1: stud[i].sub[j].point←2.00
6.3.6.2: stud[i].sub[j].letter←“D”
ProgReference.com
6.3.6.3: Go to Step-6.3.9
452 ◾ Learn Programming with C
6.3.7: stud[i].sub[j].point←0.00
6.3.8: stud[i].sub[j].letter←“F”
6.3.9: stud[i].total← stud[i].total+stud[i].sub[j].mark
6.3.10: totgrd←totgrd+stud[i].sub[j].point
6.3.11: j←j+1
6.3.12: Go to Step-6.3
6.4: stud[i].gpa←totgrd/numsub
6.5: i←i+1
6.6: Go to Step-6
Step-7: Initialize i←1
Step-8: If i<=numstd−1
8.1: Initialize j←1
8.2: If j<=numstd−i
8.2.1: If stud[j−1].gpa<stud[j].gpa
8.2.1.1: temp←stud[j−1]
8.2.1.2: stud[j−1]←stud[j]
8.2.1.3: stud[j]←temp
8.2.1.4: Go to Step-8.2.3
8.2.2: If stud[j−1].gpa=stud[j].gpa
8.2.2.1: If stud[j−1].total<stud[j].total
8.2.2.1.1: temp←stud[j−1]
8.2.2.1.2: stud[j−1]←stud[j]
8.2.2.1.3: stud[j]←temp
8.2.3: j←j+1
8.2.4: Go to Step-8.2
8.3: i←i+1
8.4: Go to Step-8
Step-9: Initialize i←0
ProgReference.com
File Management ◾ 453
Step-10: If i<numstd
10.1: stud[i].pos←i+1
10.2: i←i+1
10.3: Go to Step-10
Step-11: fp←fopen()
Step-12: If fp=NULL
12.1: Display ‘Cannot open’
12.2: Go to Step-24
Step-13: Initialize i←0
Step-14: If i<numstd
14.1: Save to fle stud[i].roll
14.2: Initialize j←0
14.3: If j<numsub
14.3.1: Save values of stud[i].sub[j].letter, stud[i].sub[j].point, stud[i].gpa
and stud[i].pos to fp
14.3.2: j←j+1
14.3.3: Go to Step-14.3
14.4: i←i+1
14.5: Go to Step-14
Step-15: Initialize i←1
Step-16: If i<=numstd−1
16.1: Initialize j←1
16.2: If j<=numstd−i
16.2.1: If stud[j−1].roll>stud[j].roll
16.2.1.1: temp←stud[j−1]
16.2.1.2: stud[j−1]←stud[j]
16.2.1.3: stud[j]←temp
16.2.2: j←j+1
16.2.3: Go to Step-16.2
ProgReference.com
454 ◾ Learn Programming with C
16.3: i←i+1
16.4: Go to Step-16
Step-17: fp←fopen()
Step-18: If fp=NULL
18.1: Display ‘Cannot open’
18.2: Go to Step-24
Step-19: Initialize i←0
Step-20: If i<numstd
20.1: Save value of stud[i].roll to fp
20.2: Initialize j←0
20.3: If j<numsub
20.3.1: Save values of stud[i].sub[j].letter, stud[i].sub[j].point, stud[i].gpa,
and stud[i].pos to fp
20.3.2: j←j+1
20.3.3: Go to Step-20.3
20.4: i←i+1
20.5: Go to Step-20
Step-21: fp←fopen()
Step-22: If fp=NULL
22.1: Display ‘Cannot open’
22.2: Go to Step-25
Step-23: If 1 or true
23.1: ch←fgetc(fp)
23.2: If ch=EOF
23.2.1: Go to Step-24
23.3: Display value of ch
23.4: Go to Step-23
ProgReference.com
File Management ◾ 455
Step-24: Stop
Programming Code of the Solution:
ProgReference.com
456 ◾ Learn Programming with C
ProgReference.com
File Management ◾ 457
ProgReference.com
458 ◾ Learn Programming with C
ProgReference.com
File Management ◾ 459
#include <stdlib.h>
/*header file stdlib.h contains prototypes of the library function
exit(), hence needs to be included using preprocessor directive
#include before they can be used in the program*/
struct subject{
/*structured data type subject is defined here using keyword struct;
its members are declared within the curly braces*/
int mark;
/*int type variable mark is declared as member of the structured
data type subject, that will be used to store the obtained mark
in a particular subject*/
float point;
/*float type variable point is declared as member of the
structured data type subject, that will be used to store the
obtained grade-point in a particular subject*/
char *letter;
/*char type pointer letter is declared as member of the
structured data type subject, that will be used to store the
obtained letter-grade in a particular subject*/
};
/*definition of structured data type must end with a semicolon; no
variable of the defined data type marks is declared here*/
struct exam{
/*structured data type exam is defined here using keyword struct;
its members are declared within the curly braces*/
int roll, total, pos;
/*int type variables roll, total and pos are declared as members
of the structured data type exam, that will be used to store
roll no, obtained total marks and merit position, respectively
of a particular student*/
struct subject sub[10];
/*structured subject type array sub[] with size 10 is declared
as member of the structured data type exam, that will be used to
store information of maximum 10 subjects of a particular student*/
float gpa;
/*float type variable gpa is declared as member of the structured
data type exam, that will be used to store gpa calculated for
a particular student*/
};
/*definition of structured data type must end with a semicolon; no
variable of the defined data type marks is declared here*/
int main(){
/*here main() function returns an integer and parameters/arguments
of the main() function also remain void; execution of the program
starts with main() function; no statement before opening curly
brace of the main() function will be executed by the compiler*/
ProgReference.com
460 ◾ Learn Programming with C
FILE *fp;
/*FILE is a structured data type defined in stdio.h header file.
Here a FILE type pointer fp is declared to refer any file*/
struct exam stud[100], temp;
/*structured exam type variable temp and an array stud[] with
size 100 are declared here; members of each of the array element
can be accessed through dot (.) operator*/
int numstd, numsub, i, j;
/*integer type variables numstd, numsub, i and j are declared;
required memory spaces have been allocated for each of the
variables*/
float totgrd;
/*float type variable totgrd is declared that can store any
decimal value*/
char ch;
/*char type variable is declared which can take and store only
character*/
printf("Enter the number of students: ");
/*output function printf() displays the message in the quotation
as it is on screen*/
scanf("%d", &numstd);
/*number of student will be input using this input function
scanf() which will take decimal value from input terminal and
keep the value in the memory spaces allocated for the variable
numstd*/
printf("How many subjects: ");
/*output function printf() displays the message in the quotation
as it is on screen*/
scanf("%d", &numsub);
/*number of subject will be input using this input function
scanf() which will take decimal value from input terminal and
keep the value in the memory spaces allocated for the variable
numsub*/
for (i=0; i<numstd; i++){
/*here i=0 is initialization, i<numstd is condition and i++ is
increment; this for loop works as follows- initialization is
done only once at the start; then condition is checked, if it is
true statements in the body, enclosed by curly braces, execute
and value of i is incremented by 1; now the condition is checked
again and if it is true the body executes again; these steps
continue till the condition becomes false; this for loop is
used here to input necessary information of all numstd students
and calculate marks, gpa and letter-grade; in each iteration
individual student is considered*/
printf("Enter the roll no. of student #%d: ", i+1);
/*output function printf() displays the message in the
quotation as it is on screen except format specifier %d is
replaced by the value of i+1*/
ProgReference.com
File Management ◾ 461
scanf("%d", &stud[i].roll);
/*this scanf() function takes a decimal value from input
terminal and save the value in roll which is a member of
struct subject type array stud[]*/
stud[i].total=0;
/*member total of structured subject type array stud[] is
initialized to 0 that will be used to store the total marks
of a particular student; it is initialized to 0, otherwise
the summation operation may give wrong answer because, when
we declare a variable a memory space is allocated for that
variable and the memory space may contain some garbage
value; when we sequentially add the data with the total
and result will be accumulated in the total variable, the
garbage value may add up in the first summation*/
totgrd=0;
/*variable totgrd is initialized to 0 that will be used to store
the total grade of a particular student needed to calculate
gpa; it is initialized to 0 to avoid add up any garbage value
in the first summation and get any wrong answer*/
for (j=0; j<numsub; j++){
/*here j=0 is initialization, j<numsub is condition
and j++ is increment; this for loop works as follows-
initialization is done only once at the start; then
condition is checked, if it is true statements in the
body, enclosed by curly braces, execute and value of j
is incremented by 1; now the condition is checked again
and if it is true the body executes again; these steps
continue till the condition becomes false; this for loop
is used here to input necessary information of all numsub
subjects and calculate marks, gpa and letter-grade; in
each iteration individual subject is considered*/
printf("Mark obtained in EEE-110%d: ", j+1);
/*output function printf() displays the message in the
quotation as it is on screen except format specifier %d
is replaced by the value of j+1*/
scanf("%d", &stud[i].sub[j].mark);
/*this scanf() function takes a decimal value from
input terminal and save the value in mark which is a
member of struct subject type array sub[] which is in
turn is a member of structured exam type array stud[],
hence variable mark is accessed through double dot (.)
operators*/
if (stud[i].sub[j].mark>=90){
/*if the condition is true, means marks of a particular
subject of a particular student is greater than or
equal to 90, then following two statements execute;
multiple statements in the body of 'if' is enclosed
with curly braces*/
ProgReference.com
462 ◾ Learn Programming with C
stud[i].sub[j].point=4.00;
/*point is a member of struct subject type array
sub[] which is in turn is a member of structured
exam type array stud[], hence variable point is
accessed through chain of dot (.) operators and
assigned a value 4.00*/
stud[i].sub[j].letter="A+";
/*character type pointer letter is a member of
struct subject type array sub[] which is in turn
is a member of structured exam type array stud[],
hence variable point is accessed through chain of
dot (.) operators and assigned a string A+*/
}
/*this closing curly brace indicates end of if (stud[i].
sub[j].mark>=90)*/
else if (stud[i].sub[j].mark>=80){
/*if the condition is true, means marks of a particular
subject of a particular student is greater than or equal to
80 but less than 90, then following two statements execute;
condition of 90 has already been checked in the previous
'if' condition and condition of 80 is only checked if the
above 'if' condition of 90 is false; multiple statements
in the body of 'if' is enclosed with curly braces*/
stud[i].sub[j].point=3.50;
/*point is a member of struct subject type array sub[]
which is in turn is a member of structured exam type
array stud[], hence variable point is accessed through
chain of dot (.) operators and assigned a value 3.50*/
stud[i].sub[j].letter="A";
/*character type pointer letter is a member of
struct subject type array sub[] which is in turn
is a member of structured exam type array stud[],
hence variable point is accessed through chain of
dot (.) operators and assigned a string A*/
}
/*this closing curly brace indicates end of else if
(stud[i].sub[j].mark>=80)*/
else if (stud[i].sub[j].mark>=70){
/*if the condition is true, means marks of a particular
subject of a particular student is greater than or equal
to 70 but less than 80, then following two statements
execute; condition of 90 and 80 have already been
checked in the previous 'if' and 'else if' conditions
and condition of 70 is only checked if the both of
the above 'if' and 'else if' conditions of 90 and 80
are false; multiple statements in the body of 'if' is
enclosed with curly braces*/
ProgReference.com
File Management ◾ 463
stud[i].sub[j].point=3.00;
/*point is a member of struct subject type array
sub[] which is in turn is a member of structured
exam type array stud[], hence variable point is
accessed through chain of dot (.) operators and
assigned a value 3.00*/
stud[i].sub[j].letter="B";
/*character type pointer letter is a member of
struct subject type array sub[] which is in turn
is a member of structured exam type array stud[],
hence variable point is accessed through chain of
dot (.) operators and assigned a string B*/
}
/*this closing curly brace indicates end of else if
(stud[i].sub[j].mark>=70)*/
else if (stud[i].sub[j].mark>=60){
/*if the condition is true, means marks of a particular
subject of a particular student is greater than or equal
to 60 but less than 70, then following two statements
execute; this condition of 60 is checked only if all the
above 'if' and 'else if' conditions are false*/
stud[i].sub[j].point=2.50;
/*point is a member of struct subject type array
sub[] which is in turn is a member of structured
exam type array stud[], hence variable point is
accessed through chain of dot (.) operators and
assigned a value 2.50*/
stud[i].sub[j].letter="C";
/*character type pointer letter is a member of
struct subject type array sub[] which is in turn
is a member of structured exam type array stud[],
hence variable point is accessed through chain of
dot (.) operators and assigned a string C*/
}
/*this closing curly brace indicates end of else if
(stud[i].sub[j].mark>=60)*/
else if (stud[i].sub[j].mark>=50){
/*if the condition is true, means marks of a particular
subject of a particular student is greater than or equal
to 50 but less than 60, then following two statements
execute; this condition of 50 is checked only if all the
above 'if' and 'else if' conditions are false*/
stud[i].sub[j].point=2.00;
/*point is a member of struct subject type array
sub[] which is in turn is a member of structured
exam type array stud[], hence variable point is
accessed through chain of dot (.) operators and
ProgReference.com
464 ◾ Learn Programming with C
ProgReference.com
File Management ◾ 465
stud[i].gpa=totgrd/numsub;
/*gpa of each student is calculated from total grade-point
totgrd of that particular student; in each iteration of
first 'for' loop individual student is considered*/
}
/*this closing curly brace indicates end of for (i=0; i<numstd;
i++)*/
for (i=1; i<=numstd−1; i++)
/* this for loop is used to repeat the following 'for' loop as
long as the condition satisfies; here i=1 is initialization,
i<=numstd−1 is condition and i++ is increment; this for loop
works as follows- initialization is done only once at the start;
then condition is checked, if it is true statement in the body
executes and value of i is incremented by 1; now the condition
is checked again and if it is true the body executes again;
these steps continue till the condition becomes false; this for
loop together with the following for loop are used here to sort
students based on their earned gpa in ascending order*/
for (j=1; j<=numstd−i; j++)
/*this for loop is used to compare gpa of each student
and swap if necessary to place one student in its right
position in each iteration; hence after each iteration,
number of gpa of students to be compared is decreased
by 1, as the student which is already placed in right
position in previous iteration does not need to be compared
again in the subsequent iteration; here j=1 is initialization,
j<numstd−i is condition and j++ is increment; this for loop
works as follows- initialization is done only once at the
start; then condition is checked, if it is true statement in
the body executes and value of j is incremented by 1; now the
condition is checked again and if it is true the body executes
again; these steps continue till the condition becomes false*/
if (stud[j−1].gpa<stud[j].gpa){
/*body of above 'for' loop contains only this 'if'
condition; if the condition of 'if' is true then following
three statements will execute; as there are multiple
statements in the body of 'if' they are enclosed with
curly braces; here gpa of two contiguous students are
compared, if the larger gpa stays above the smaller one
then they are swapped to always keep the student with
smaller gpa above the larger one*/
temp=stud[j−1];
/*array element stud[j−1] is stored in variable temp*/
stud[j−1]=stud[j];
/*array element stud[j] is stored as array
element stud[j−1], that is and stud[j] now becomes
stud[j−1]*/
ProgReference.com
466 ◾ Learn Programming with C
stud[j]=temp;
/*value of temp is stored as array element stud[j],
that is stud[j−1] now becomes stud[j]*/
}
/*this closing curly brace indicates the end of 'if'*/
else if (stud[j−1].gpa==stud[j].gpa)
/*if above 'if' condition is false then this 'else if'
condition is checked; if this condition is true, means
gpa of two contiguous students are equal then following
'if' condition executes to sort students according to
their obtained total marks in ascending order*/
if (stud[j−1].total<stud[j].total){
/*if this condition is true then following three
statements will execute; means- here total of two
contiguous students are compared, if the larger
total stays above the smaller one then they are
swapped to always keep the student with smaller
total above the larger one*/
temp=stud[j−1];
/*array element stud[j−1] is stored in variable
temp*/
stud[j−1]=stud[j];
/*array element stud[j] is stored as array
element stud[j−1], that is and stud[j] now
becomes stud[j−1]*/
stud[j]=temp;
/*value of temp is stored as array element
stud[j], that is stud[j−1] now becomes
stud[j]*/
}
/*this closing curly brace indicates the end of
'if' with condition*/
for (i=0; i<numstd; i++)
/*this for loop is used to set position of each student
according to sorted gpa; here i=0 is initialization, i<numstd is
condition and i++ is increment; this for loop works as follows-
initialization is done only once at the start; then condition is
checked, if it is true statement in the body executes and value
of i is incremented by 1; now the condition is checked again
and if it is true the body executes again; these steps continue
till the condition becomes false*/
stud[i].pos=i+1;
/*member pos of structured exam type array stud[] is set to
i+1; at 1st iteration position of first student is set to
stud[0].pos=1, at 2nd iteration position of second student
is set to stud[1].pos=2, and so on*/
ProgReference.com
File Management ◾ 467
fp=fopen("c:\\myfiles\\Results.txt", "w");
/*fopen() function opens a text file named Results.txt in the
address C:\\myfiles\\ with write mode, indicated by “w”, and
returns a FILE type pointer*/
if (fp==NULL){
/*after opening a file in C, we must always check whether
the file opens successfully; to do that we check the pointer
returned by fopen() function; if it is NULL then file could not
open; hence, here if the file failed to open the condition is
true and following two statements will be executed*/
puts("Cannot open source file!\n");
/*output function puts() will display the string message
inside the double quotation as it is on screen except
newline character \n is replaced by enter*/
exit(1);
/*exit(1) function causes abnormal termination of the
program; all buffers, temporary files, streams are deleted
or cleared before the termination*/
}
/*this closing curly brace indicates the end of the 'if' body*/
fprintf(fp, "\nResult according to merit position . . . \n");
/*fprintf() function writes information inside the double
quotation as it is in the file referred by the pointer fp; here
enter is written in place of new line character*/
for (i=0; i<numstd; i++){
/*this for loop is used to display information of each student
according to sorted gpa; in each iteration individual student is
considered; here i=0 is initialization, i<numstd is condition and
i++ is increment; this for loop works as follows- initialization
is done only once at the start; then condition is checked, if
it is true statements in the body execute and value of i is
incremented by 1; now the condition is checked again and if it
is true the body executes again; these steps continue till the
condition becomes false*/
fprintf(fp, "Roll No.: %d\n", stud[i].roll);
/*fprintf() function will write information inside the
double quotation as it is in the file referred by the pointer
fp; here enter is written in place of new line character,
value of stud[i].roll in place of %d format specifier*/
for (j=0; j<numsub; j++)
/*this for loop is used to display information of all subjects
of each student according to sorted gpa; in each iteration
individual subject of a particular student is considered;
here j=0 is initialization, j<numsub is condition and j++ is
increment; this for loop works as follows- initialization
is done only once at the start; then condition is checked,
ProgReference.com
468 ◾ Learn Programming with C
ProgReference.com
File Management ◾ 469
ProgReference.com
470 ◾ Learn Programming with C
fp=fopen("c:\\myfiles\\Results.txt", "r");
/*fopen() function opens a text file, same file used before
to write information of the students, named Result.txt in the
address C:\\my files\\ with read mode, indicated by “r”, and
returns a FILE type pointer*/
if (fp==NULL){
/*after opening a file in C, we must always check whether
the file opens successfully; to do that we check the pointer
returned by fopen() function; if it is NULL then file could
not open; hence, here if the file failed to open the condition
is true and following two statements execute*/
puts("Cannot open target file!\n");
/*output function puts() will display the string message
inside the double quotation as it is on screen except
newline character \n is replaced by enter*/
exit(1);
/*exit(1) function causes abnormal termination of the
program; all buffers, temporary files, streams are deleted
or cleared before the termination*/
}
/*this closing curly brace indicates the end of the 'if'
body*/
printf("\n");
/*output function printf() displays enter due to newline
character \n*/
while (1){
/*as the 1 means true, the condition of 'while' is always true
and following statements in the body of while, enclosed by curly
braces, execute in any case; in each iteration character is read
sequentially from the file and displayed on screen*/
ch=fgetc(fp);
/*fgetc() function reads a character from the file referred by
the pointer fp; at 1st iteration, it reads the 1st character
(ch=1st character) and the pointer automatically points
to the 2nd character; at 2nd iteration, it reads the 2nd
character (ch=2nd character) and the pointer automatically
points to the 3rd character; and so on*/
if (ch==EOF)
/*ch is compared with EOF, means whether we reach the end-
of-file or not; if yes, then the program steps out of the
while loop*/
break;
/*program control immediately comes out of the while
loop skipping following statement*/
printf("%c", ch);
/*output function printf() displays character ch due to
format specifier %c*/
}
/*this closing curly brace indicates the end of while loop*/
ProgReference.com
472 ◾ Learn Programming with C
fclose(fp);
/*once a file is open in C, it is a good practice to close the
file before end of the program or reuse the file to properly
flush the output buffer; this is done here by the fclose()
function which close the file referred by its argument fp*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace indicates the end of the body of main()
function and the end of the program; no statement will execute after
that curly brace*/
EXERCISES
5) What are the C functions used to read or write a fle in text mode?
A) fprintf(), fscanf()
B) fread(), fwrite()
C) fprint(), fscan()
D) read(), write()
6) What are the C functions used to read or write a fle in binary mode?
A) fprintf(), fscanf()
B) fread(), fwrite()
C) readf(), writef()
D) printf(), scanf()
7) What is the C function used to move current pointer to the beginning of fle?
FILE *fp;
A) rev(fp)
B) rewind(fp)
C) rew(fp)
D) wind(fp)
ProgReference.com
[Ans. B, A, D, B, A, B, B, C, A]
474 ◾ Learn Programming with C
“w+”: opens a text fle both for reading and for writing; frst truncating the fle to
zero length if it exists or creating the fle if it does not exist.
8) Is FILE a built-in data type?
Ans. No, it is a structure defned in stdio.h.
9) How can we determine whether a fle is successfully open or not using fopen()
function?
Ans. Afer opening the fle using the fopen() function and assigning the “fle” to a
variable, we must check the return value. An error has occurred if the variable ==
NULL; otherwise, the fle was successfully open.
Problems to Practice
1) Write a program to read name and marks of a student and store them in a fle.
2) Write a program to open the fle created in the last problem, read name and marks
of a student and append them in the fle.
3) Write a program to open the fle created in the last problem, read information from
the fle, and display them on the screen.
4) Write a program to calculate the area and circumference of a circle.
5) Te annual examination results of n students are tabulated as follows:
(d) Te result should be displayed according to the roll number and merit.
(e) Save the results in a text fle and retrieve and print the results from the text fle.
6) Write a program to write and read multiple lines in a text fle.
7) Write a program to count the number of lines, words, and characters in a text fle.
8) Write a program to delete and replace a specifc line in a text fle.
9) Write a program to copy a fle and write it in a new fle.
10) Write a program to merge two fles and write it in a new fle.
11) Write a program to read a string from a fle and display it to the user.
ProgReference.com
CHAPTER 7
C Graphics
7.1 INTRODUCTION
C applications usually run in a console window known as CUI (character user interface).
C library contains header file graphics.h containing many predefined functions to imple-
ment GUI (graphical user interface) in C applications. To implement GUI programming,
we need to convert the output screen from CUI (character data) mode to GUI (pixel) mode.
7.2 FUNCTION
All the related functions to implement the graphics programming are available in the
header file graphics.h. Open graphics.h header file to see all the functions available in the
header file. Some of the important functions used are as follows:
initgraph() used to convert CUI mode into GUI mode (initialize graphics mode). It
takes three arguments: graphics driver, graphics mode, and path.
closegraph() used to deallocate all memory allocated by graphics system and shut
down the graphics system.
outtextxy() displays a message in (x, y) coordinate. It takes three arguments: x and y
arguments, and a message as string or char type pointer.
getmaxx() returns the maximum x coordinate for current graphics mode and driver.
getmaxy() returns the maximum y coordinate for current graphics mode and driver.
ProgReference.com
478 ◾ Learn Programming with C
setcolor() sets drawing color. It takes an integer argument whose value (0 to 15)
determines a particular color. Or name of the color (BLACK, CYAN,
RED, WHITE etc.) can be passed as string argument.
setbkcolor() sets the background color. It takes an integer argument whose value (0 to
15) determines a particular color. Or name of the color (BLACK, CYAN,
RED, WHITE etc.) can be passed as string argument.
settextstyle() sets the current text characteristics (font, direction, and size). It takes three
arguments: frst argument sets the font depending on integer constant (0,
1, 2, 3, or 4), second argument sets the font’s direction (HORIZ_DIR=0
for horizontal from lef to right and VERT_DIR=1 for vertical from bot-
tom to top), and the third argument sets the font’s size which gradually
increases depending on the integer value you have passed from 1 to 10.
kbhit() checks for recent keystrokes. It returns a nonzero integer if a keystroke is
available.
setfllstyle() sets the current fll pattern and fll color. First parameter represents the
pattern and the second one the color. Te allowed patterns are EMPTY_
FILL=0, SOLID_FILL=1, LINE_FILL=2, . . ., USER_FILL=12 and the col-
ors are BLACK=0, BLUE=1, . . ., WHITE=15.
foodfll() flls an enclosed area at location (x, y) coordinate. Te current fll pattern
and fll color are used to fll the area. Border color of the enclosed area is
passed as third argument of the function.
delay() delay() function is built upon another C library function clock(). Tis is
used to suspend execution of a program for a particular time. Te time to
be delayed is passed as argument in some integer milliseconds.
cleardevice() clears the screen in graphics mode, like clrscr() function does in CUI
mode, and sets the current position to (0, 0). To clear the screen, it just
flls the screen with current background color.
DETECT a macro that automatically detect the suitable graphics driver.
ProgReference.com
C Graphics ◾ 479
ProgReference.com
480 ◾ Learn Programming with C
7.7 EXAMPLES
PROBLEM-01
Write a program to draw a bar of size 100 × 300 and a circle with a radius of 50.
ProgReference.com
C Graphics ◾ 481
ProgReference.com
482 ◾ Learn Programming with C
Comments:
To run the above program in Turbo C, we need to defne the initgraph() function in the
program as follows:
initgraph(&gd, &gm, “C:\\TC\\BGI”);
Tat is, instead of writing an empty string in the third argument, we need to write the full
path address of the BGI folder in TC with double backslash. Tis modifcation is needed
for all the other graphics program to run in Turbo C.
PROBLEM-02
Write a program that prints a message in diferent colors.
ProgReference.com
C Graphics ◾ 483
ProgReference.com
484 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 485
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-03
Write a program that displays diferent messages in diferent colors and diferent
directions on diferent backgrounds.
ProgReference.com
486 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 487
cleardevice();
/*this function erases the previous two messages shown and
clears the screen*/
setbkcolor(RED);
/*sets the background color to red from white that was previously
set*/
setcolor(BLUE);
/* sets the drawing color to blue from the green that was
previously set*/
settextstyle(1, VERT_DIR, 3);
/*sets the current text characteristics; first argument sets
the font to TRIPLEX_FONT=1, second argument sets the font’s
direction to vertical and the third argument sets the size of
the font to 3*/
outtextxy(50, 50, "Very effective book to learn C . . . ");
/*this displays the message enclosed by double quotations in
the coordinate (50, 50) in the vertical direction; (50, 50) is
the top coordinate*/
outtextxy(150, 50, "Press any key to close . . . ");
/*this displays the message enclosed by double quotations in
the coordinate (150, 50) in the vertical direction; (150, 50)
is the top coordinate*/
getch();
/*input function getch() is called here to keep the console
state visible until we enter any character*/
closegraph();
/*function closegraph() is called here to deallocate all memory
and shut down the graphics system*/
return 0;
/*0 is returned as it is the standard for the successful
execution of the program*/
}
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-04
Write a program that draws 16 circles of same size at diferent coordinates where each
circle intersects all its neighbor circles.
ProgReference.com
488 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 489
int main(){
/*all C program must have a main() function with return type void
or int; here there is no parameter of the main() function and it
returns an integer; opening curly brace specifies start of the
main() function and no statement before that curly brace is executed
by the compiler*/
int gd=DETECT, gm;
/*two integer type variables gd, and gm are declared. Variable
gd is initialized to DETECT which is a macro that automatically
detect graphics driver suitable for hardware*/
int x, y;
/*two integer type variables x and y are declared; compiler
assigns required spaces in memory for these two variables*/
initgraph(&gd, &gm, (char *)"");
/*library function initgraph() is called here to initialize the
graphics mode. Graphics mode gm represents screen resolution
and will be selected implicitly depending on the graphics
driver gd; as the mentioning path in the third argument is not
mandatory we write it as empty string*/
setbkcolor(WHITE);
/*sets the background color to white; the default color is
black*/
setcolor(RED);
/* sets the drawing color to red*/
for (y=100; y<=400; y+=100)
/*y=100 is initialization, y<=400 is condition and y+=100
=> y=y+100 is increment; initialization is done once at the
beginning of the loop; next the condition is checked, and if it
is true, the statement in the body is executed; the value of y
is incremented by 100 before the condition is re-checked; this
process continues until the condition becomes false at which
point the program flow exits the loop*/
for (x=100; x<=400; x+=100)
/*x=100 is initialization, x<=400 is condition and x+=100
=> x=x+100 is increment; initialization is done once at
the beginning of the loop; next the condition is checked,
and if it is true, the statement in the body is executed;
the value of x is incremented by 100 before the condition
is re-checked; this process continues until the condition
becomes false at which point the program flow exits the
loop*/
circle(x, y, 50);
/*this function draws a circle of radius 50 cm whose
center is at (x, y) coordinate; we want to draw 4×4=16
circles that touches each others’ neighbor circles;
that’s why the distance between two centers is 100
and the radius of each circle is 50; for the first 4
ProgReference.com
490 ◾ Learn Programming with C
PROBLEM-05
Write a program that draws dynamic rainbow with beautiful colors.
ProgReference.com
C Graphics ◾ 491
ProgReference.com
492 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 493
/*the closing curly brace specifies the end of the main() function’s
body, as well as the program’s end; after that curly brace, no
statement is executed*/
PROBLEM-06
Write a program that draws a simple house and shows it on the screen.
ProgReference.com
494 ◾ Learn Programming with C
ProgReference.com
496 ◾ Learn Programming with C
PROBLEM-07
Write a program to make a dynamic digital clock.
ProgReference.com
C Graphics ◾ 497
ProgReference.com
498 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 499
ProgReference.com
500 ◾ Learn Programming with C
PROBLEM-08
Write a program that displays an animated smiley on the screen.
ProgReference.com
C Graphics ◾ 501
ProgReference.com
502 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 503
ProgReference.com
504 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 505
PROBLEM-09
Write a program that shows a man walking in the rain.
ProgReference.com
506 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 507
ProgReference.com
508 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 509
PROBLEM-10
Write a program that displays a moving car on the screen.
ProgReference.com
510 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 511
int i, x, y;
/*three integer type variables i, x and y are declared;
compiler assigns required spaces in memory for these three
variables*/
initgraph(&gd, &gm, (char *)"");
/*library function initgraph() is called here to initialize the
graphics mode. Graphics mode gm represents screen resolution
and will be selected implicitly depending on the graphics
driver gd; as the mentioning path in the third argument is not
mandatory we write it as empty string*/
x = getmaxx()/2;
/*library function getmaxx() returns the maximum x coordinate
that is divided by 2 and the value is assigned to variable
x*/
y = getmaxy()/2;
/*library function getmaxy() returns the maximum y coordinate
that is divided by 2 and the value is assigned to variable y;
thus we get the (x, y) coordinate at the center of the current
graphics mode and driver*/
x −= 300;
/*x=x−300, that is, the value of x is decreamented by 300*/
for (i=0; i<600; i=i+5){
/*i=0 is initialization, i<600 is condition and i=i+5 is
increment; initialization is done once at the beginning of the
loop; next the condition is checked, and if it is true, the
statements in the body are executed; the value of i is incremented
by 5 before the condition is re-checked; this process continues
until the condition becomes false at which point the program
flow exits the loop*/
cleardevice();
/*this clears the screen and sets the current postion
to (0, 0); if we don’t clear the screen after showing a
particular position of the car for 50 milliseconds, then in
the next iteration of the for loop, the car will be shown
in two different locations- current and previous; and so
on*/
line(x−70+i, y, x+70+i, y);
/*draws a straight line from a point (x−70+i, y) coordinate
to point (x+70+i, y) coordinate*/
line(x−69+i, y−3, x+69+i, y−3);
/*draws a straight line from a point (x−69+i, y−3) coordinate
to point (x+69+i, y−3) coordinate*/
arc(x−105+i, y, 0, 180, 35);
/*it draws an arc with center at (x−105+i, y), 0 is the
starting point of the angle, 180 is the ending point of the
angle, and 35 is the radius of the arc*/
circle(x−105+i, y, 25);
/*function circle() is called to draw a circle that takes
ProgReference.com
512 ◾ Learn Programming with C
ProgReference.com
C Graphics ◾ 513
Problems to Practice
1) Write a program to draw a bar of size 100 × 300 and a circle with a radius of 50.
2) Write a program that prints a message in diferent colors.
3) Write a program that displays diferent messages in diferent colors and diferent
directions on diferent backgrounds.
4) Write a program that draws 16 circles of same size at diferent coordinates where
each circle intersects all its neighbor circles.
5) Write a program that draws rainbow with beautiful colors.
ProgReference.com
514 ◾ Learn Programming with C
6) Write a program that draws a simple house and shows it on the screen.
7) Write a program to make a dynamic digital clock.
8) Write a program that displays an animated smiley on the screen.
9) Write a program that shows a man walking in the rain.
10) Write a program that displays a moving car on the screen.
11) Write a program that shows a man walking in the rain with an umbrella.
12) Write a program that creates a car and trafc light signal.
13) Write a program that shows a moving car with a fag in front.
14) Write a program to make a fying plane in C graphics.
15) Write a program to draw six concentric circles with diferent radius and colors.
16) Write a program that shows many circles with diferent colors and animation.
ProgReference.com
CHAPTER 8
C Cross-platform
ProgReference.com
516 ◾ Learn Programming with C
Now click on Next> and write SimpleLib on “Project title”: and select a folder where to cre-
ate the project (may be in C:\Users\SazzadImran\Desktop\ for example).
Now click Next>, select your compiler (GNU GCC Compiler in this case) and then click
Finish. A static library project named SimpleLib.cbp will be created.
Step-2: Click File→New→File . . ., select “C/C++ source”, click Go and then Next>.
Now select C and then click Next>. On the “Filename with full path”: go to C:\Users\
SazzadImran\Desktop\SimpleLib and write SimpleLib1 (user-defned name of the C source
fle) on the “File name”. Now click Save and then check Debug and Release under ‘In build
target(s):’ before click on Finish.
ProgReference.com
C Cross-platform ◾ 517
Step-3: On the SimpleLib1.c defne any function. We defne a function named add(), as
an example, that takes two integers as argument and return sum of the values. Include the
user-defned header fle, where the prototype of the function will be available, using double
quotation in the defnition of the function.
Defne another function subtract() in another source fle named SimpleLib3.c in a similar
way as we have defned function add() in SimpleLib1.c.
Step-4: Click File→New→File . . ., select “C/C++ header”, click Go and then Next>. On
the “Filename with full path:” go to C:\Users\SazzadImran\Desktop\SimpleLib and write
SimpleLib2 as user-defned name of the C header fle (may also be same as the source fle)
on the “File name” and then click Save. Now check Debug and Release under “In build
target(s):” and then click on Finish.
ProgReference.com
518 ◾ Learn Programming with C
Include all standard header fles, that are needed to compile and run the user-defned
functions add() and subtract(), afer 2nd statement (#defne . . .). Afer including header
fles, write the prototypes of the function add() and subtract() and then save the fle.
Step-5: Open main.c source fle, write the following codes in the fle, and click Save. You
may rename the main.c source fle as example1.c to write the following codes.
Step-6: Now click Build→Build. All object fles with .o extension are created in our target
folder obj\Debug, and a static library named libSimpleLib with .a extension is created in
our target folder bin\Debug.
ProgReference.com
C Cross-platform ◾ 519
Step-7: To run the program, click Project→Properties . . . →“Build targets”, select “Console
application” under Type: drop-down menu and check “Pause when execution ends”.
Now, click OK and then “Build and run”. Afer successful compilation, an executable fle
SimpleLib.exe is created in our target folder bin\Debug and the output of the program will
look as follows:
Now click on Next> and write SimpleLib on “Project title:” and select a folder where to cre-
ate the project (may be in C:\Users\SazzadImran\Desktop\ for example).
ProgReference.com
520 ◾ Learn Programming with C
Now click Next>, select your compiler (GNU GCC Compiler in this case) and then click
Finish. A dynamic library project named SimpleLib.cbp will be created.
Step-2: Click File→New→File . . ., select “C/C++ source”, click Go and then Next>.
Now select C and then click Next>. On the “Filename with full path:” go to C:\Users\
SazzadImran\Desktop\SimpleLib and write SimpleLib1 (user-defned name of the C source
fle) on the ‘File name’. Now click Save and then check Debug and Release under ‘In build
target(s):’ before click on Finish.
Step-3: On the SimpleLib1.c defne any function. We defne a function named add(), as
an example, that takes two integers as argument and returns sum of the values. Include the
user-defned header fle, where the prototype of the function will be available, using double
quotation in the defnition of the function.
Defne another function subtract() in another source fle named SimpleLib3.c in a similar
way as we have defned function add() in SimpleLib1.c.
ProgReference.com
C Cross-platform ◾ 521
Step-4: Click File→New→File . . ., select “C/C++ header”, click Go and then Next>. On
the ‘Filename with full path:’ go to C:\Users\SazzadImran\Desktop\ SimpleLib and write
SimpleLib2 as user-defned name of the C header fle (may also be same as the source fle)
on the ‘File name’ and then click Save. Now check Debug and Release under ‘In build
target(s):’ and then click on Finish.
Include all standard header fles that are needed to compile and run the user-defned
functions add() and subtract(), afer 2nd statement (#defne . . .). Afer including header
fles, write the prototypes of the function add() and subtract() and then save the fle.
Step-5: Open another source fle named example1.c, write the following codes in the fle
and click Save.
Step-6: Delete main.cpp and main.h fles from the project. Now click Build→Build. All
object fles with .o extension are created in our target folder obj\Debug, and a dynamic
link library named SimpleLib with .dll extension is created in our target folder bin\Debug.
ProgReference.com
522 ◾ Learn Programming with C
Other than .dll fle, a module defnition fle libSimpleLib.def and a static library
libSimpleLib.a were also created. Te .def fle provides information to the linker about
exported fles, attributes, etc., of the program to be linked, and is necessary while building
a dll fle.
Step-7: To run the program, click Project→Properties . . . →“Build targets”, select “Console
application” under Type: drop-down menu and check “Pause when execution ends”.
Now, click OK and then “Build and run”. Afer successful compilation, an executable fle
SimpleLib.exe is created in our target folder bin\Debug and the output of the program will
look like as follows:
8.2 TURBO C
Turbo C is a compiler for the C programming language from Borland. It includes a source
code editor, a fast compiler, and a linker. Tough it is discontinued nowadays, many still
use this compiler to edit and run C programs. Terefore, a step-by-step procedure to run C
programs using the Turbo C compiler is given below.
Step-1: Download and install Turbo C/C++ for windows. It may be downloaded from
https://techdecodetutorials.com/download/.
Step-2: Open the program and click on File -> New, an empty blue window appears.
Write your C program codes on the fle and click File -> Save as . . ., write a fle name of your
choice with .cpp extension (Example1.cpp, for example) and then click OK.
ProgReference.com
C Cross-platform ◾ 523
Step-3: Tree extra lines need to be added to run a program on the Turbo C platform.
For example, our frst C program in Chapter 1 was as follows:
ProgReference.com
524 ◾ Learn Programming with C
To run this program using the Turbo C compiler, the program should be modifed as follows:
Step-4: Press Alt+F9 to compile the program. Correct any error(s) or warning(s) on the
codes. Correcting the errors is a must, though it is optional to correct the warnings.
Recompile the program until we get 0 error(s) and 0 warning(s).
Step-5: Press Ctrl+F9 to execute the program. Te output may look like as follows:
ProgReference.com
526 ◾ Learn Programming with C
Step-2: Add path in environment variable to access gcc in visual studio code. To do that,
– copy the path of the bin directory of MinGW (for example, C:\Users\
SazzadImran\Desktop\MinGW\bin).
– go to Control Panel\System and Security\System and click on “Advanced sys-
tem settings”. Alternately, right-click on Tis PC, click on Properties, and then
on “Advanced system settings” on the rightmost column.
– click “Environment Variables . . .” and click on Path→Edit→New under the
“User variables”, paste the MinGW path in the blank feld, and then click on OK
button three times.
– go to Command Prompt (press Win+R, write cmd, and press Enter) and write
“gcc – version” and press Enter. If it shows the version number on the screen,
then the MinGW gcc is successfully installed.
ProgReference.com
C Cross-platform ◾ 527
Now install the sofware. During setup, we must check “Add to PATH” option.
Step-4: Start and confgure the visual studio code for running C programs. For that,
– install the C extension in the visual studio code (needed only for the frst time).
To do that, press the extension button, type c/c++ in the search bar, and install
the frst option from Microsof.
– again, type code runner in the search bar and install (needed only for the frst
time) the frst option from Jun Han.
Step-5: Click File→New File . . . → “Text File Built-In”→ “Select a Language” and then C
(c) to create a new source fle in the visual studio code. Now click File→Save and choose
C:\Users\SazzadImran\Desktop\MinGW\bin to save your fle (in the bin directory of
ProgReference.com
528 ◾ Learn Programming with C
MinGW) and give a name to your fle as you wish (for example, example1) and click on the
Save button.
Step-6: Write your C programming codes on the fle and save the program.
Now press ctrl+alt+n or click on the small play button in the top-right corner.
Step-7: To run a program that includes input from the user, frst click on
File→Preferences→Settings and type “run in terminal” and check the box “Code runner:
Run in Terminal”.
ProgReference.com
C Cross-platform ◾ 529
Now cancel the settings and return to the program. Run the code by pressing the run play
button. Te output will look like as follows:
If there is an error message showing “#include errors detected. Please update your include-
Path” while compiling or running a program even afer following all the above steps; in
that case, it should be enough to correct the error if we just restart the program “Visual
Studio Code”.
To install Visual Studio, click on VisualStudioSetup and then uncheck all the
Workloads except “Desktop development with C++”. Now click on “Install while
downloading”.
ProgReference.com
530 ◾ Learn Programming with C
Step-2: Start the Visual Studio program and click on “Create a new project”. Select
“Empty Project” and click Next.
Enter an appropriate project name (Project1, for example), choose a suitable location (for
example, C:\Users\SazzadImran\Desktop\), and click “Create”. A folder of the project name
will be added to the location.
Step-3: In the “Solution Explorer” window, right-click on “Source Files”, and choose
“Add” and “New Item”. Now give a fle name of your choice with .c extension (for example,
example1.c) and click Add. A blank fle will be created in the project.
ProgReference.com
C Cross-platform ◾ 531
Step-4: Write your C programming codes in the editor window and save the fle.
We may need to use more secure version scanf_s() instead of scanf() as input function.
Because the Visual Studio considers scanf() as an unsafe function and returns error code
C4996 while compiling the program. Te format and structure of both scanf_s() and
scanf() functions are identical.
Step-5: Now click Build→“Build Solution” to create the executable fle. If there is any
syntax error in the program, the error messages will be displayed in the output window.
Make necessary corrections in the source code, save it again, and then click Build→“Build
Solution”. Continue correcting the source codes until there is no more error.
Step-6: Now press ctrl+F5 to run and execute the program. Te output will show in the
output window accordingly.
ProgReference.com
532 ◾ Learn Programming with C
Or, download and install the GCC compiler for the system from http://tdm-gcc.tdragon.
net/download.
Step-2: Properly set the Path environment variable to access the program from any other
location. To do that,
– copy the path of the bin directory of MinGW or TDM-GCC-64 (for example,
C:\Program Files (x86)\CodeBlocks\MinGW\bin or, C:\TDM-GCC-64\bin).
– go to Control Panel\System and Security\System and click on “Advanced sys-
tem settings”. Alternately, right-click on Tis PC, click on Properties, and then
on “Advanced system settings” on the rightmost column.
– click “Environment Variables . . . ” and click on Path→Edit→New under the
“System variables” and paste the bin path in the blank feld, and then click on
OK button three times.
ProgReference.com
C Cross-platform ◾ 533
– go to Command Prompt (press Win+R, write cmd, and press Enter), write “gcc
– version” and press Enter. If it shows the version number on the screen, then the
GCC is successfully installed.
Step-3: Write C programming codes using any text editor, for example, Notepad, and
save the fle in any location (for example, in Desktop) with a suitable name with extension
.c (for example, example1.c).
Step-4: Open the command prompt in the location where you have saved your fle
example1.c. To do that, go to the location, and in the address bar, write cmd and press
Enter. Or, we can do that using the cd command.
ProgReference.com
534 ◾ Learn Programming with C
Step-5: Write gcc -c example1.c and press Enter. An object fle named example1.o will be
created if there is no syntax error in the program.
Step-6: Write gcc example1.o -o example1.exe and press Enter. An exe fle named exam-
ple1 will be created.
Step-7: We can create exe fle with a single command also. Just write gcc example1.c
and press Enter. An executable fle will be generated as a.exe. If we want to give a name of
our choice to the executable fle, then write gcc -o example1 example1.c and press Enter.
Step-8: To run the program, write a or example1 and press Enter. Te output will be
shown on the command prompt accordingly.
ProgReference.com
C Cross-platform ◾ 535
– frst one (argc = ARGument Count) is the number of arguments that must be a
positive integer, and
– second (argv = ARGument Vector) is the list of command-line arguments. Here,
argv[0] is the program name, and then argv[1], argv[2], . . ., argv[argc-1] is the
arguments that will be written in the command line shell of the operating systems.
2) Command line arguments are given afer the program name in the command line shell.
Example:
Save the above program on desktop as example1.c and compile the program. Now open
the command prompt (Win+cmd and press Enter) and type cd desktop, and press Enter
to change the path to where we save the program. Now write the commands to run the
program. Te following four scenarios may arise:
ProgReference.com
536 ◾ Learn Programming with C
If we want to pass two integers through the command line and add or multiply the two
integers, we need to convert the string values to integers using atoi() function in the main()
program. We can only pass string values to the main() function through command-line
arguments, not integers or other data types. Given below is such an example.
Save the program as add.c and compile the program. Ten, in the command prompt if we
write “add 10 20 and press Enter”, the output will be as follows:
ProgReference.com
C Cross-platform ◾ 537
8.7 LINUX
Linux is an open-source operating system that is freely available to everyone. Hence, it
has become a developer’s programming paradise. Tere are many versions available for
Linux OS. Here, we will explain how to write, compile, and run C programs in WSL Linux
Ubuntu.
Step-1: Open the Linux command-line tool, the Terminal. Login as root using the follow-
ing command and entering your password:
$ sudo su
Step-2: Connect to the internet and enter the following command as root in the Linux ter-
minal to update the resources of the linux system:
# apt-get update
Step-3: Now, enter the following command as root in the Linux terminal and press Enter
to install the GCC compiler:
# apt-get install gcc – y
Step-4: To create and edit text fles right from the Linux terminal, install gedit text editor
using the following command as root in the Linux terminal:
# apt-get install gedit -y
ProgReference.com
538 ◾ Learn Programming with C
Step-5: Afer installing the GCC and gedit packages, write the following command in the
Linux terminal as root and press Enter:
# gedit example1.c
Tis will create and open a fle named example1.c, where you can write and save your C
programming codes.
Step-6: Write the following command in the Linux terminal to compile the program that
will make an executable fle named example1, if there is no error.
# gcc example1.c -o example1
If we write only # gcc example1.c, then an executable fle named a.out will be created.
If the program is not located in the Home folder, we need to specify the appropriate paths
in the command. For example, if the fle is saved on the Desktop, write # cd Desktop/ in the
Terminal and press Enter to change the directory.
Step-5: To run the compiled program, write the following command in the Terminal and
press Enter.
# ./example1 or # ./a.out
ProgReference.com
C Cross-platform ◾ 539
Step-1: Go to www.mathworks.com/matlabcentral/fleexchange/52848-matlab-
support-for-mingw-w64-c-c-compiler.
Download “MATLAB Support for MinGW-w64 C/C++ Compiler”. Now open MATLAB
and browse to this downloaded fle using the current folder browser. Double-click on
this fle to install the MinGW-w64 C/C++ Compiler for MATLAB.
Step-2: Download MinGW-w64 compiler from https://jmeubank.github.io/tdm-gcc/.
ProgReference.com
540 ◾ Learn Programming with C
Install the tdm-gcc in a location (pathname must not contain any space), for example,
C:\TDM-GCC-64.
Step-3: In the MATLAB Command window, run the command:
setenv(‘MW_MINGW_64_LOC’, ‘path’)
for example, setenv(‘MW_MINGW_64_LOC’, ‘C:\TDM-GCC-64’)
Step-4: In the Command window, run the command:
mex -setup
Step-5: Click New→Script and write your C codes in the fle. Now save it as a .c fle in the
current working folder (for example, example1.c in C:\Users\SazzadImran\Desktop).
Use mexFunction() instead of main() as mexFunction() is the entry point for a mex fle.
ProgReference.com
C Cross-platform ◾ 541
Step-6: In the Command window of the MATLAB program, run the command
mex example1.c
and press Enter. A MATLAB executable fle example1.mexw64 will be created in the cur-
rent folder.
Note: When we run the mex fle example1 in the MATLAB command prompt, it will show
nothing. Tis is due to the fact that the functions printf(), scanf(), etc., only works in native
C. For example, printf() function only displays any string or message on standard output
and does not display that on MATLAB command window. To create mex fles that work
on MATLAB command prompt just like a native C program, we need to use diferent mex
functions. However, this is a separate topic and out of scope for discussion in this book.
Generating mex fle (Matlab EXecutable fle) of C program is necessary to call external
C code into diferent Matlab Simulink model.
Step-1: Go to www.mathworks.com/matlabcentral/fleexchange/52848-matlab-support-
for-mingw-w64-c-c-compiler.
ProgReference.com
542 ◾ Learn Programming with C
Download “MATLAB Support for MinGW-w64 C/C++ Compiler”. Now open MATLAB
and browse this downloaded fle using the current folder browser. Double-click on
this fle to install the MinGW-w64 C/C++ Compiler for MATLAB.
Step-2: Download MinGW-w64 compiler from https://jmeubank.github.io/tdm-gcc/.
Install the tdm-gcc in a location (pathname must not contain any space), for example,
C:\TDM-GCC-64.
Step-3: In the MATLAB Command window, run the command
setenv(‘MW_MINGW_64_LOC’, ‘path’)
for example, setenv(‘MW_MINGW_64_LOC’, ‘C:\TDM-GCC-64’)
Step-4: In the Command window, run the command
mex -setup
Step-5: Create a header fle SimpleLib2.h containing prototype of the user-defned func-
tion prototype add() in the current working directory (for example, in C:\Users\
ProgReference.com
C Cross-platform ◾ 543
Step-6: Create a C source fle in the same directory, defne its function, and save the
fle with a .c extension. Use double quotations to include the header fle created in
Step-5. For example, the SimpleLib1.c fle may contain the defnition of the func-
tion add().
Step-7: In the Command window of the MATLAB program, run the following
commands:
(i) Initialize the structure of the S-function:
def = legacy_code(‘initialize’) and press Enter
(ii) Give a name of your choice to the S function:
def.SFunctionName = ‘MySFunction’ and press Enter
iii) For the output function specifcation, use only y and u as parameters:
def.OutputFcnSpec = ‘double y1 = add(double u1, double u2)’ and press
Enter
iv) Add header and source fles:
def.HeaderFiles = {‘SimpleLib2.h’} and press Enter
def.SourceFiles = {‘SimpleLib1.c’} and press Enter
ProgReference.com
544 ◾ Learn Programming with C
Step-8: Create a new Simulink model and save it as MyModel.mdl. To do that, click
New→Simulink Model and then click “Blank Model”. Now click File→Save As . . .,
write MyModel in the “File name:” box, select Simulink Models (*.mdl)’ in “Save as
type:” box and click on Save.
ProgReference.com
C Cross-platform ◾ 545
Download “MATLAB Support for MinGW-w64 C/C++ Compiler”. Now open MATLAB
and browse to this downloaded fle using the current folder browser. Double-click on this
fle to install the MinGW-w64 C/C++ Compiler for Matlab.
Step-2: Download MinGW-w64 compiler from https://jmeubank.github.io/tdm-gcc/.
ProgReference.com
546 ◾ Learn Programming with C
Install the tdm-gcc in a location (pathname must not contain any space), for example, C:\
TDM-GCC-64.
Step-3: In the MATLAB Command window, run the command
setenv(‘MW_MINGW_64_LOC’, ‘path’)
for example, setenv(‘MW_MINGW_64_LOC’, ‘C:\TDM-GCC-64’)
Step-4: In the Command window, run the command
mex -setup
Step-5: Create a header fle containing the user-defned function prototype in the cur-
rent working directory (C:\Users\SazzadImran\Desktop\MatlabCfunction, for example).
For example, the SimpleLib2.h fle may contain a prototype of the function add().
ProgReference.com
C Cross-platform ◾ 547
Step-6: Create a C source fle in the same directory, defne its function, and save the fle
with a .c extension. Use double quotations to include the header fle created in Step-5. For
example, the SimpleLib1.c fle may contain the defnition of the function add().
Step-7: Create a new Simulink model and save it as MyModel.mdl. To do that, click
Home→New→Simulink Model and then click “Blank Model”. Now click File→Save As . . .,
write MyModel in the “File name:” box, select Simulink Models (*.mdl)’ in “Save as type:”
box and click on Save.
Step-8: Add a MATLAB Function block to the model. To do that, click View→ Library
Browser→Simulink→User-Defned Functions and then drag MATLAB Function block to
MyModel. Double-click on the Function block to open MATLAB Function Block Editor
and enter Matlab code that uses the coder.ceval Matlab function to call the C function
add().
Step-9: Connect two Constant blocks to the input ports and a Display block to the
output port of the MATLAB Function Block. For Constant blocks, click View→ Library
Browser→Simulink→Sources and drag two Constant blocks to MyModel. For Display
block, click View→Library Browser→Simulink→Sinks and drag Display block to MyModel.
ProgReference.com
548 ◾ Learn Programming with C
Step-10: Open the Model Confguration Parameters window, and navigate the Simulation
Target pane.
(i) Click “Header fle” in the “Insert custom C code in generated:” tab and enter
#include “SimpleLib2.h”.
(ii) Click “Source fle” in the “Additional build information:” tab and enter SimpleLib1.c.
Now click Apply and then OK.
(iii) If the C source file and the header file are outside the MATLAB current folder
where the MyModel.mdl was saved, click Set Path→Add Folder . . . select the
folder where C source and header files were saved, and then click “Select
Folder”→Save →Close.
Step-11: Save the model and run the simulation. If we input 3 and 4.5 in the two input
Constant blocks, 7.5 appears in the Display output block.
ProgReference.com
C Cross-platform ◾ 549
Download “MATLAB Support for MinGW-w64 C/C++ Compiler”. Now open MATLAB
and browse to this downloaded fle using the current folder browser. Double-click on this
fle to install the MinGW-w64 C/C++ Compiler for Matlab.
Step-2: Download MinGW-w64 compiler from https://jmeubank.github.io/tdm-gcc/.
ProgReference.com
550 ◾ Learn Programming with C
Install the tdm-gcc in a location (pathname must not contain any space), for example, C:\
TDM-GCC-64.
Step-3: In the MATLAB Command window, run the command
setenv(‘MW_MINGW_64_LOC’, ‘path’)
for example, setenv(‘MW_MINGW_64_LOC’, ‘C:\TDM-GCC-64’)
Step-4: In the Command window, run the command
mex -setup
Step-5: Create a header fle containing the user-defned function prototype in the cur-
rent working directory (in C:\Users\SazzadImran\Desktop\MatlabCcaller for example).
For example, the SimpleLib2.h fle may contain a prototype of the function add().
Step-6: Create a C source fle in the same directory, defne its function, and save the fle
with a .c extension. Use double quotations to include the header fle created in Step-2. For
example, the SimpleLib1.c fle may contain the defnition of the function add().
Step-7: Create a new Simulink model and save it as MyModel.mdl. To do that click
New→Simulink Model and then click “Blank Model”. Now click File→Save As . . ., write
MyModel in the “File name:” box, select Simulink Models (*.mdl)’ in “Save as type:” box
and click on Save.
ProgReference.com
C Cross-platform ◾ 551
Step-8: Open the Model Confguration Parameters window, and navigate to the
Simulation Target pane.
(i) Click the Header fle under “Insert custom C code in generated:” bar and enter the
name of the header fle with #include “SimpleLib2.h”.
(ii) If the model and the header fles are stored in diferent folders, click “Include direc-
tories” under “Additional build information” and list the path of the header fles in
the text box.
(iii) Click Source fles under “Additional build information:” and enter SimpleLib1.c.
If the model and the source fle are in diferent folders, enter the source fle’s path
address before the source fle name and click OK.
ProgReference.com
552 ◾ Learn Programming with C
Step-12: Save the model and run the simulation. If we input 3 and 4.5 in the two input
Constant blocks, 7.5 appears in the Display output block.
Install Python in any location (C:\Program Files (x86)\Python38–32 for example). Don’t
forget to check “Add python.exe to PATH” and “Install launcher for all users” during
installation of the Python program. We choose 32-bit version as we have GCC from 32-bit-
MinGW to create *.so shared object fle.
Now, download and install any C compiler (for example, CodeBlocks with 32-bit MinGW
from www.codeblocks.org/downloads/binaries/) on your PC.
ProgReference.com
C Cross-platform ◾ 553
Step-1: Open CodeBlocks C compiler. Now, click File→New→ “Empty fle”. An empty text
fle will open. Now, click “File→Save fle as . . . “, write SimpleLib in the “File name:” box,
select a folder of your choice (for example, C:\Users\SazzadImran\Desktop\ CfromPython),
and click Save.
Step-2: Defne one or more of your C functions in the fle except main(). For example,
we have defned functions add() and subtract(), and save the fle.
A shared object fle SimpleLib.so is created in the destination folder. We can give any name of
our choice to the shared object fle (*.so). It does not necessarily be the same as that of the *.c fle.
ProgReference.com
554 ◾ Learn Programming with C
Step-4: Click on Windows, write IDLE, and click on IDLE (Python 3.8 32-bit) to open
Python shell. Click File→New File and save it with any name (for example, example1) as
Python fles in any location (may be in the same folder where we saved *.so fle, C:\Users\
SazzadImran\Desktop\CfromPython).
Step-4: Now write your Python codes in example1.py fle. In the coding, we must do the
following to use any function defned in the *.c fle:
ProgReference.com
C Cross-platform ◾ 555
(vi) Now click Run→“Run Module” to run the program. Te output will be as follows”
We can also do the same task using dynamic link library (*.dll) created in Section 8.1.2 in
folder C:\Users\SazzadImran\Desktop\SimpleLib\ bin\Debug.
To call C functions using DLL fle, write full path of the location of SimpleLib.dll as it is in
separate location from that of example1.py. Also, we can use WinDLL() function to defne
the Python object. Te Python fle will look like as follows
multiple languages gives anyone a competitive edge over others in the job market. Tis sec-
tion highlights some benefts and tips on efective switching from one language to another.
Many programmers might think that mastering one language is enough. But, in real-
ity, many coders practice switching programming languages to improve their professional
skills and get their desired job. If we know the reason behind our switching language, we
can switch and learn the right language for us.
When choosing a language to learn, always pay attention to the following six points:
Most experts argue that frst you need to master a fundamental language. Afer that, you
can quickly learn another language of your needs. Take into account the following simple
tips to master another language of your choice:
ProgReference.com
C Cross-platform ◾ 557
To be an expert developer, you need to learn new programming languages mastering their
principles and algorithms. Tere are no alternatives other than improving your program-
ming skills based on recent market trends to be competitive in the job market.
(1) Write new codes in C++ and link these with existing C codes.
(2) Develop codes in C and then modify them so that the codes are compatible with
C++ compiler.
(3) Start using C++ language features to improve programming style without initially
using OOP features.
C programmers need to throw away and forget some of the C concepts they are familiar
with and get used to C++ or OOP features. Some of such C concepts are as follows:
(1) Tink of everything as objects. Create a class and create as many functions as you
need inside it.
(2) Instead of defning lots of global functions, make them member functions of a class.
(3) Group similar functions of diferent types in a template.
(4) Tere is no need to use a prefx in the identifers to avoid name conficts, as they can
be put in a namespace.
(5) We may use references and derived classes instead of so many pointers and type casts.
C and C# are two completely diferent programming languages. Tere are more diferences
than similarities between these two languages. C# adds garbage collection, bound check-
ing, uninitialized variable checking, and type checking capabilities. Having a background
in C may help learn C# as many of the syntaxes are similar, but anyone can learn C#
quickly without knowing anything about C.
ProgReference.com
CHAPTER 9
C Projects
PROJECT-1
Create a student management system that can store all information of all students, teach-
ers, and staff of your department in the form of structures. The following information
needs to be stored for each student:
Name, Semester, Class Roll, Exam Roll, Course Name and Grade Point Earned in the
Current Semester, GPA Earned in Previous Semesters, CGPA.
Employ files as a database to conduct file handling activities such as add, search, change,
and remove entries.
PROJECT-2
Create a simple address book that automatically generates an external file to permanently
store the user’s data. The user’s data will be Name, Phone Number, E-mail ID, and Address.
Keep the option to add, search, edit, and delete data from the record.
PROJECT-3
Create a simple online mini voting system that securely enables organizations to conduct
votes and elections. In the voting system, users can enter their preferences, total votes, and
leading candidates can be calculated. The voting system can identify a legitimate voter, and
one voter can vote only once.
PROJECT-4
Create a Tic-Tac-Toe game in the C programming language using 2D arrays. It is a two-person
game where each player alternately marks squares in a 3×3 grid with X or O. The winner is the
player who successfully places his three markers in a horizontal, vertical, or diagonal row.
ProgReference.com
C Projects ◾ 559
PROJECT-5
Create a simple library management system that manages and preserves book data. Te
book data will be Name, Authors, Publisher, and Year. Both students and library adminis-
trators can use the system to keep track of all the books available in the library. Te library
administrators can search, add, delete, or issue books and the students can only search and
make a request to issue books. As one particular student can keep three books at a time for
a maximum of one month, the system will check that before issuing any book to a student.
PROJECT-6
Create a simple bus reservation system that can book bus tickets in advance. Te user can
check the bus schedule, book tickets, cancel a reservation, and check the bus status. When
purchasing tickets, the user must enter the bus number, seat number, the number of tick-
ets, and passengers’ names.
PROJECT-7
Create a simple bank management system that can create a new account and remove an
existing account. It can also update the information of an existing account (name, contact
number, and address) and check the details of an existing account (name, account number,
total debit, credit and current balance). Te system can view the existing customers’ lists
and manage each account’s transactions (debit and credit).
PROJECT-8
Create an employee management system that can store all information of all staf of
an organization in the form of structures. Name, Designation, Contact Number, Job
Responsibility, and Monthly Salary need to be stored for each staf. Employ fles as a data-
base to conduct fle-handling activities such as add, search, modify, and remove entries.
PROJECT-9
Create a student attendance management system that will take and store the daily atten-
dance of each student in a particular subject. Te system will show Name, Class Roll, Total
Class Taken, Total Class Attended, Percentage and Marks for Attendance for each student.
Employ fles as a database to conduct fle-handling activities such as add, search, modify,
and remove entries.
PROJECT-10
Create a simple quiz game that will ask a number of questions to the user. If the user can
give a correct answer, a cash prize will be awarded for each correct answer, and a fne
will be imposed for each wrong answer. Questions may be asked randomly from science,
movies, sports, geography, etc. We can divide the game into two rounds. Te contestant
will move to the “advanced round” only if he can get qualifed in the preliminary round.
Te questions will be more challenging in the “advanced round”, and prize money and
fne will be higher.
ProgReference.com
560 ◾ Learn Programming with C
PROJECT-10
Create a simple snake game in which the snake’s food is provided in diferent coordinates
of the screen to eat. When the snake eats the food, its length is automatically increased by
one element, and the score is increased by 10 points.
PROJECT-11
Create a simple cricket score display system that will display the following information
on the screen:
For batsman- Name, Runs, Balls, 4s, 6s, Out/Not-Out, Strike-rate etc.
For bowler- Name, Over, Wide, No-ball, Wickets etc.
Date and Time of the game, Toss, Name of the teams, Target, Current and required run
rate, Remaining wickets etc.
PROJECT-12
Create a simple cash-fow manager that allows users to keep track of their daily cash infow
and outfow. It will show total income, categorize expenses, and balance each month. It
also has the provision to store data in a fle for each month and display the yearly data.
PROJECT-13
Create a simple ATM machine management system that allows users to withdraw cash
afer entering the PIN and amount to be withdrawn. Afer successful withdrawal, the
amount will be debited from their bank account. Te user can also check his current bal-
ance using the system.
PROJECT-14
Create a simple matrix calculator that allows users to add, subtract, or multiply two matri-
ces. It can also perform division and transpose operations. First, it checks the matrices’ size
and then performs the operation only if the size is allowed.
PROJECT-15
Create a modern periodic table that accurately stores the name, symbol, atomic number,
atomic weight, and other properties of the chemical elements. Users can search by name or
any properties of the elements.
PROJECT-16
Design a CE amplifer with voltage divider bias of a given gain. Te C project will calcu-
late and provide values of all the elements (resistors, capacitors, voltage source, etc.) needed
to get the output gain.
PROJECT-17
Develop a vaccine registration portal that verifes users through NID or BRN num-
bers and checks their age and status. Te portal gives a date, time, and place to receive a
ProgReference.com
C Projects ◾ 561
particular vaccine based on the information. Te portal also shows the list of people with
their NID or BRN numbers who have already received vaccines.
PROJECT-18
Develop a password management system used by the cyber cafes and computer centers
to keep a record of the clients. Clients frst need to sign-up to use a computer there. Te
signed-up users need to log in with their valid credentials (user name and password) to
use a computer. Te system also maintains a database that stores all the users’ data (name,
contact number, user name, password, date and time of use) and shows a particular user’s
information on demand.
PROJECT-19
Create a monthly calendar with days and dates. It shows the list of holidays and the sched-
ule of events of a particular user. Users can edit, add, or delete their events as well. Te
calendar also gives reminders 24 hours and 10 minutes before the occurrence of each event.
PROJECT-20
Create a medical store management system that shows the list of all available medicines
in the store. Unit price, packet price, and name of the pharmaceutical company for each
drug are also available. Users can search for any medication by name or by indication.
PROJECT-21
Develop a hospital management system that adds new patient’s records (name, age, sex,
disease description, and referred room number) and searches, edits, or deletes patient’s
records. Users can list patient’s records by names (alphabetic order), emergency patients,
OPD patients, or dates.
PROJECT-22
Develop a telephone billing system that shows the current month’s telephone billing
records (customer name, phone number, and amount to be paid). Te system can add new
records and search, modify, and delete old records.
ProgReference.com
ProgReference.com
Index
0–9 break, 7, 53, 54, 55, 83, 141, 143, 144, 147, 179, 319
#elif, 440 builder, 539, 541
#else, 440 built-in, 4, 37, 40, 43, 122, 273, 475
#endif, 440 bus reservation, 559
#if, 440
2D array, 153, 154, 558
2’s complement, 179, 184, 214 C
C#, 2, 3, 557
A C++, 2, 3, 529, 542, 545, 549, 557
calculator, 79, 83, 89, 98, 149, 560
actual, 218, 298
calendar, 497, 561
addition, 8, 218, 256, 257, 260, 261, 263, 265, 266,
caller, 296, 539, 549, 551
342, 434
calloc ( ), 156, 212, 213, 216
address book, 558
car, 477, 509, 511, 512, 513, 514
allocation, 37, 156, 308, 428, 433
case, 53, 54, 83, 142, 144
alphabet, 27, 59, 60, 149, 216, 561
cash-flow manager, 560
animated, 500, 514
casting, 11, 42
annual, 99, 376, 435, 448, 475
C caller, 539, 549, 551
append, 155, 168, 210, 438, 443, 444, 469, 475
CE amplifier, 560
arc ( ), 491, 502, 510, 512
C function, 217, 515, 519, 539, 545, 547, 551, 553, 555
array element, 152, 153, 157, 158, 160, 177, 231, 236,
char, 10, 22, 23, 29, 30
252, 341, 392, 466
circle, 19, 45, 475, 480, 482, 487, 489, 507, 513
ascending, 215, 247, 299, 391, 392, 394, 465, 466, 468
circle ( ), 439, 481, 482, 488, 506, 507, 510, 511, 512
ascii, 25, 26, 34, 45, 209
circular, 305, 306, 328, 433, 436
ATM machine, 560
circular linked list, 305, 306, 328, 433, 436
atoi ( ), 536
circumference, 19, 45, 475
attendance, 353, 354, 434, 559
class, 354, 360, 434, 557, 559
attendance management, 559
cleardevice ( ), 478, 486, 497, 502, 508, 511
average, 45, 91, 150, 160, 161, 214, 361, 372, 374, 434
clock, 496, 514
clock ( ), 478
B closegraph ( ), 477, 482, 484, 487, 490, 495, 509, 513
clrscr ( ), 478, 524
background, 478, 484, 485, 486, 487, 489, 499, 504,
codeblocks, 3, 5, 480, 516, 519, 531, 532, 552
513, 557
command, 526, 531, 533, 534, 535, 540, 553
bank management, 559
command line, 531, 534, 535, 536, 537
bar, 480, 482, 513, 527, 533, 551
command prompt, 526, 533, 534, 535, 536, 541, 553
bar ( ), 481, 482
command window, 439, 540, 541, 542, 543, 546, 550
binary, 43, 179, 183, 214, 342, 433, 437, 439, 472,
comment, 4, 35, 41, 482
473, 474
compatibility, 253, 299
binary file, 437, 474
compilation, 39, 41, 145, 148, 439, 515, 519, 522
binary tree, 433
compilation error, 39, 148
563
ProgReference.com
564 ◾ Index
ProgReference.com
Index ◾ 565
G L
game, 558, 559, 560 Lagrange, 124, 216
gate, 338, 433 largest, 151, 169, 172, 214, 252, 302
GCC compiler, 516, 520, 532, 537 length, 155, 162, 163, 214, 274, 283, 286
GCD, 241, 243, 245, 299 library function, 4, 21, 43, 106, 155, 214, 217, 220,
gcdf ( ), 243, 244, 246 222, 224, 293, 478, 484
getchar ( ), 202, 203, 309, 311 library management, 559
getche ( ), 82, 84, 126, 128, 131, 193, 195, 348 line ( ), 494, 506, 507, 511, 512
getmaxx ( ), 477, 491, 492, 502, 503, 506, 508, linear linked list, 396, 411, 435
510, 511 linked list, 303, 304, 305, 306, 315, 317, 321, 324, 325,
getmaxy ( ), 477, 491, 492, 502, 508, 511 404, 406, 421, 432, 433
gets ( ), 155, 163, 164, 166, 168, 182, 198, 273, 282, linking, 38, 39, 515
307, 442, 444 linking error, 39
gettime ( ), 497, 498 linux, 525, 537, 538
global, 219, 297, 298, 557 logical, 8, 9, 34, 38, 39, 51, 143, 214, 431
goto, 7, 55, 143 logical error, 39, 51
grade, 308, 376, 391, 435, 448, 459, 475, 558 long, 7, 11, 31, 42, 43, 61, 98, 166, 217, 239, 241
graphics.h, 477, 480, 481, 486, 491, 497, 506, 510 loop, 49, 51, 52, 53, 107, 123, 130
loop control, 143
H
M
harmonic, 64, 149
machine, 1, 2, 3, 37, 38, 560
header file, 4, 5, 12, 21, 40, 56, 82, 106, 110, 121, 128,
main ( ), 4, 12, 15, 39, 40, 445, 534, 536,
155, 156, 162, 217, 439, 441, 477, 481, 486, 506,
540, 553
515, 517, 521, 524, 542, 546, 548, 551
malloc ( ), 156, 212, 213, 310, 316, 318, 333
heap, 431, 433
management, 437, 558, 559, 560, 561
hospital, 561
manager, 529, 560
hospital management, 561
math.h, 21, 74, 110, 121, 225, 234, 290, 368
matlab, 539, 540, 541, 547, 551
I matrices, 253, 261, 267, 299, 560
matrix, 153, 184, 188, 215, 253, 257, 299, 560
identifier, 7, 27, 28, 29, 35, 41, 43, 213, 403, 418 matrix calculator, 560
if statement, 46, 47, 70, 74, 75, 90, 130, 139, 144 mean ( ), 233, 234, 236
increment, 8, 42, 44, 49, 52 medical store, 561
index ( ), 277, 282, 283, 284 memory allocation, 37, 156, 308, 433
infinite, loop, 51, 144, 149 mex file, 541
initgraph ( ), 477, 481, 482, 484, 488, 491, 494, 498, mexFunction ( ), 540
503, 511 middle-level, 37
initialization, 41, 49, 50, 51, 52, 63, 128, 144, 146, mingw-w64, 539, 541, 542, 545, 549
149, 188 modifier, 11, 42
insert ( ), 270, 272, 273, 304, 331, 336, 413, 415, 419, modulus, 8, 41, 42, 231, 508
424, 436 Monte Carlo, 108, 150
integral, 136, 140, 150, 302, 432 monthly calendar, 561
interactively, 64, 104, 149, 153, 226, 396, 411, 435 moving, 507, 508, 509, 512, 514
interpolation, 124, 150 multidimensional, 154, 214
interpreter, 38 multiplication, 8, 20, 62, 63, 75, 149, 214, 223, 240,
267, 342, 352, 434
K
N
kbhit ( ), 478, 497, 498, 502, 503
key feature, 37 near pointer, 212
keyword, 3, 7, 28, 35, 39, 43, 143, 145, 217, 219, negative, 56, 57, 149, 155
297, 432 nested, 47, 48, 51, 143, 302, 427, 431
ProgReference.com
566 ◾ Index
nested if, 47, 48 puts ( ), 155, 169, 217, 439, 467, 469, 471
nested structure, 302, 427, 431 Python, 2, 3, 525, 552, 554
newline \n, 75
Newton-Raphson, 112, 116, 150
Q
nonlinear, 112, 117, 150, 303, 433
nosound ( ), 497, 499 quadratic, 71, 149
NULL pointer, 213 quiz game, 559
O R
object, 2, 3, 7, 38, 39, 301, 474, 477, 498, 515, 519, 534, rain, 505, 508, 514
552, 554, 557 rainbow, 490, 513
object code, 2, 38 rand_max, 109, 111
odd, 57, 58, 139, 149, 299 rand ( ), 105, 106, 107, 110, 111, 182, 506, 508
online mini voting, 558 random, 45, 104, 106, 107, 111, 150, 223, 474, 508
operand, 42, 43, 48 random access, 474
operating system, 1, 2, 5, 37, 439, 515, 535, 537, 557 rectangle ( ), 494, 495, 497, 500
operator, 8, 9, 10, 12, 33, 39, 41, 42, 43, 48, 49, 57, 79, recursive, 237, 240, 241, 245, 299
143, 156, 214, 231, 301, 302, 307, 431, 554, 557 register, 7, 39, 198, 219, 296, 426
ordinary, 131, 150 remainder, 8, 18, 42, 58, 70, 78, 231
outtextxy ( ), 477, 483, 484, 486, 500, 506, 508 reserved, 7, 14, 39, 43
overloading, 296, 557 reverse, 151, 155, 215, 300, 321, 327
run-time error, 39, 43
P
S
passing, 218, 298
password, 537, 561 Secant, 117, 122, 150
password management, 561 self-referential, 431, 432
pattern, 477, 478, 479, 495, 503, 504, 556 semantic, 39
periodic table, 560 sequence, 10, 42, 46, 143, 173, 177, 214, 433
PI, 10, 19, 20, 108, 111, 439 sequential access, 474
piety, 85, 89, 91, 150 series, 64, 149, 155, 300, 303, 304
pointer, 152, 156, 157, 163, 165, 211, 212, 213, 214, setbkcolor ( ), 478, 486, 487, 488, 489
218, 219, 277, 282, 298, 302, 305, 306, 310, 320, setcolor ( ), 478, 483, 484, 486, 487, 488, 489, 491,
403, 419, 431, 432, 438, 444, 469, 474, 477, 557 492, 497, 498, 502, 503
pointer access, 213 setfillstyle ( ), 478, 494, 495, 502, 503, 504
pointer operator, 302, 404, 420 settextstyle ( ), 478, 486, 487, 497, 500
pointer variable, 152, 310, 311, 318, 319, 325, 326, S-function, 539, 541, 543, 545
333, 334, 335, 404, 419 short, 7, 11, 39, 42
polynomial, 287, 291, 292, 299 signed, 7, 11, 29, 30, 31, 42
positive, 56, 57, 76, 149, 155, 223, 535 significance, 38
pow ( ), 21, 289, 290, 293 Simpson, 136, 139, 150
power ( ), 222, 223, 224 sin ( ), 113, 115
preprocessor, 12, 21, 110, 115, 121, 188, 217, 234, 260, single statement, 42, 48
298, 439, 441 singly, 305, 315, 433, 435, 436
prime ( ), 227, 228, 230, 231 singly linked list, 305, 315, 433, 435
product, 16, 17, 79, 253, 264 sizeof ( ), 10, 23, 36, 43, 156, 159, 309, 310, 318,
program algorithm, 38 418, 419
program flowchart, 38 smallest, 151, 169, 172, 214, 252
program fragment, 142, 145, 146, 147, 148, 149 smiley, 500, 504, 514
project, 5, 516, 519, 530, 558 snake game, 560
ProgReference.com
Index ◾ 567
ProgReference.com