Computer Programming Book Final-Version-2
Computer Programming Book Final-Version-2
DCSA-1303
Computer Programming
DCSA-1303
Editor
Professor Dr. K.M. Rezanur Rahman
School of Science and Technology
Bangladesh Open University
Overall Supervision
Professor Dr. K.M. Rezanur Rahman
School of Science and Technology
Bangladesh Open University
Published by
Publishing, Printing and Distribution Division
Bangladesh Open University
Gazipur-1705.
Cover Design
Monirul Islam
Graphics
Abdul Malek
Computer Compose
Mohammad Mamunur Rashid
Printed by
M/S Monirampur Printing Press
76/A, Naya Paltan, Dhaka.
ISBN: 984-34-4003-X
Unit 2 13
Keyword, Variable and Data Type ………………………..………………….. 13
Lesson-1: Keyword, and Identifier ……. ……………………………………….. 14
Lesson-2: Variable …………………………………………………………………….. 16
Lesson-3: Constant …………………………………………..………………….. 20
Lesson-4: Data Type …………………………………..……………................... 22
Unit 3 26
Operators ……………………………………………………………………...... 26
Lesson-1: Operator Part -1...……..………………………………………............ 27
Lesson-2: Operator Part-2 …………………………………….………………… 30
Unit 4 33
Decision Making and Branching …………………………………….………... 33
Lesson-1: Basic Concept on Decision Making Statements ……………………... 34
Lesson-2: Decision Making Using If And If-Else Statements ………………...... 36
Lesson-3: Decision Making Using Nesting Of If-Else Statements ……………... 44
Lesson-4: Decision Making Using Else-If Ladder Statements …………………. 50
Lesson-5: Decision Making Using Switch Case Statement …………………….. 56
Unit 5 60
Decision Making and Looping ………………………………………………… 60
Lesson-1: Basic Concept On Loop Control Structures …………………………. 61
Lesson-2: Understanding While Loop ………………………………………….. 64
Lesson-3: Understanding Do-While Loop ……………………………………… 68
Lesson-4: Understanding For Loop …………………………………………...... 72
Lesson-5: Understanding Break And Continue Statements………….………….. 79
Lesson-6: Understanding goto Statement …………………………..................... 87
Unit 6 92
Arrays and Strings ……………………………………………………………... 92
Lesson-1: Familiar With Arrays………………………………............................ 93
Lesson-2: Familiar with One Dimensional Array ……………………………… 96
Lesson-3: Familiar with Two Dimensional Arrays …………………………….. 104
Lesson-4: Introduction to Strings ……………………………………………..... 115
Lesson-5: Understanding String Handling Functions …………………............... 122
Unit 7 129
Functions ……………………………………………………………………….. 129
Lesson-1: Introduction to C functions ………………………………………….. 130
Lesson-2: Function Prototype and Definition …………………………………... 133
Lesson-3: Categories of User Defined Functions ………………………………. 139
Lesson-4: Function With No Arguments and No Return Value ………………... 140
Lesson-5: Function With No Arguments and Return Value ……………………. 143
Lesson-6: Function With Arguments And No Return Value …………………… 146
Lesson-7: Functions With Arguments And Return Value ……………………… 150
Lesson-8: Recursive Function …………………………………………………... 154
Lesson-9: Uses of Local and Global Variables in Function …………………….. 159
Unit 8 170
Structures and Unions …………………………………………………………. 170
Lesson-1: Introduction to C Structures …………………………………………. 171
Lesson-2: Structures Initialization ……………………………………………… 177
Unit 9 181
Pointers ………………………………………………………………………………….. 181
Lesson-1: Introduction to C Pointers ……………………………………………. 182
Lesson-2: Pointer Declaration and Initialization ………………………………… 185
Lesson-3: Accessing Variable and Pointer Expression ………………………….. 188
Units True / False and MCQ Answer ………………………………………………… 191
Preface to the 2nd Edition
Computers are used to automate methods for processing information. Apart from information
processing, computers play ever increasing role in many other areas of modern life.
Programming is a vital element in efficient utilization of a computer. The present volume is
written according to the revised syllabus of the “Computer Programming” for distance learners
of DCSA Program. The high level programming language “C” has been described in the book
to familiar a learner with C language and design a program. The basic aspects of computer
programming are presented. Data types, Operator, Loop, array are described.
The book is split into 9 units. Important topics such as structures, union and pointers are
described in unit 8 and unit 9 respectively. At the end of the each lesson, there is activity, study
skill, assignment, exercise and hands on practice for preparation of examination. I am confirm
that the book is written in a simple and understandable manner and lessons are organized well,
so that learners can adopt and familiar easily while reading the book. Hope that the book is
useful for learners, teachers, educators and all concerns.
Any suggestion or feedback for further improvement of the book would be highly appreciated.
Amran Hossain
Mohammad Mamunur Rashid
School of Science and Technology DCSA Program
Timeframe
How long ?
Unit Structure
Lesson- 1 : Introduction to Computer Programming
Lesson- 2 : Algorithm and Flowchart
Lesson- 3 : Overview of C language
Lesson- 4 : Basic structure of C
1
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Hope all of you are conscious with the term language. Language is a system of communication between
two persons. Observe, In order to communicate with each other, we use languages like Bengali, English,
Hindi, Urdu, French etc. We have different language around us in our real life to communicate with
each other. However, human beings cannot speak or write in computer language, and since
computers cannot speak or write in human language, so an intermediate language had to be devised
(design) to allow people to communicate with the computers. These intermediate languages, known
as Computer Language, that allow a computer programmer to direct the activities of the computer.
COMPUTER PROGRAM
Let us first recall computer and what they do.
A computer is an electronic device or machine used for processing data to deliver required
information.
A computer is a programmable electronic machine that receives input, stores and process data,
and provides output in a useful format.
Computer has no intelligence of its own to perform any task.
We also know that hardware (Computer) is all of the physical equipments or components which
are visible and touchable. A computer without a computer program (software) is just a dump
box; it is programs that make computers active. The usefulness of the computer depends on the
programs that are written to manipulate it.
As you know computer cannot do anything on its own and has to be guided (directed) by the user. In
order to do any specific job you have to give a sequence of instructions to the computer. This set of
instructions is called a computer program. Computer program is a sequence of instructions written in a
Computer Language to perform a specified task by the computer. Computer Programming is the process
of developing and implementing various sets of instructions to enable a computer to do a certain task.
2
School of Science and Technology DCSA Program
WHY PROGRAMMING?
Hope all of us know that computer can neither think nor make any judgments on its own; it can't do
anything by themselves. They do exactly what you tell them to do: no more, no less unlike human
beings. Suppose, if someone asks you, “What is the sum of 2+2?” or “add 2+2=?” or just, “2+2=?” you
understand anyway but computer is different. Instructions to the computer should be explicitly stated.
So we can say that computer needs a program to tell it what to do.
PROGRAMMING LANGUAGE
In earlier section we have learnt about computer language, computer program. In this section we will
learn about programming language. We have different language around us in our real life to
communicate with each other. What do you think if a Bengali person talks to an English man in Bengali
language who does not know Bengali, can they communicate with each other? I am sure all of you will
say no. In the same way if you tell the computer do this work or koro ei kaj ta, computer will not
understand anything because computer understand only its own language (0 and 1). That’s why need
programming language. To build programs, people use languages which are similar to human languages
that are translated into machine code, which computers understand. A Programming Language
(Computer) is composed of a set of characters, words and rules of the language that can be used to
perform specific tasks by writing a computer program. Examples of some of the programming
languages are BASIC, FORT RAN, COBOL, C, C++ etc.
There are three types of programming language according to their levels and they are as follows:
MACHINE LANGUAGE
Machine language is the only language that is directly understood by the computer. It is
written in binary form that is 0 and1.
It is most efficient for the computer as the instructions are directly executed.
It is not an easy language to learn because of its complexity as it consists of 1's and 0's.
Program instruction may look like this: 1011000111101
Machine language is hardware dependent. A program written for one computer might not run
on other computers with different hardware configuration. It is also difficult to debug the
program written in this language.
The only advantage is that program of machine language run very fast because no translation
program is required for the CPU.
It is considered to the first generation language.
The following program is an example of a machine language program for adding two numbers.
3
School of Science and Technology DCSA Program
ASSEMBLY LANGUAGE
In assembly language, the operation code is expressed as a combination of letters rather than
binary numbers, sometimes called mnemonics. This allows the programmer to remember
the operations codes easily than when expressed strictly as binary numbers.
Translator program (called Assembler) translate the programs written in assembly language
into machine language for execution by the computer.
It is relatively easier to correct errors and modify program instructions.
Assembly Language has almost the same efficiency of execution as the machine language.
Assembly language is machine dependent. A program written for one computer might not run
on other computers with different hardware configuration.
It is considered to be a second generation language.
Example of an assembly language program for adding two numbers as follows:
4
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Define algorithm.
Write algorithm.
Define flowchart.
Explain Flowchart symbols & their meanings.
Draw flowchart.
ALGORITHM
From programming point of view,
An algorithm is a step by step procedure (technique) for solving any problem.
An algorithm is an effective method expressed as a finite set of well defined instructions.
Refers to the logic of a program and step by step description of how to arrive at the solution of
a given problem.
For example, find the sum of two numbers.
Step 1: Start
Step 2: Input A
Step 3: Input B
Step 4: Calculate C = A + B
Step 5: Output C
Step 6: Stop
Another example, Consider the following instructions that you need to boiling water.
Step 1: Start
Step 2: Take water in a kettle.
Step 3: Place the kettle on the oven.
Step 4: Turn the oven on.
Step 5: Check whether water is boiled
Step 6: Turn the oven off
Step 7: Stop
FLOWCHART
A flowchart is a graphical/ pictorial representation of an algorithm. a flowchart is most helpful
in planning, designing, and structuring a program.
Uses symbols (boxes of different shapes) that have standardized meanings to denote different
types of instructions.
5
School of Science and Technology DCSA Program
For example
Advantages of Flowchart
Efficient coding
Systematic debugging
Systematic testing
Proper documentation
6
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Write history of C.
Explain the importance of C.
Write application of C.
Define compiler and interpreter.
BRIEF HISTORY OF C
C is a fast, general-purpose, platform independent, high-level programming language that
evolved by “Dennis Ritchie” at Bell Laboratories from two previous programming languages,
BCPL and B on DEC PDP-11 machine in 1972. Initially, C widely known as the development
language of the UNIX operating system but today all new major operating systems are written
in C and/or C++.
Evolved over the years
1972 – C invented
1978 – The C Programming Language published; first specification of language
1989 – C89 standard (known as ANSI C or Standard C)
1990 – ANSI C adopted by ISO, known as C90 and 1999 – C99 standard
2007 – work on new C standard C1X announced
WHY C
C is a powerful and flexible language.
C is the most widely used and popular System Programming Language.
C has rich set of built-in functions and support variety of data types & operators.
C is highly portable (Machine independent) and it is static (compiled), typed, structured and
imperative.
C has ability to extend itself and it is stable (the language doesn’t change much).
C is quick running (code written in c is efficient & fast).
C is the basis for many other languages (C++, C#, Java, Perl etc).
C is small (only 32 keywords) and it is a Programmers Language.
APPLICATIONS OF C
Systems Programming: e.g., compilers and interpreters
Operating System: e.g., Linux ,Unix
Microcontrollers: automobiles and airplanes
Embedded Processors: phones, portable electronics etc.
Database systems and DSP Processors: digital audio and TV systems.
7
School of Science and Technology DCSA Program
Though Environment Setup is not the part of Programming Language, but it is the first step to be
followed before setting on to write a program. Thus, we need to have the required software setup, i.e.,
installation on our PC which will be used to write computer programs, compile, and execute them. Once
C compiler is installed in your machine, you can create, compile and execute C programs. You need the
following two software tools available on your computer to set up your environment for starting C
programming language,
(i) Text Editor / Code editor and
(ii) C Compiler.
You are able to write program in Notepad but, notepad and the other editors don't provide you with the
right tools to do software development. That’s why code editor or an IDE is better option instead of
notepad. Code editor is a piece of software that you can use to write your code and it will behave like
the tool you need to develop software, for example, coloring keywords, display the line numbers that's
important for debugging, allow for multiple text manipulation and add a file explorer or project
explorer to select the files you need to work on. Beside, a compiler is necessary to compile the program
which converts your program (source code) into a language understandable by a computer. So before
proceeding, make sure you have C compiler available at your computer. There are many compilers
available on the internet and sold commercially in stores or online. Most compilers come with a built-
in code editor that can be used to enter source code; however, some don't.
When you save a source file, you must give it a name. The name should describe what
the program does. In addition, when you save C program source files, give the file a
.C extension.
8
School of Science and Technology DCSA Program
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
Let us look at a simple program (code) that will print a Line of Text
/ * first program in C */
#include <stdio.h>
int main()
{
printf( "Welcome to C" );
return 0;
}
Output
Welcome to C
9
School of Science and Technology DCSA Program
terminator; each individual statement must be ended with a semicolon (;). This is very important
missing of a semicolon (;) at the end of statement is a syntax error and compiler will report an error
during compilation.
return 0;
A way to exit a function., in this case terminates the main() function and returns the value 0
Don’t forget to have a main function, or mistype the name, the compiler will give you
an error.
INPUT/ OUTPUT STATEMENT
In this section we will learn how a computer reads data (input) and prints data (output). Two
commonly used functions for I/O (Input/Output) are scanf() and printf().
scanf() function
scanf() function reads one or more values from an input device, and stores them into variables specified
by the programmer. In scanf() syntax a special character format specifier is used to specify the data type
of value.
In C programming language, scanf() function is used to read character, string, numeric data from
keyboard.
The format specifier %d is used in scanf() statement. So that, the value entered is received as an
integer and %s for string.
Ampersand (&) is used before variable name in scanf() statement as &number.
Syntax
scanf("format specifiers",&value1,&value2,.....);
Example
int a;
float b;
char c;
scanf("%d%f %c ",&a,&b,&c);
In the above example scanf() is able to read three input values ( integer, float value and character) and
those are stored in a, b and c variable respectively.
Format specifier:
Format specifier Type of value
%d Integer
%f Float
%lf Double
%c Single character
%s String
%u Unsigned int
%ld Long int
%lf Long double
printf() function
Printf is a predefined function in "stdio.h" header file, by using this function, we can display the data or
user defined message on monitor.
In C programming language, printf() function is used to display the “character, string, float, integer,
octal and hexadecimal values” onto the output screen. While working with printf(), it can take any
number of arguments but first argument must be within the double cotes (" ") and every argument
should separated with comma ( , ) Within the double cotes, whatever we pass, it prints same.
10
School of Science and Technology DCSA Program
We use printf() function with %d format specifier to display the value of an integer variable.
Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
To create a newline,we use “\n” in C printf() statement.
Syntax
printf("user defined message");
prinf("Format specifers",value1,value2,..);
Statements can be either simple or compound. A simple statement performs a single action. Examples
of simple statements are as follows:
printf( "Welcome to C" );
int i = 12;
Compound statement does several actions in sequence. A compound statement is composed of simple
statements enclosed within a pair of braces {}. The following is an example of compound statements in
C.
{
pi= 3.141593;
area= pi*radius*radius;
}
Summary
Summary
In this lesson
We have understood C programming language and programming language types.
Also understood difference betwen compiler and interpreter.
Also understood various C syntax, flowchart and formate specefier.
Assessment
Fill in the blanks
1. What is a program?
a) set of instruction c) set of algorithm
b) set of pseudo code d) none of these
2. Which of the following is a graphical representation of a program’s flow?
11
School of Science and Technology DCSA Program
12
School of Science and Technology DCSA Program
How long ?
Unit Structure
Lesson- 1 : Keyword and Identifier
Lesson- 2 : Variable
Lesson- 3 : Constant
Lesson- 4 : Data type
13
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Define token.
Define identifier.
Define keyword.
TOKENS IN C
A C program consists of various tokens and a token is either keywords, an identifiers, a constants, a
strings literal, operator or a symbols.
KEYWORDS
Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a specific function.
Different programming languages have different set of reserved keywords, but there is one important
and common rule in all the programming languages that these reserved words cannot be used as
constants or variables or any other identifier names. So we should keep in mind that; while giving a
name to your variable, constants or any other identifier you should not use any reserved keyword for
that programming language. The following list shows the reserved words in C.
IDENTIFIER
In C any name is called identifier. This name can be variable name, function name, enum constant name,
micro constant name, goto label name, any other data type name like structure, union, enum names or
typedef name. In other words in C, identifier is a name used to identify a variable, function, or any other
user defined item.
Rules for constructing identifiers
First character must be an alphabet or underscore and subsequent characters must be either
letter, digits, or underscore.
14
School of Science and Technology DCSA Program
1. Let’s do simple exercise. In this exercise we will match valid and invalid identifier.
2. Determine which of the following are valid identifiers. If invalid, explain why.
a) record1 b) 1record
c) file_3 d) return
e) $tax f) name
g) name and address h) name_and_address
i) name-and-address j) 123-45-6789.
15
School of Science and Technology DCSA Program
Lesson-2 Variable
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
Define variable.
Declare variables and assign values to variables.
Write programs using variables.
VARIABLE
Computer programs usually work with different types of data and need a way to store the values being
used. These values can be numbers or characters. C has two ways of storing number values such as
variables and constants with many options for each. A variable is a data storage location that has a value
that can change during program execution. So finally we can say that an identifier whose value is
allowed to change during the execution of a program is called a variable. Every variable must be
individually declared (i.e., defined) before it can appear in a statement.
In other word we can say variable is container of data. In real world you have used various type
containers for specific purpose. For example you have used match box to store match sticks, file cabinet
to store files etc. In the same way variables of different data type is used to store different types of data.
As for example integer variables are used to store integers char variables is used to store characters etc.
Before you get to variables, you need to know a little about the operation of your computer's memory.
Hope all of us already know that computer uses random access memory (RAM) to store information
while it's operating. Each computer has a certain amount of RAM installed. RAM is located in integrated
circuits, or chips, inside your computer. RAM is volatile, which means that it is erased and replaced
with new information as often as needed. Being volatile also means that RAM "remembers" only while
the computer is turned on and loses its information when you turn the computer off. The amount of
RAM in a system is usually specified in kilobytes (KB) or megabytes (MB), or gigabytes (GB) and so
on One kilobyte of memory consists of 1,024 bytes. Thus, a system with 640KB of memory actually
has 640 * 1,024, or 65,536, bytes of RAM. One megabyte is 1,024 kilobytes. A machine with 4MB of
RAM would have 4,096KB or 4,194,304 bytes of RAM.
The RAM in computer is organized sequentially, one byte following another. Each byte of memory has
a unique address by which it is identified an address that also distinguishes it from all other bytes in
memory. Now that you understand a little about the nuts and bolts of memory storage, you can get back
to C programming and how C uses memory to store information.
Study skills
16
School of Science and Technology DCSA Program
declared (i.e., defined) before it can appear in a statement and value of the variable can
change during program execution.
For example:
int number = 15;
Here, number is a variable of integer type. The variable is assigned value 15.
PROPERTIES OF VARIABLE IN C:
Every variable in c have three most fundamental attributes. They are:
1. Name
2. Value
3. Address
VARIABLE DECLARATIONS
C programming language requires a variable creation, i.e., declaration before its usage in your program.
You cannot use a variable name in your program without declaring it. The purposes of a variable
declaration-
tells the compiler what the variable name is.
specifies what type of data the variable will hold.
Where variables to be declared:
- Inside function (local variables)
- In the definition of function parameters (Formal parameters)
- Outside of all functions (global variables)
A variable declaration has the following form:
General syntax:
type varable_name;
Example:
int a
float temp;
char flag, ;
You can declare multiple variables of the same type on one line by separating the variable names with
commas:
int count, number, start; /* three integer variables */
float percent, total; /* two float variables
If your program attempts to use a variable that hasn't been declared, the compiler
generates an error message.
17
School of Science and Technology DCSA Program
On the basis of how many data a variable will store, we can categorize the all c variable in three
groups.
1. Variables which can store only one data at time. Example: integer variables, char variables,
pointer variables etc.
2. Variables which can store more than one data of similar type at a time. Example: array variables
3. Variables, which can store more than one value of dissimilar type at a time. Example: structure or
union variables.
Not two variables in c can have same name with same visibility. For example:
#include<stdio.h>
int main(){
auto int a=5; //Visibility is within main block
static int a=10; //Visibility is within main block
/* Two variables of same name */
printf("%d",a);
return 0;
}
Output: compilation error
But it is possible that two variable with same name but different visibility. In this case variable name
can access only that variable which is more local. In c there is not any way to access global variable if
any local variable is present of same name. For example:
(a)
#include<stdio.h>
int a=50; //Visibility is whole the program
int main(){
int a=10; //Visibility within main block
printf("%d",a);
return 0;
}
Output: 10
(b)
#include<stdio.h>
int main(){
int a=10; //Visibility within main block.
{
a=a+5; //Accessing outer local variable a.
int a=20; //Visibility within inner block.
a=a+10; //Accessing inner local variable a.
18
School of Science and Technology DCSA Program
Let’s consider a simple example. In this example we take two integers, add them and
display the answer on the screen. The code of the program is written below.
#include <iostream.h>
main()
Study skills {
int x;
int y;
int z;
x = 5;
y = 10;
z = x + y;
}
The first three lines declare three variables x, y and z. These three declarations can also be
written on one line. C provides us the comma separator (,). The above three lines can be
written in a single line as below
int x, y, z;
As we know that semicolon (;) indicates the end of the statement. So we can write
many statements on a single line. In this way we can also write the above declarations
in the following form
int x; int y; int z;
For good programming practice, write a single statement on a single line.
We have declared all the variables in a single line by using comma separator (,). This
is a short method to declare a number of variables of the same data type.
19
School of Science and Technology DCSA Program
Lesson-3 Constant
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
Define constant.
Declare constant.
Apply escape sequence.
CONSTANT
Like a variable, a constant is a data storage location used by your program. As its name implies, the
value stored in a constant can't be changed (fixed) during program execution. Constants (i.e., fixed
values) are also called literals. A constant is a value or an identifier whose value cannot be altered in a
program.
For example: 1, 2.5, "C programming", etc.
As mentioned, an identifier also can be defined as a constant.
const double PI = 3.14
INTEGER CONSTANT
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
decimal constant(base 10)
octal constant(base 8)
hexadecimal constant(base 16)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.
FLOATING-POINT CONSTANT
A floating point constant is a numeric constant that has either a fractional form or an exponent form.
For example:
-2.0
0.0000234
-0.22E-5
CHARACTER CONSTANT
A character constant is a constant which uses single quotation around characters. For example: 'a', 'l',
'm', 'F'
STRING CONSTANT
String constants are the constants which are enclosed in a pair of double-quote marks. For example:
"Bangladesh" //string constant
"" //null string constant
" " //string constant of six white space
20
School of Science and Technology DCSA Program
ESCAPE SEQUENCES
There are some characters which we use very frequently but they are invisible in your program and
these characters are spaces, tabs (\t), new lines (\n). These characters are called whitespaces. These
three important whitespace characters are common in all the programming languages and they remain
invisible in your text document. In order to use these characters, escape sequence is used.
Escape Sequences
Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
a) `a`
Activity b) `$`
c) `\n`
d) `/n`
e) `\\`
f) `\a`
g) `T`
h) `\0`
i) `xyz`
j) `\052`.
a) `8:15 P.M.`
b) ``Red, White and Blue``
c) ``Name:
d) ``Chap. 3 (Cont\’d)``
e) ``1.3e-12
f) ``NEW YORK, NY 10020``
g) ``The professor said, “Please don’t sleep in class``
21
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
22
School of Science and Technology DCSA Program
We can’t store decimal values using int data type. If we use int data type to store decimal
values, decimal values will be truncated and we will get only whole number. In this
case, float data type can be used to store decimal values in a variable.
FLOATING POINT DATA TYPE:
Floating point data type consists of 2 types. They are,
1. float
2. double
FLOAT
Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the
CPU as “int” data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.
DOUBLE
Double data type is also same as float data type which allows up-to 10 digits after
decimal.
The range for double datatype is from 1E–37 to 1E+37
CHARACTER DATA TYPE
So far we have been looking on data types to store numbers, In programming we do need to store
characters like a,b,c etc. For storing the character data C language provides char data type. By using
char data type we can store characters in variables. While assigning a character value to a char type
variable single quotes are used around the character as ‘a’.
Character data type allows a variable to store only one character.
Storage size of character data type is 1. We can store only one character using
character data type.
“char” keyword is used to refer character data type.
For example, ‘A’ can be stored using char datatype. You can’t store more than one
character using char data type.
Let’s take a look into different data types that the C language provides us to deal with whole numbers,
real numbers and character data.
int - data type
int is used to define integer numbers.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
printf("Entered Number is = %d",number);
return 0;
}
Output
Enter an integer: 4
Entered Number is = 4
23
School of Science and Technology DCSA Program
#include <stdio.h>
int main()
{
float f;
printf("Enter a number: ");
scanf("%f",&f);
printf("Value = %f", f);
return 0;
}
Output
Enter a number: 23.45
Value = 23.450000
double - data type
double is used to define BIG floating point numbers. It reserves twice the storage for the number.
{
double atoms;
atoms = 2500000;
}
char - data type
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.",chr);
return 0;
}
Output
Enter a character: g
You entered g.
{
char letter;
letter = 'x';
}
24
School of Science and Technology DCSA Program
enum 2
Summary
Summary
In this lesson
We have understood about C keywords and data types.
Also understood C constants and variables.
Also understood that how variables are declared in program.
Assessment
Fill in the blanks
Exercises
25
School of Science and Technology DCSA Program
Operators Unit
INTRODUCTION 3
In the previous units (unit 1 and 2) you have learned about the basics of computer programming,
different data types, constants, keywords and basic structure of a C program. You've learned how to
declare and initialize variables and constant. In this unit you will learn about operator, Operators are
special symbols that perform specific operations on one, two, or three operands, and then return a
result; and finally will explore the operators available in C programming language.
Timeframe
How long ?
Unit Structure
Lesson- 1 : Operator part -1
Lesson- 2 : Operator part -2
26
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Define Operator.
Classify Operator.
Explain arithmetic operator.
OPERATOR
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
Operators, functions, constants and variables are combined together to form expressions. Consider the
expression A + B * 5 where, +, * are operators, A, B are variables, 5 is constant and A + B * 5 is an
expression. C language is rich in built-in operators and provides the following types of operators:
Types of Operators Description
Arithmetic operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
Assignment operators These are used to assign the values for the variables in C programs.
Relational operators These operators are used to compare the value of two variables.
Logical operators These operators are used to perform logical operations on the given two
variables.
Bit wise operators These operators are used to perform bit operations on given two
variables.
Conditional (ternary) Conditional operators return one value if condition is true and returns
operators another value is condition is false.
Increment/decrement These operators are used to either increase or decrease the value of the
operators variable by one.
Special operators &, *, sizeof( ) and ternary operators.
ARITHMETIC OPERATORS
Computer programs are widely used for mathematical calculations. In C language we have the usual
arithmetic operators for addition, subtraction, multiplication and division. C also provides a special
arithmetic operator which is called modulus. All these operators are binary operators which means they
operate on two operands. So we need two values for addition, subtraction, multiplication, division and
modulus. The following table lists down a few of the important arithmetic operators available in C
programming language. Assume variable x holds 10 and variable y holds 20, then:
27
School of Science and Technology DCSA Program
Addition, subtraction and multiplication are same as we use in algebra. There is one thing to note in
division that when we use integer division (i.e. both operands are integers) yields an integer result. This
means that if, for example, you are dividing 5 by 2 (5 / 2) it will give integer result as 2 instead of actual
result 2.5. Thus in integer division the result is truncated to the whole number, the fractional part (after
decimal) is ignored. If we want to get the correct result, then we should use float data type. The modulus
operator returns the remainder after division. This operator can only be used with integer operands. The
expression x % y returns the remainder after x is divided by y. For example, the result of 5 % 2 will
be 1, 23 % 5 will be 3 and 107%10 will be 7.
INCREMENT, DECREMENT OPERATORS (++, --)
Increment and decrement are common arithmetic operation. C provides two short cuts for the same.
Postfix- will return the current value and then increment/ decrement.
x++ is a short cut for x=x+1; will return the current value and then increment.
x-- is a short cut for x=x-1; will return the current value and then decrement.
Prefix:
++x is a short cut for x=x+1; will increment x and then return the value (so it will return one greater
than the original value)
--x is a short cut for x=x-1; will decrement a and then return the value (so it will return one less than
the original value)
PRECEDENCE OF OPERATORS
The arithmetic operators in an expression are evaluated according to their precedence. The precedence
means which operator will be evaluated first and which will be evaluated after that and so on. In an
expression, the parentheses ( ) are used to force the evaluation order. The operators in the parentheses (
) are evaluated first. If there are nested parentheses then the inner most is evaluated first. The
expressions are always evaluated from left to right. The operators *, / and % have the highest precedence
after parentheses. These operators are evaluated before + and – operators. Thus + and – operators has
the lowest precedence. It means that if there are * and + operators in an expression then first the * will
be evaluated and then its result will be added to other operand. If there are * and / operators in an
expression then the operator which occurs first from left will be evaluated first and then the next, except
you force any operator to evaluate by putting parentheses around it. The following table explains the
precedence of the arithmetic operators:
OPERATOR OPERATIONS PRECEDENCE (ORDER OF EVALUATION)
() Parentheses Evaluated first
*, /, or % Multiplication, Evaluated second. If there are several, they are
Division, Modulus evaluated from left to right
+ or - Addition, Subtraction Evaluated last. If there are several, they are evaluated
from left to right
28
School of Science and Technology DCSA Program
Let’s look some examples. What is the result of 10 + 10 * 5? The answer is 60 not 100. As * has
higher precedence than + so 10 * 5 is evaluated first and then the answer 50 is added to 10 and we get
the result 60. The answer will be 100 if we force the addition operation to be done first by putting 10 +
10 in parentheses. Thus the same expression rewritten as (10 + 10) * 5 will give the result 100. Note
that how the parentheses affect the evaluation of an expression. Similarly the expression 5 * 3 + 6 / 3
gives the answer 17, and not 7. The evaluation of this expression can be clarified by writing it with the
use of parentheses as (5 * 3) + (6 /3) which gives 15 + 2 = 17. Thus you should be careful while writing
arithmetic expressions.
1. Suppose a, b and c are integer variables that have been assigned the values a = 8, b
= 3 and c = -5. Determine the value of each of the following arithmetic expressions.
a) a +b + c
Activity b) 2 * b + 3 * (a-c)
c) a / b
d) a % b
e) a * b / c
f) a * (b / c)
g) (a * c) % b
h) a * (c % b).
2. Is 2 + 5 * 2 equal to (2 + 5) * 2?
29
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
RELATIONAL OPERATOR
A relational operator takes a pair of expressions as operands and returns a logical value, true or false.
There are six common relational operators: ==, !=, >, < , , . The following table shows all the
relational operators supported by C. Assume variable x holds 10 and variable y holds 20, then:
OPERATOR DESCRIPTION EXAMPLE
== Checks if the values of two operands are equal or not. If yes, (x == y) is not true.
then the condition becomes true.
!= Checks if the values of two operands are equal or not. If the (x ! = y) is true.
values are not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of (x > y) is not true.
right operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of right (x < y) is true.
operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (x >= y) is not true.
value of right operand. If yes, then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the (x <= y) is true.
value of right operand. If yes, then the condition becomes true.
LOGICAL OPERATOR
Logical operators are very important in any programming language and they help us take decisions
based on certain conditions.
OPERATOR OPERATIONS DESCRIPTIONS EXAMPLE
&& Logical AND If both the operands are true, then (x>5)&&(y<5)
condition becomes true.
|| Logical OR If any of the two operands is true, then (x>=10)||(y>=10)
condition becomes true.
! Logical NOT Use to reverses the logical state of its
operand. If a condition is true then Logical !((x>5)&&(y<5))
NOT operator will make false.
30
School of Science and Technology DCSA Program
ASSIGNMENT OPERATOR
Operator Description Example
= Simple assignment operator. Assigns values C = A + B will assign the value of A
from right side operands to left side operand. + B to C
In C programs, values for the variables are assigned using assignment operators. For example, if the
value “10” is to be assigned for the variable “sum”, it can be assigned as “sum = 10;” In C language
equal-to-sign (=) is used as assignment operator. Do not confuse the algebraic equal-to with the
assignment operator. In Algebra X = 2 means the value of X is 2, whereas in C language X = 2 (where
X is a variable name) means take the value 2 and put it in the memory location labeled as X, afterwards
you can assign some other value to X, for example you can write X = 10, that means now the memory
location X contains the value 10 and the previous value 2 is no more there. In C language the statement
X = X + 1 means that add 1 to the value of X and then store the result in X variable. If the value of X is
10 then after the execution of this statement the value of X becomes 11. This is a common practice for
incrementing the value of the variable by ‘one in C language. Similarly you can use the statement X =
X - 1 for decrementing the value of the variable by one. Remember that assignment operator must have
a variable name on left hand side unlike algebra in which you can use expression on both sides of equal
sign (=). For example, in algebra, X +5 = Y + 7 is correct but incorrect in C language. The compiler
will not understand it and will give error.
C provides compound assignment operators that can be used instead.
x+=1 /∗is the same as x=x+1∗/
x-=1 /∗is the same as x=x-1∗/
x∗=10 /∗is the same as x=x∗10 ∗/
x/=2 /∗ is the same as x=x/2
x%=2 /∗is the same as x=x%2
Note that the "==" equality operator is different from the "=", assignment operator.
TERNARY OPERATOR (?:)
Conditional operators return one value if condition is true and returns another value is condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example : (A > 100 ? 0 : 1);
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
One more example
if(a > b)
result = x;
else
result = y;
is equivalent to
result = a > b ? x : y;
1. What is the output of this C code? 2. What is the output of this C code?
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
Study skills int a = 1, b = 1, c; int a = 10, b = 10;
c = a++ + b; if (a = 5)
printf("%d, %d", a, b); b--;
} printf("%d, %d", a, b--);
a) a = 1, b = 1 b) a = 2, b = 1 }
c) a = 1, b = 2 d) a = 2, b = 2 a) a = 10, b = 9 b) a = 10, b = 8
Correct answer is: b c) a = 5, b = 9 d) a = 5, b = 8
31
School of Science and Technology DCSA Program
Summary
Summary
In this lesson
We have understood about various types of C operators and operands.
Also understood operator precedence.
Assessment
Fill in the blanks
3. In C logical AND represents as…………
Assessment 4. …….. operator is called “modulus operator” in C
32
School of Science and Technology DCSA Program
In the previous lessons we have learned about the programming structure, data types, declaration of
variables, tokens, constants, keywords and operators as well as how to write program in C and how
to execute program. In this unit we will teach about another feature of C. In this unit we will also
learn how to make a decision in program and how to execute this concept.
Timeframe
How long ?
Unit Structure
Lesson- 1 : Basic concept on decision making statements
Lesson- 2 : Decision making using if and if-else statements
Lesson- 3 : Decision making using nesting of if-else statements
Lesson- 4 : Decision making using else-if ladder statements
Lesson- 5 : Decision making using switch case statements
33
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
PRELIMINARIES
We have already seen that, basically a C program is a set of statements which are usually executed
successively. But in practice, we have a number of situations where we may have to change the order
of execution of statements based on certain conditions, or replicate a group of statements until certain
specified circumstances are met.
The general form of a standard decision making structure found in most of the programming languages
like C is as follows:
Entry
Condition ?
If
If condition is true
condition
Conditional code is false
i. if statement
ii. if-else statement
iii. nesting if-else statement
iv. else-if ladder statement
v. switch case statement
34
School of Science and Technology DCSA Program
We have a number of situations where we may have to change the order of execution
of statements based on certain conditions
The above decision making statements are shortly described here, and described in details in next
lessons.
Summary
Summary
In this lesson
We have understood about C language decision making statements.
Assessment
Fill in the blanks
Exercises
35
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
SIMPLE IF STATEMENT
The simple if statement is an influential decision making statement. It is used to control the flow of
execution of statements. On other hand, it is also a two-way decision making statement.
It is also used to evaluate the expression or condition first and then, depending on whether the value of
the expression is true or false.
if ( Condition/expression )
{
Statement-block;
………………….
}
Statement-n;
Here, statement-block can be single or a group of statements. If condition/expression is true then, the
statement-block will be executed, otherwise the statement-block will be omitted and the execution will
jump to the statement-n.
In this situation, it is remembered that, when the condition is true both the statement-block and
statement-n are executed in sequence.
36
School of Science and Technology DCSA Program
Entry
Test True
Conditions
?
Statement-block
False
Statement-n
Next Statement
Figure 4.2.1: Flowchart of simple if control statement
void Main()
{
…………………………….
……………………………
if( N= =100)
{
N=N+50;
}
printf(“%d”, N);
. ……………………
……………………..
}
In the above program segment, the program checks the value of N. If the value of N is 100 then extra
50 are added with N before printed, otherwise the value of N will be printed.
The if statement is used to evaluate the expression or condition first and then,
depending on whether the value of the expression is true or false
Program 4.2.1 Write a program to display a number if user enters negative number. If user
enters positive number, that number won't be displayed.
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("Enter Integer Number:");
scanf("%d",&num);
37
School of Science and Technology DCSA Program
if(num < 0)
{
printf("You entered %d. \n", num);
}
Program 4.2.2 Write a program to display salary of an employee, where if salary is less than
20000 taka then add home allowance 5000 taka with basic salary, otherwise display salary
without home allowance.
#include<stdio.h>
#include<conio.h>
void main()
{
long int salary;
printf("Enter Basic salary of an employee:");
scanf("%ld",&salary);
The if-else statement is an extension of the simple if statement. This type of statement is used to carry
out a logical test and then take one of the two possible actions depending on the result of the test. The
general structure of if-else statement is as follows:
if (test condition/expression)
{
38
School of Science and Technology DCSA Program
True statements-block;
}
else
{
False statements-block;
}
statement- n;
The if-else statement executes some code if the test condition or expression is true and some other code
if the test expression or condition is false.
Here, if the test condition or expression is true (non-zero) then true statements-block is executed
otherwise false (zero) statements-block is executed. It is remembered that, in if-else statement, either
true statements-block or false statements-block will be executed, not both. In both cases the control is
transferred subsequently to statement-n.
Entry
Statement-n
void main()
{
................
................
if(test= = 1)
{
scanf("%f",&radious);
Area=3.14159*radious*radious;
printf("Area of Circle is:= %f\n",Area);
}
else
39
School of Science and Technology DCSA Program
{
scanf("%f %f",&base,&height);
Area=0.5*base*height;
printf("Area of traingle is:= %f\n",Area);
}
}
In the above example, if the variable test value is only 1 then true statement block of if will be executed
and print the area of circle, otherwise false statement block of else will be executed and print the area
of triangle.
void main()
{
int age;
In the above example, user enter his or her age from keyboard, if the variable age value is greater than
or equal 18 years then, true statement block of if will be executed and print ‘you are eligible for voting’,
otherwise false statement block of else will be executed and print ‘you are not eligible for voting’.
The if-else statement executes some code if the test condition or expression is true and
some other code if the test expression or condition is false.
Program 4.2.3 write a program that checks a number is either EVEN or ODD.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int number;
40
School of Science and Technology DCSA Program
if(number%2==0)
{
printf("Given Number is EVEN.\n");
}
else
{
printf("Given Number is ODD.\n");
}
getch();
}
…………………………………………………………………………………..
Output
Enter a integer number: 100
Given Number is EVEN.
Enter a integer number: 15
Given Number is ODD
Program 4.2.4 Write a program to print employee monthly salary, where, if basic salary is grater
that 20000 taka then 40% home allowance of basic salary and 1500 taka medical allowance are
added with basic salary, otherwise 55% home allowance and 1000 taka medical allowance are
added with basic salary.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
long int bsalary,msalary;
getch();
}
……………………………………………………………………………………
Output
Enter Employee Basic salary: 30000
Employee Monthly Salary is: 43500
Enter Employee Basic salary: 20000
Employee Monthly Salary is: 32000
41
School of Science and Technology DCSA Program
b. ................................
................................
if( code>1)
{
a=b+c
else
a=0
}
4. The following is a segment of a program:
X=1;
Y=1;
if(n>0){
X=X+1;
Y=Y-1;
}
printf(“%d %d”,X,Y);
42
School of Science and Technology DCSA Program
Summary
In this lesson
We have gathered knowledge about C control statements.
Moreover we have learned that how if statement works in program.
We also have understood that how if-else statement works in program.
ASSIGNMENT
Assessment
Write “T” for true and “F” for false for the following sentences
1. The if-else statement is an extension of the simple if statement.
Assessment 2. if statement is a single-way decision making statement.
3. The if-else statement executes some code if the test condition is true and some
other code if the test condition is false.
Exercises
43
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
In the previous lesson, we have seen that, the if-else statement executes only two different codes
depending upon whether the test expression/condition is true or false. However, in practical, sometimes,
a choice has to be made from more than two possibilities.
When sequences of decisions are concerned, we may have to apply more than one if-else statement in
nested form. Nested if-else statement is similar to if-else statement, where new block of if-else statement
is defined in existing if or else block statement. The nested if-else statement allows us to verify for
multiple test expressions and execute different codes for more than two conditions.
if(test expression-1)
{
if(test expression-2)
{
block of statement-1;
}
else
{
block of statement-2;
}
else
{
block of statement-3;
}
statement-n;
The logic execution flow chart is demonstrated in figure 4.3.1.
44
School of Science and Technology DCSA Program
Entry
Test True
Expression-2
?
False
Statement-n
Next Statement
Figure 4.3.1: flowchart of nested if-else statements
From the flowchart, we can say that, if the test expression-1 is false the block statement-3 will be
executed; otherwise it continues to perform the second test expression. If the test expression-2 is true
the block statement-1 will be executed; otherwise the block statement-2 will executed and then the
control goes to the statement-n and so on.
Nested if-else statement is similar to if-else statement, where new block of if-else
statement is defined in existing if or else block statement.
Program 4.3.1 Write a program to display largest number from three integer numbers using
nested if-else statements.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
45
School of Science and Technology DCSA Program
int num1,num2,num3;
}
else
{
printf("Largest number is: %d\n", num3);
}
}
else
{
if(num3 > num2)
{
printf("Largest Number is: %d\n",num3);
}
else
{
printf("Largest Number is: %d\n",num2);
}
}
getch();
}
…………………………………………………………………………………..
Output
Enter three integer numbers:
20
400
100
Largest Number is: 400
Program 4.3.2 Write a program to check username and password for login using nested if-else
statements.
#include <stdio.h>
#include <conio.h>
void main()
{
char username;
int password;
clrscr();
printf("Enter Your Username:");
scanf("%c",&username);
printf("Enter Your Password:");
scanf("%d",&password);
46
School of Science and Technology DCSA Program
if(username = ='a')
{
if(password = =12345)
{
printf("Login successful");
}
else
{
printf("Password is incorrect, Try again!!!");
}
}
else
{
printf("Username is incorrect, Try again!!!");
}
getch();
}
.......................................................................................................................................
Output
Enter Your Username: am
Enter Your Password:1234
Username is incorrect, Try again!!!"
Program 4.3.3 Write a program to check monthly balance of a customer of a bank, where if
customer sex is female and current balance is greater than 10000 taka, than bonus will be 10% of
current balance, and if current balance is less than 10000 taka bonus will be 5%, otherwise bonus
will be 2%.
#include <stdio.h>
#include <conio.h>
void main()
{
char sex;
long int balance,bonus,mbalance;
clrscr();
printf("Enter your sex:");
scanf("%c",&sex);
printf("Enter your balance:");
scanf("%ld",&balance);
if(sex=='F')
{
if(balance>10000)
{
bonus=balance*.10;
}
else
{
bonus=balance*.05;
}
47
School of Science and Technology DCSA Program
}
else
{
bonus=balance*.02;
}
mbalance=balance+bonus;
printf("Monthly Balance will be: %ld",mbalance);
getch();
}
…………………………………………………………………………………
Output
Enter your sex: M
Enter your balance: 12000
Monthly Balance will be: 12240
1. Identify the errors form the following program segments and correct them :
void main()
{
Study skills int x,y,z;
x=10;y=5,z=6;
if(x<=10);
{
if(y>5)
y=x++;
else
if(z = =6 && x=10)
z=x+y;
else
x=x++;
}
printf("%d\n",&x)
printf("%d\n",&y);
}
printf("%d\n",&z);
}
2. After correction the above program what will be the output?
Summary
Summary
In this lesson
We have gathered knowledge about C control statements.
Moreover we have learned that how nesting if-else statement works in program.
48
School of Science and Technology DCSA Program
ASSIGNMENT
Assessment
Write “T” for true and “F” for false for the following sentences
1. When sequences of decisions are concerned, we may have to apply more than
Assessment one if-else statement in nested form.
2. Nested if-else statement allows us to verify for multiple test expressions.
Exercises
49
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
In practical, when we need to test different conditions with different statements, where multipath
decisions are involved, this is called else-if ladder. Actually multipath decision is a sequence of ifs in
which the statements related with each else is an if. If-else ladder statement is used to test set of
conditions in sequence that is if we have different test conditions with different statements then we need
else-if ladder statements. The general syntax of if-else ladder is as follows:
if (test_condition-1)
{
statement-1;
}
else if(test_condition-2)
{
statement-2;
}
else if(test_condition-3)
{
statement-3;
}
else if(test_condition-4)
{
statement-4;
}
………………
else if(test_condition-n)
{
statement-n;
}
else
{
default-statement;
}
Statement-X;
50
School of Science and Technology DCSA Program
The above construction is known as if-else ladder. Here, the conditions are evaluated from top to
bottom. As soon as when a test condition is true, then the statement(s) associated with it is executed and
the programming control is transferred to the statement-X. When all conditions are failed or false then
the final else containing the default-statement will be executed. The flowchart of if-else ladder is shown
in bellow:
Input Entry
False
Test
Condition-1
True False
Test
Statement-1
Condition-2
True False
Test
Statement-2 Condition-3
True False
Test
Statement-3 Condition-n
Statement-n
Default statement
Statement-X
If-else ladder statement is used to test set of conditions in sequence that is if we have
different test conditions with different statements then we need else-if ladder statements
51
School of Science and Technology DCSA Program
Program 4.4.1 Assume an example of grading system of the students in an institution. The
grading is done according to the following rules:
#include<stdio.h>
#include<conio.h>
void main()
{
int marks;
printf("Enter your Marks:");
scanf("%d",&marks);
if(marks>100)
{
printf("\nInvalid Marks. Marks must be less than 100");
}
else
{
if(marks<=100 && marks>=80)
{
printf("Your Grade is A+");
}
else if(marks<80 && marks>=75)
{
printf("Your Grade is A-");
}
else if(marks<75 && marks>=70)
{
printf("Your Grade is A");
}
else if(marks<70 && marks>=65)
{
printf("Your Grade is B+");
}
else if(marks<65 && marks>=60)
{
printf("Your Grade is B-");
}
else if(marks<60 && marks>=55)
{
printf("Your Grade is B");
}
else if(marks<55 && marks>=50)
{
printf("Your Grade is C+");
}
else if(marks<50 && marks>=45)
{
52
School of Science and Technology DCSA Program
Program 4.4.2 Assume that DESCO power distribution company charges its domestic
customers as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
int units;
float pa_amount;
printf("Enter Consumed Units:");
scanf("%d",&units);
if(units>701)
{
pa_amount=units*8.50;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else
{
if(units<=100 && units>=0)
{
pa_amount=units*1.00;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else if(units<=200 && units>=101)
{
53
School of Science and Technology DCSA Program
pa_amount=units*1.50;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else if(units<=300 && units>=201)
{
pa_amount=units*2.00;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else if(units<=400 && units>=301)
{
pa_amount=units*2.75;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else if(units<=500 && units>=401)
{
pa_amount=units*3.50;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else if(units<=600 && units>=501)
{
pa_amount=units*4.70;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else if(units<=700 && units>=601)
{
pa_amount=units*5.00;
printf("\n Customer Total Payable amount is: %f Taka",pa_amount);
}
else
{
printf("Illigible Customer!!!!!");
}
}
getch();
}
…………………………………………………………………………………..
Output
Enter Consumed Units:800
Customer Total Payable amount is: 6800.00000 Taka
Enter Consumed Units:300
Customer Total Payable amount is: 600.00000 Taka
1. Mention the significance of using if-else ladder statement by your own concept.
………………………………………………………………………………..
……………………………………………………………………..…………
Activity
2. Write the if-else ladder statement syntax with 10 conditions.
…………………………….………….……………………………………….
………..…………………………….…………………………………………
54
School of Science and Technology DCSA Program
Summary
Summary
In this lesson
We have gathered knowledge about C control statements.
Moreover we have learned that how if-else ladder statement works in program.
We also have understood that how if-else ladder flowchart works in program.
ASSIGNMENT
1. Suppose A Firm has 100 employee. The basic salary range and house rent and bonus
of different categories employees are given bellow:
Now write a C program to calculate total salary of an employee, where total salary
is the sum of basic salary, house rent and bonus.
Assessment
Write “T” for true and “F” for false for the following sentences
1. If-else ladder statement is used to test set of conditions in sequence.
Assessment 2. When all conditions are failed or false then the final else containing the
default-statement will not be executed.
Exercises
55
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
In previous lesson we have seen that the nested if-else statement allows us to execute a block of
statements or code among many conditions or alternatives. If we are checking on the value of a single
variable in nested if –else statement, in this situation it is better to use switch case statement. It is
frequently faster than nested if-else but not always. Fortunately, C has built-in multi-way decision
statement known as switch statement. A switch statement tests the value of a given variable or
expression against a list of case values. In this statement, when case is matched or found then block of
statements associated with that case is executed. This type of statement is mostly used when we have
number of options or choices or cases and we may need to perform a different task for each choice or
case. The general syntax of switch case statement is as follows:
default:
default block;
break;
}
56
School of Science and Technology DCSA Program
Statement-X;
In the above syntax, the expression is an integer expression or characters. Constant-1, Constant-2,
Constant-3…. Constant-n are known as case labels. Here, each of these values must be unique within
switch statement and bock-code-1, bock-code-2, bock-code-3… bock-code-n are statement lists. When
switch is executed the variable or value of the expression is successively compared against the cases. If
a case is found or matched with the value of the expression, then the associated block code or
statement(s) are executed.
The break statement at the end of the each block code means the end of specific case and causes an exit
from the switch statement, and for that reason, transfers program control to statement-X. If the break
statement is missed from any case, then program executes all statements until get break statement from
another case. The default is optional. When variable or value of expression does not match with any of
the case values then default statement(s) are executed.
Input Entry
Switch
Expression
Case Constant-1
Block-code-1
Case Constant-2
Block-code-2
No match default
Default block
Statement-X
Figure 4.5.1: Flowchart of switch case statement
A switch statement tests the value of a given variable or expression against a list of case
values. When case is matched or found then block of statements associated with that
case is executed.
1. Mention the significance of using switch case statement by your own concept.
……………………………………………………………………………………..
……………………………………………………………………………………..
Activity
2. Write the switch case syntax with 10 cases.
……………………………………………..………………………………………
……………………………………………..………………………………………
57
School of Science and Technology DCSA Program
Program 4.5.1 Assume an example of grading system of the students in an institution. The
grading is done according to the following rules:
#include<stdio.h>
#include<conio.h>
void main()
{
value =marks/10;
switch(value)
{
case 10:
case 9:
case 8:
printf("Well done Your grade is A+");break;
case 7:
printf("Well done Your grade is A-");break;
case 6:
printf("Well done Your grade is B");break;
case 5:
printf("Well done Your grade is C"); break;
case 4:
printf("Well done Your grade is D");break;
default:
printf("Sorry Your grade is F!!");
}
getch();
}
…………………………………………………………………………………..
Output
Enter the marks: 95
Well done Your grade is A+
Enter the marks: 66
Well done Your grade is B
Enter the marks: 33
Sorry Your grade is F!!"
58
School of Science and Technology DCSA Program
Summary
Summary
In this lesson
We have gathered knowledge about basic idea about switc case statement.
Moreover we have learned that how switch case statement works in program.
ASSIGNMENT
Suppose A Firm has 100 employee. The basic salary range and house rent and bonus of
different categories employees are given bellow:
Basic salary House rent Bonus
Greater than 40000 35% of basic salary 20% of basic salary
Assignment 30000 to less than 40000 40% of basic salary 15% of basic salary
20000 to less than 30000 45% of basic salary 12% of basic salary
10000 to less than 20000 50% of basic salary 10% of basic salary
Less than 10000 55% of basic salary 8% of basic salary
Now write a C program to calculate total salary of an employee, where total salary
is the sum of basic salary, house rent and bonus using switch case statement.
Assessment
Fill in the blanks with appropriate word
1. C has built-in …………. decision statement known as………… statement.
Assessment 2. When switch is executed the ……………….. is successively compared
against the cases.
3. In switch case statement the …………… is optional.
4. A ……….statement tests the value of a given…………….against a list of
case values.
Exercises
59
School of Science and Technology DCSA Program
How long ?
Unit Structure
Lesson- 1 : Basic concept on loop control structures
Lesson- 2 : Understanding while loops
Lesson- 3 : Understanding do-while loops
Lesson- 4 : Understanding for loop
Lesson- 5 : Understanding break and continue statements
Lesson- 6 : Understanding goto statement
60
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
INTRODUCTION TO LOOP
In practical, we may encounter many circumstances, when a block of code needs to be executed several
number of times. We have already learned that in program, statements are executed sequentially. The
first statement is executed first, followed by the second, third and so on. C language provides various
control structures that allow for more complicated execution paths. In programming, a loop is a
sequence or arrangement of instruction(s) that is continually repeated until a certain condition is
reached. In looping, a sequence of statements are executed until some conditions for end of the loop are
satisfied. It is a necessary idea that is commonly used in writing programs. A loop statement permits us
to execute a statement or group of statements several times. A program loop contains two sections, such
as (1) body of the loop and (2) control statement. The control statement tests definite conditions and
then guides the repeated execution of the statements checked in the body of the loop.
A loop control structure may be classified either as the entry-controlled loop or as the exit-controlled
loop. Both control structures are described in the following sections.
Entry-controlled loop
In the entry-controlled loop, the control conditions are tested before the start of the loop execution. It
the conditions are not satisfied, then the body of the loop will not be executed. The flowchart of entry-
controlled loop is shown in below:
61
School of Science and Technology DCSA Program
Input Entry
False
Test
Condition
Running
True
Input Entry
True
Test
Condition
False
Figure 5.1.2: Exit-controlled loop structure
A loop control structure may be classified either as the entry-controlled loop or as the
exit-controlled loop.
LOOPING PROCESS
62
School of Science and Technology DCSA Program
The programming C language provides three loops for performing loop operation, which are as
follows: (i) while loop, (ii) do-while loop, and (iii) for loop. We will briefly describe above loops in
the later lessons one by one.
Summary
Summary
In this lesson
We have learned about C loop control structure.
Moreover we have learned how to design entry-controlled and exit-controlled loop structure
flow chart.
Assessment
Fill in the blanks
1. A loop is a …………instruction(s).
Assessment 2. A loop statement ……….. us to execute a statement or …………. several
times.
Multiple Choice Questions (MCQ)
1. a loop is a sequence or arrangement of
a) Variables b) Constants c) Instructions d) None of these
2. In looping, a sequence of statements are executed until-
a) Some conditions for end of the b) Only one conditions for end of
loop are satisfied the loop are satisfied
c) Some variables for end of the d) None of these
loop are satisfied
3. In the entry-controlled loop, the control conditions are tested
a) Before the start of the loop execution
b) After the start of the loop execution
c) Middle of the loop execution
d) End of the loop execution
4. In the exit-controlled loop, the control conditions are tested
a) At the end of the body of the loop
b) After the start of the loop execution
c) Before the start of the loop execution
d) None of these
Exercises
1. What is loop? Mention the major benefit of using loop in programming language.
2. Explain the loop control structures with flowchart.
3. Mention the looping process steps.
63
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
We have already learned that loops are used in programming to repeat a specific block until some end
condition is met. While loop is simple loop in C. A while loop in C programming repeatedly executes
a target statement as long as a given condition is true. The basic form or syntax of while loop is as
follows:
while( Test-condition)
{
Body of the loop or statement(s);
}
Here, body of the loop or statement(s) may be a single statement or a block of statements. The Test-
condition may be any expression, and true is any nonzero value. The while loop is an entry-controlled
loop.The Test-condition is evaluated and if the condition is true then the body of the loop or statements
Input Entry
Test False
Condition
True
64
School of Science and Technology DCSA Program
are executed. After execution of the body of the loop, the Test-condition is once again evaluated and it
is true, the body of the loop is executed again. This process is repeated until the Test-condition finally
becomes false and the programs control is transferred out of the loop. Finally we can say that, in while
loop Test-condition is tested before the body of the loop is executed. The flowchart of while loop is
shown in figure 5.2.1. Here, the important point is noted that a while loop might not execute at all, when
the Test-condition is tested and the result is false, body of the loop will be skipped and the next
statement after the while loop will be executed.
#include <stdio.h>
#include <conio.h>
void main ()
{
int a = 10;
while( a <16 )
{
printf("value of a: %d\n", a);
a++;
}
getch();
}
……………………………………………………………………………….
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Program 5.2.2 write a C program to find out factorial value of a given integer number using while
loop
#include <stdio.h>
void main()
{
int number;
long int factorial;
printf("Enter an integer Number: ");
scanf("%d",&number);
factorial = 1;
while (number > 0)
{
factorial = factorial * number;
--number;
}
printf("Factorial value is = %ld", factorial);
65
School of Science and Technology DCSA Program
}
…………………………………………………………………………….……….
Output
Enter an integer Number: 6
Factorial value is = 720
Enter an integer Number: 10
Factorial value is = 3628800
Program 5.2.3 write a C program that prints only odd numbers from 1 to 30 using while loop
#include <stdio.h>
#include<conio.h>
void main ()
{
int a = 1;
printf("Odd Numbers Till 30 are: \n");
while( a < 30 )
{
printf("%d \t", a);
a+=2;
}
getch();
}
…………….………………………………………………………………..
Output
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
A while loop might not execute at all, when the Test-condition is tested and the result
is false, body of the loop will be skipped and the next statement after the while loop will
be executed.
66
School of Science and Technology DCSA Program
Summary
Summary
In this lesson
We have learned about C while loop with its syntax.
We have also learned how a while loop works in program.
ASSIGNMENT
1. Write a C program that find out the odd and even numbers from N integer numbers
using while loop.
……………………………………………………………………………………
………………………..…………………………………………………………..
2. Write a C program to print the result of the equation yx using while loop.
Assignment
……………………………………………………………………………………
…………………………………………………………………………………….
Assessment
Write “T” for true and “F” for false the following sentences:
1. A while loop in C programming repeatedly executes a target statement as long as a
Assessment given condition is false.
2. In while loop Test-condition finally becomes true and the programs control is
transferred out of the loop.
Exercises
1. What is while loop? Mention the major benefit of using while loop in programming language.
2. Explain the while loop control structures with flowchart.
3. Write a C program to calculates the power value of equation P=2N using while loop.
4. Write a C program to find out the value of following series using while loop:
Y= 11+23+35+………………………………….Nn
67
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
We have learned that, in while loop a Test-condition is tested before body of the loop is executed.
Consequently, if the Test condition is not satisfied at the first time, then the body of the loop may not
be executed at all. But in some situations it might be necessary to execute the body of the loop or
statement(s) before the test is executed. Such circumstances can be handled with the help of do-while
loop. The general syntax of do-while loop is as follows:
do
{
Body of the loop or statement(s);
}while(Test-condition);
In do-while loop, the program proceeds to evaluate the body of the loop or statement(s) first. In this
loop, the Test-condition in while statement is evaluated at the end of the loop.
Input Entry
Body of the
loop True
Test
Condition
False
If the Test-condition is true, the program continues to evaluate the body of the loop once again. This
process continues as along as the Test-condition is true. If the Test-condition is false, the loop will be
68
School of Science and Technology DCSA Program
terminated and program control goes to the statement that appears after while statement A do...while
loop is similar to a while loop, but the point that it is exit-controlled loop and therefore the body of the
loop is always executed at least one time. The flowchart of do-while loop is shown in figure 5.3.1.
In do-while loop, the program proceeds to evaluate the body of the loop or statement(s)
first. In this loop, the Test-condition in while statement is evaluated at the end of the
loop
Program 5.3.1 Write a program to calculate the average of N numbers and display the result
using do-while loop.
#include<stdio.h>
#include<conio.h>
void main ()
{
int number, count =1;
float x, average, sum = 0.0;
printf("How Many Numbers?:");
scanf("%d",&number);
do
{
printf(" Enter the %d Number = ",count);
scanf("%f",&x);
sum = sum + x;
++count;
}while(count < = number);
average = sum/number;
printf("\n The average is: %f",average);
getch();
}
…………………………………………………………………………….
Output
How Many Numbers?: 3
Enter the 1 Number =10
Enter the 2 Number =20
Enter the 3 Number =30
The average is: 20.000000
Program 5.3.2 Write a C program that convert a line of lowercase text to Uppercase text using
do-while loop.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#define EOL '\n'
void main ()
{
char letter[80];
int value,count=-1;
printf("Type text or line as lowercase:\n");
do
{
++count;
69
School of Science and Technology DCSA Program
Program 5.3.3 Write a C program that print the multiplication table of 5 from 1 to 10 using do-
while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int value=1;
printf("Multiplication Table of 5 from 1 to 10:\n");
do
{
printf("5 * %d = %d\n",value,5*value);
value++;
}while(value<=10);
getch();
}
……………………………………………………………………………….
Output
Multiplication Table of 5 from 1 to 10:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
70
School of Science and Technology DCSA Program
do
{
printf("6 * %d = %d\n",value,6*value);
value++;
}while(value <= 6);
}
Summary
Summary
In this lesson
We have learned about C do-while loop with its syntax.
We have also learned how a do-while loop works in program.
ASSIGNMENT
1. Write a C program that display factorial value of n number using do-while loop.
………………………………………………………………………………..
………………………………………………………………………………..
Assignment
Assessment
Write “T” for true and “F” for false the following sentences:
1. In do-while loop, the program proceeds to evaluate the body of the loop or
Assessment statement(s) first.
2. If the Test-condition is false in do while loop, the program continues to
evaluate the body of the loop once again.
Exercises
1. What is do while loop? Mention the major benefit of using do while loop in programming
language.
2. Explain the do while loop control structures with flowchart.
71
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
FOR LOOP
We have learned in previous lesson about while and do-while loops. The for loop is the third and most
commonly used loop in C program. It is another entry-controlled loop that delivers shorter loop control
structure. The for loop is a recurrence control structure that allows us to proficiently write a loop that
needs to perform an exact number of times.
1. In loop, the initialization step is performed first, and only once. This stage allows us to
announce or declare and initialize any loop control variables. We are not necessary to put a
statement here, as long as a semicolon appears. Initialization of control variable using
assignment operator such as i=1, count=0, value=1 etc. These initialization variables are
known as loop control variable.
2. Next, the Test-condition is evaluated. Test-condition is a relational expression such as count
<=10 or I >20 etc. that determines when the loop will exit. If Test-condition is true, then the
body of the loop is executed. If Test-condition is false, the body of the loop does not execute
and the flow of control jumps to the next statement just after for loop.
3. After execution of the body of the for loop, the flow of control jumps back up to the
increment/decrement statement. This statement allows us to update (i.e., increment or
decrement) any loop control variable.
4. After control variable updated (i.e., increment or decrement), the Test-condition is now
evaluated again. If Test-condition is true, the loop executes and the process repeats itself and
if the Test-condition becomes false, the for loop terminates.
72
School of Science and Technology DCSA Program
Initialization
Test False
Condition
True
Increment/decrement
Exit
The for loop is a recurrence control structure that allows us to proficiently write a loop
that needs to perform an exact number of times
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
73
School of Science and Technology DCSA Program
for(i=1;i<=10;i= i+1)
{
printf("%d\t",i);
}
getch();
}
…………………………………………………………………………..
Output
1 2 3 4 5 6 7 8 9 10
Program 5.4.2 Write a C program that calculate the value of the following series using for loop
Y=1+3+5+7+……………………………………………………………………N.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, N, sum=0;
printf("Enter the value N of series: ");
scanf("%d",&N);
printf("\nThe Total value of series is: ");
for(i=1;i<=N; i=i+2)
{
sum=sum+i;
}
printf("%d",sum );
getch();
}
……………………………………………………………………………
Output
Enter the value N of series: 10
The Total value of series is: 25
Program 5.4.3 Write a C program that calculate the value of the following series using for loop
Y=12+32+52+72+……………………………………………………………………N2.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
long int i, N, sum=0;
printf("Enter the value N of series: "); scanf("%ld",&N);
printf("\nThe Total value of series is: ");
for(i =1;i<=N; i=i+2)
{
sum=sum+pow(i,2);
}
printf("%ld",sum ); getch();
}
…………………………………………………………………………..
Output
74
School of Science and Technology DCSA Program
C programming allows us to use one loop inside another loop. Nesting of loops, that is one for loop
within another for loop statement. This process is called nesting of for loop. Tow loops can be nested
as follows:
Nesting of loops, that is one for loop within another for loop statement. This process is
called nesting of for loop
Program 5.4.4 Write a C program that print the following pattern using nested for loop.
1
12
123
1234
12345
123456
#include<stdio.h>#include<conio.h>#include<math.h>
void main()
{
int row,col;
for(row=1;row<=6;row++)
{
for(col=1;col<=row;col++)
{
printf("%d ", col);
}
printf("\n");
}getch();
}
……………………………………………………………………………
Output
1
12
123
1234
12345
75
School of Science and Technology DCSA Program
123456
Program 5.4.5 Write a C program that print the following pattern using nested for loop.
*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int row,col,j,space=5;
for(row=0;row<5;row++)
{
for(col=0;col<space;col++)
{
printf(" ");
}
for(j=0;j<=row;j++)
{
printf("* ");
}
printf("\n");
space--;
}
getch();
}
……………………………………………………………………………
Output
*
* *
* * *
* * * *
* * * * *
Program 5.4.6 Write a C program that print all prime numbers from 1 to N range using nested
for loop.
#include <stdio.h>
void main ()
{
int i, j,N;
printf("Enter the value of range N: ");
scanf("%d",&N);
for(i = 1; i<N; i++)
{
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break;
if(j > (i/j))
printf("%d is prime\n", i);
}
76
School of Science and Technology DCSA Program
}
…………………………………………………………………………..
Output
Enter the value of range N: 20
1 is prime
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
1. Analyze each of the program segments that follow and determine how many times
the body of each loop will be executed:
i. int i;
Activity for( i=0;i<=8; i=i+2/5)
{
……………………
}
ii. int m=10, n=7;
while(m%n>=0)
{ …………………..
m=m+1;
n=n+2;
}
2. Find errors, if any in each of the following looping segments:
i. for(x=1,x>10;x=1)
{
printf(“ %d test”);
………………………..
}
ii. for (p=10;p>0;)
p=p-1;
printf(“%f”,&p);
Summary
Summary
In this lesson
We have learned about C for loop with its syntax.
We have also learned how a for loop works in program.
ASSIGNMENT
1. Write a C program that display factorial value of n number using for loop.
………………………………………………………………………………..
………………………………………………………………………………..
2. Write a program that print the result of the following series:
Y= 1+x+x2+x3+x5+……………………………………..xn
Assignment
77
School of Science and Technology DCSA Program
Assessment
Write “T” for true and “F” for false the following sentences:
1. In for loop, the initialization step is performed first, and infinite.
Assessment 2. In for loop Test-condition is an assignment expression.
3. The for loop is a recurrence control structure.
4. In for loop if Test-condition is false, then the body of the loop is executed.
Multiple Choice Questions (MCQ)
1. In for loop initialization of control variable using-
a) Assignment b) Relational c) Logical d) None of these
operator operator operator
2. For loop is another-
a) Entry-controlled loop that delivers shorter loop control structure.
b) Exit- controlled loop that delivers shorter loop control structure.
c) Exit- controlled loop that delivers longer loop control structure.
d) None of these
3. After execution of the body of the for loop, the flow of control-
a) Jumps back up to the increment/decrement statement.
b) Jumps down up to the increment/decrement statement.
c) Jumps back up to the assignment statement.
d) Jumps back up to the test-control statement.
Exercises
1. What if for loop? Discus with its syntax
2. Distinguish among while, do-while and for loop with an example
3. Describe for loop flowchart with an example.
4. Write a C program that prints the following pattern using for loop
A
AA
A AA
A A AA
A A A AA
5. Write a C program that prints the following pattern using for loop:
1
2 3
3 4 5
4 5 6 7
6. Write a C program that prints the following pattern using for loop
1
2 2
33 3
4 4 4 4
7. Write a C program to evaluate the following investment equation:
V= P(1+r)n
78
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
We have already known loops are used to perform a set of operations repeatedly until the control
variable fails to satisfy the test condition. The number of periods a loop is repeated is decided in advance
and the test condition is written to accomplish this goal. In most cases, when performing a loop it
becomes necessary to skip a part of the loop or leave the loop as soon as a certain condition happens.
Programming C permits jump from one statement to another within a loop as well as jump out of the
loop. So it is necessary to skip some statements inside the loop or terminate the loop immediately
without checking the test condition. In such cases, break and continue statements are used. These
statements are described below with program.
BREAK STATEMENT
The break is a built-in keyword in C. The break statement allows us to departure a loop from any point
within its body, avoiding its regular termination process or expression. In practical, when the break
statement is encountered inside a loop, the loop is immediately terminated, and program control resumes
at the next statement following the loop. We have seen the use of break statement in switch statement.
The general format of break statement is simply:
break;
When loops are nested, the break would only exit from the loop containing it. This means that break
will exit only a single loop. The break statement can also be used in while, do-while, and for loops. The
use of break statement procedure is illustrated in figure 5.5.1.
while(Test-condition) do
{ {
…………… ………………
…………… if(condition)
if(condition) break;
break; ……………….
………… ……………….
} }while(Test-condition);
…………………… …………………………
(a) break in while loop (b) break in do-while
79
School of Science and Technology DCSA Program
Entry loop
False
Test condition
of loop
True
Yes
break?
No
con
Remaining body of
loop Exit loop
con
Figure 5.5.2: Flowchart of break statement
When the break statement is encountered inside a loop, the loop is immediately
terminated, and program control resumes at the next statement following the loop
Program 5.5.1 Write a C program that calculates sum and average until user enters positive
number. When enter negative number program will be terminated.
# include <stdio.h>
#include<conio.h>
void main()
{
int i;
float number, sum = 0.0, average=0.0;
80
School of Science and Technology DCSA Program
break;
sum + = number;
}
average = sum/(i-1);
printf("Total Sum = %.2f\n",sum);
printf("Average is = %.2f",average);
getch();
}
…………………………………………………………………………….......
Output
The program calculates maximum 10 Numbers.
The program will terminate, if enter negative number.
Enter a n1: 10
Enter a n2: 20
Enter a n3: 30
Enter a n4: -3
Total Sum = 60.00
Average is = 20.00
Program 5.5.2 Write a C program that takes numbers from user until enter 15.
# include <stdio.h>
#include<conio.h>
void main()
{
int number ;
printf("Enter numbers one by one :");
for ( ; ; )
{
scanf("%d" , &number) ;
if ( number = =15 )
break ;
}
printf("Your last Entered number is: %d \n",number);
printf("End of an infinite loop...\n");
getch();
}
…………………………………………………………………………………
Output
Enter numbers one by one :10
100
456
789
15
Your last Entered number is: 15
81
School of Science and Technology DCSA Program
CONTINUE STATEMENT
The continue is a built-in keyword in C. Throughout the loop operations, it may be essential to skip a
part of the body of the loop under certain conditions. Like break statement C supports another statement
called the continue statement. The continue statement is used to avoid the remainder of the current
pass through a loop. However, when a continue statement is encountered, then the loop does not
terminate. This means that, the continue statement causes the loop to be continued with the next
iteration after skipping any statements in between. Actually, continue statement tells the compiler “Skip
the following statements and continue with the next iteration.” The general format of continue statement
is:
continue;
The continue statement is also used in different types of loops like while, do-while and for loops. The
use of continue statement in different loops are illustrated in following 5.5.3 figure. The continue
process is shown with an arrow line in figure 5.5.3.
while(Test-condition) do
{ {
…………… …………………
…………… …………………
if(condition) if(condition)
continue; continue;
…………… ……………….
…………… ……………….
} }while(Test-condition);
In while and do-while loops, continue causes the control to go directly to the Test-condition and then
to continue the iteration process, on the other hand in for loop, the increment/decrement section of the
loop is performed before the Test-condition is assessed.
82
School of Science and Technology DCSA Program
Test condition
of loop
False
True
Yes
continue?
con
No
Exit loop
Remaining body of
loop
continue statement tells the compiler “Skip the following statements and continue with
the next iteration”
Program 5.5.3 Write a C program that calculate sum of maximum 10 numbers. Negative
numbers are skipped from calculation.
#include <stdio.h>
#include<conio.h>
void main()
{
int i;
float number, sum = 0.0;
printf("Enter 10 Numbers.\n");
printf("Negative number is skipped from calculation.\n");
for(i=1; i <= 10; ++i)
{
printf("Enter a number n%d: ",i);
scanf("%f",&number);
/*If user enters negative number, loop is terminated*/
if(number < 0.0)
{
continue;
}
sum += number;
}
printf("Total Sum = %.2f",sum);
getch();
}
………………………………………………………………………………….
83
School of Science and Technology DCSA Program
Output
Enter 10 Numbers.
Negative number is skipped from calculation.
Enter a number n1: 10
Enter a number n2: 20
Enter a number n3: -90
Enter a number n4: 40
Enter a number n5: 50
Enter a number n6: 46
Enter a number n7: 78
Enter a number n8: 90
Enter a number n9: 34
Enter a number n10: 23
Total Sum = 391.00
if(i%2==1)
x+=i;
else
x--;
printf("%d ",x);
break;
}
printf("\nx=%d",x);
}
2. what will be the output of the following program segment:
#include <stdio.h>
#include<conio.h>
void main()
{
int i = 0,j,x = 0;
for(i = 0;i<5;++i)
{
for(j = 0;j<i;++j)
x += (i + j - 1);
printf("%d ",x);
break;
}
printf("\nx = %d",x);
}
3. what will be the output of the following program segment:
void main()
{
84
School of Science and Technology DCSA Program
int i=0,x=0;
for(i=1;i<10;++i)
{
if(i%2 = =1)
x+=i;
else
x--;
printf("%d ",x);
continue;
}
printf("\nx=%d",x);
}
Summary
Summary
In this lesson
We have learned about break statement with its syntax.
We have also learned about continue statement with its syntax.
ASSIGNMENT
85
School of Science and Technology DCSA Program
4. In while and do-while loops, continue causes the control to go directly to the
Test-condition.
Exercises
1. Why are break and continue statements used in program?
2. Mention the benefits of break statement with its flowchart.
3. Explain the uses of break statement in different types of loops.
4. Explain the uses of continue statement in different types of loops.
5. Describe distinguish between break and continue statement with an example.
86
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
GOTO STATEMENT
In the previous lessons, we have already learned the uses of different types of statements those are used
to directly exit or continue the execution of statements in different types of loops. Another statement
that is used in C program to transfer the control one place to another place of a program is known as
goto statement.
The goto statement is used to change the normal sequence of C program execution by transferring
control to any place of the program. Since, the goto statement can transfer the program control to any
place in a program, so it is convenient to provide branching within a loop.
This statement is also used to exit from deeply nested loops when an error occurs. Actually, goto
statement provides an unconditional jump from the 'goto' to a labeled statement in the same function.
The general form or syntax of goto statement is: Target statement
goto Label_name;
Here, Label_name is an identifier that is used to label the target statement to which control will be
transferred. The Label_name can be any ordinary text except C keyword and it can be set anyplace in
the C program.
An important note that, target statement must be labeled and Label_name must be followed by a colon
(:). Therefore the target statement will seem as:
Label_name:
Statement(s);
Every labeled statement within the program must have a unique label, which is no two statements can
have the same label. Jumping within and exiting from the loops with goto statement is shown in
following figure 5.6.1.
87
School of Science and Technology DCSA Program
Figure 5.6.1 Jumping within and exiting from the loops with goto statement
Label 1 Statement(s) 1
Label 2 Label 3
Statement(s) 2
Label 3 Statement(s) 3
The goto statement is used to change the normal sequence of C program execution by
transferring control to any place of the program
Program 5.6.1 write a C program that evaluate the following series using goto statement
𝟏
= 𝟏 + 𝒙 + 𝒙𝟐 + 𝒙𝟑 + … … … … … … … … … … … + 𝒙𝒏 for -1< x <1 to evaluate to 0.01 percent
𝟏−𝒙
accuracy. Goto statement is used to exit the loop.
88
School of Science and Technology DCSA Program
#include <stdio.h>
#include<conio.h>
#define Loop 100
#define accuracy 0.0001
void main()
{
int n;
float x,term,sum = 0.0;
printf("Enter the value of x: ");
scanf("%f",&x);
for(term =1,n = 1;n <= Loop; ++n)
{
sum += term;
if(term < = accuracy)
goto output; /* Exit from loop*/
term*=x;
}
printf("\n Final value of n is not sufficient \n");
printf("To achieve desired accuracy\n");
goto end;
output:
printf("\n Exit from loop \n");
printf("SUM = %f; No. of terms = %d\n", sum,n);
end:
;
}
……………………………………………………………………………...
Output
Enter the value of x: .21
Program 5.6.2 write a C program that demonstrate the inner and outer loop using goto
statement.
#include <stdio.h>
void main()
{
int p, q;
for ( p = 0; p < 5; p++ )
{
printf( "Outer loop executing. p = %d\n", p );
for ( q= 0; q < 2; q++ )
{
printf( " Inner loop executing. q = %d\n", q );
if ( p == 5 )
goto stop;
}
}
89
School of Science and Technology DCSA Program
stop:
printf( "Jumped to stop. p = %d\n", p );
}
……………………………………………………………………………..
Output
Outer loop executing. p = 0
Inner loop executing. q = 0
Inner loop executing. q = 1
Outer loop executing. p = 1
Inner loop executing. q = 0
Inner loop executing. q = 1
Outer loop executing. p = 2
Inner loop executing. q = 0
Inner loop executing. q = 1
Outer loop executing. p = 3
Inner loop executing. q = 0
Inner loop executing. q = 1
Outer loop executing. p = 4
Inner loop executing. q = 0
Inner loop executing. q = 1
Loop exited. p = 5
Jumped to stop. p = 5
Summary
In this lesson
We have learned about goto statement with its syntax.
We have also learned how a goto statemet works in program.
90
School of Science and Technology DCSA Program
ASSIGNMENT
Exercises
1. Why is goto statement used in programming C?
2. Mention the benefits of using goto statement in C.
3. Explain goto statement with its syntax and discuss its flowchart.
4. Describe the difference among break, continue and goto statements with proper example.
91
School of Science and Technology DCSA Program
In the previous lessons you have learned about the programming structure, decision making
procedure, how to write statements, as well as different types of conditional statements, branching
statements and various types of loops. In this unit you will learn about definition of an array,
declaration and initialization of an array, various types of arrays and its applications and also how to
handle arrays. On the other hand you also understand how strings are declared, initialized as well as
how strings are handled using C library functions. In C programming language the array is very
useful data structure.
Timeframe
How long ?
Unit Structure
92
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
INTRODUCTION TO AN ARRAY
An array is a one kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of same type of data. In general it is often more
useful to think of an array as a collection of variables of the same type. On the other hand we also define
that an array is a sequence of data item of homogeneous value.
Practically, in C programming language, one of the frequently rising problems is to handle similar types
of data. For instance, if the user or programmer want to store marks of 200 students. Generally this can
be done by creating 200 variables individually but, this process is rather tedious and impracticable. This
type of problem can be handled using arrays. All elements of any given array must be of the same type
i.e., we can’t have an array of 10 numbers, of which 5 are integer type (int data type) and 5 are float
type. Instead of declaring individual variables, such as marks0, marks1, marks2, marks3 …... and
marks199, you can declare one array variable such as marks and use marks[0], marks[1],marks[2]
,marks[3] and ..., marks[199] to represent individual variable. A particular component or element in an
array is accessed by an index.
An array must be declared before it can be used in the program. In general, in C programming
language an array declaration procedure is as follows:
93
School of Science and Technology DCSA Program
Study skills
Solution:
B. We know that an array is stored only same type of data and every element
is accessed by array index.
Initializing of an array is very simple in C programming. The initializing values are enclosed within the
curly { } braces in the declaration and placed following an equal sign after the array name. In C
Language, an array starts at position 0. The elements of the array occupy adjacent locations in memory.
C Language treats the name of the array as if it were a pointer to the first element. Any item in the array
can be accessed through its index, and it can be accessed anywhere using program.
INITIALIZATION EXAMPLE
Here is an illustration which declares and initializes an array of five student’s marks of type integer
(int).
int marks[5]={50,80,30,40,70};
Array can also be initialized after declaration. In the following example, that demonstrates the
declaration and initialization of an array.
int age[5];
age[0]=50;
age[1]=70;
age[2]=60;
age[3]=40;
age[4]=30;
All arrays have 0 as the index of their first element which is also called the base index and the last
index of an array will be total size of the array minus 1. The pictorial representation of the array we
discussed above is shown in below
age[0] age[1] age[2] age[3] age[4]
50 70 60 40 30
94
School of Science and Technology DCSA Program
Solution:
C. As per rule of array we know that array is stored same type of data. Students
CGPA is float type number that is float type data. So if we store float type value
of an array we required float type of array declaration.
Summary
Summary
In this lesson
We have covered about C language array and its declaration.
Moreover we have learned some example of initialization procedure of an array.
Wealso have understood that how an array is presented graphically.
ASSIGNMENT
1. Suppose you are a programmer of a firm. Your firm has 10 employees. Now
declare and initialization an array named “Salary” to store employee’s salary.
……………………………………………………………………………….
2. Represent the array as graphically considering the activity 1
………………………………………………………………………………
Assignment
Assessment
Fill in the blanks
95
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
CLASSIFICATION OF ARRAY
We know that Array is a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. It consists of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.
Generally array is two types such as:
i. One dimensional (1D) Array
ii. Two dimensional (2D) Array
Two types of arrays: One dimensional (1D) and Two dimensional (2D).
One dimensional array is defined with a single subscript. In the one dimensional array, the size is
specified by a positive integer (greater than 0) enclosed in single square [ ] brackets.
In general, the declaration form of one-dimensional array is expressed as
data-type array-name[array-size];
Where data-type is the valid data type in C and array-name is the user defined array name and array-
size is a positive valued integer expression, which indicates the number of array elements.
EXAMPLE
int numbers[5];
96
School of Science and Technology DCSA Program
One dimensional (1D) array is also known as simple array. The initialization procedure is also very
easy. Whenever we declare an array, we initialize that array directly at compile time. Initializing 1D
array is called as compiler time initialization if and only if we assign certain set of values to array
element before executing program.
In the Specified Directly method, we try to specify the array Size directly as follows:
int numbers[10]={20,40,100,50,30,250,450,80,70,300};
float numbers[5]={30.00,40.00,50.00,60.00,90.00};
In the Specified Indirectly method, we do not provide size to an array but instead we provide set of
values to the array. The example of this method is as follows:
int number[ ]={20,40,100,50,30,250};
In this cases, compiler counts the number of elements written inside pair of braces { } and determines
the size of an array. In this example, after counting the number of elements inside the braces { }, the
size of array is considered as 6 during complete execution. This type of initialization scheme is also
called as “Compile Time Initialization“.
In Specified Directly method, specify the array Size directly. In Specified Indirectly method
do not provide size to an array.
97
School of Science and Technology DCSA Program
Here a is the array name and 0, 1, 2…………..n-1 is the memory location number. In an one
dimensional array the first location is 0, second location is 1, third location is 2 and so on and last
location is n-1. This means that the first value is stored in location 0, second value is stored in location
1 and third value is stored in location 2 and so on and last value is stored in location n-1.
Now if we declare and initialize the following array with the name “numbers” with five integer values
then memory representation in figure 4.2.2 would be as follows:
int numbers[5];
numbers[0]=100;
numbers[1]=200;
numbers[2]=400;
numbers[3]=250;
numbers[4]=500;
Programmatically, one of the nice things is that you can use a loop to manipulate or insert each element
to one dimensional array. When an array is declared, the values of each element are not set to zero
automatically. In some cases you want to initialize the array.
98
School of Science and Technology DCSA Program
The following example (Program-6.2.1) illustrates insertion procedure of 10 numbers from the user in
to the one dimensional array.
#include <stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int numbers[ 10 ]; /* numbers is an array of 10 integers */
int i;
printf(“Enter the ten numbers:\n”);
for ( i = 0; i < 10; i++ )
{
scanf(“%d”,& numbers [ i ]); /* insert elements in the numbers array */
}
getch();
}
…………………………………………………………………………………………..
Output
Enter the ten numbers:
10
50
48
30
400
33
456
678
100
500
Programmatically, one of the nice things is that you can use a loop to print or display each element from
one dimensional array.
The following example (Program-6.2.2) illustrates insertion procedure of 10 numbers from the user in
to the one dimensional array as well as display or print stored numbers from array.
Program 6.2.2: Write a program that display or print elements from an array.
#include <stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int numbers[ 10 ]; /* numbers is an array of 10 integers */
int i,j;
printf(“Enter the ten numbers:\n”);
for ( i = 0; i < 10; i++ )
{
99
School of Science and Technology DCSA Program
#include <stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int numbers[ 10];
int i,j,sum=0;
printf(“Enter the 10 numbers:\n”);
for ( i = 0; i < 10; i++ ) {
scanf(“%d”,& numbers [ i ]);
}
for (i = 0; i < 10; i++ )
{
sum=sum+ numbers[i];
}
printf(“The summation of ten numbers is: ”);
100
School of Science and Technology DCSA Program
printf(“%d”, sum);
getch();
}
………………………………………………………………………………….
Output
Enter the 10 numbers:
10
20
30
40
50
60
70
80
90
100
The summation of ten numbers is: 550
Program 6.2.4 Write a program to calculate average of n integer numbers, which are given by
user.
#include <stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int numbers[ 100];
int i,j,n,sum=0,
float average=0.0;
printf("Enter the value of n:");
scanf("%d",&n);
printf("Enter the n numbers:\n");
for ( i = 0; i < n; i++ )
{
printf("Enter the %d number:",i+1);
scanf("%d",& numbers [ i ]);
printf(“\n”);
}
for (j = 0; j < n;j++ )
{
sum=sum+ numbers[j];
}
average=sum/n;
printf("\nThe average value is:%f ", average);
getch();
}
……………………………………..…………………………………………..
Output
Enter the value of n: 5
Enter the n numbers:
Enter the 1 number:10
Enter the 2 number:20
Enter the 3 number:30
Enter the 4 number:40
101
School of Science and Technology DCSA Program
#include <stdio.h>
#include<math.h>
#include<conio.h>
void main ()
{
clrscr();
long int a[ 100];
long int i,sum=0;
for ( i = 2; i <= 100; i=i+2){
sum=sum+pow(i,2);
}
printf("Summation of the series is:%ld",sum);
getch();
}
…………………………………………………………………………………
Output
Summation of the series is: 171700
Program 6.2.6 Write a program to find out the greatest number from n numbers.
#include <stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int a[ 100],i,n,max=0;
printf("Enter the value of n\n:");
scanf(“%d”,&n);
max=a[0];
for(i=0;i<n;i=i+1){
printf("Enter the %d number:",i+1);
scanf(“%d”,&a[i]);
printf(“\n”)
}
for ( i = 1; i <=n; i=i+1){
if(max<a[i]){
max=a[i];
}
}
printf("Greatest Number is:%d",max);
getch();
}
……………………………….………………………………………………..
Output
Enter the value of n: 5
Enter the 1 number:20
Enter the 2 number:400
102
School of Science and Technology DCSA Program
Summary
Summary
In this lesson
We have covered about 1D array and its declaration and initialization.
We also have understood that how 1D array is presented graphically as well as we have seen
that 1D array memory representation and some 1D example
ASSIGNMENT
1. Write a program in C, which finds out the minimum number from 200 integer
numbers.
2. Write a program in C, that calculates the summation of all even numbers from 100
integer numbers.
3. Write a program in C that determines the summation of following series
Assignment
11+22+33+44+……………………………….nn
Assessment
Fill in the blanks
Exercises
103
School of Science and Technology DCSA Program
scale
Lesson-3 Familiar With Two Dimensional Arrays
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
Two dimensional (2D) arrays are defined with a double subscript. In the two dimensional arrays, the
size is specified by two positive integer (greater than 0) enclosed in double square [ ][ ] brackets.
Two Dimensional array stores the values in the form of matrix. Generally in 2D, one subscript denotes
the “Row” and another subscript denotes the “Column”. So, 2D arrays are generally known as matrix.
2DARRAY DECLARATION
EXAMPLE
The following declares two dimensional array called ‘matrix’ to hold total 12 integers values consisting
four rows and three columns:
int matrix[4][3];
Row Size
Array Name
104
School of Science and Technology DCSA Program
1. If we want to store five subjects numbers information’s of 5 students, then 2D array is used as
follows:
int stumarks[5][5];
2. If we want to store three items by four sales mans of a inventory management system we declare
2D array as follows:
int slalesman[4][3];
There are many ways to initialize 2D arrays. We have already described in previous section that when
we give values during one dimensional array declaration, we don’t need to mention dimension. But
that’s not the case with 2D array; you must specify the second dimension even if you are giving values
during the declaration. Some illustrations help you to initialization 2D in many ways as follows:
int totalvals [ ][ ] = {1, 2, 3 ,4,5,6,7 } /* Invalid declaration, you must specify second dimension*/
int totalvals [2][ ] = {1, 2, 3 ,4 } /* Invalid declaration ,you must specify second dimension */
In 2D arrays for initializing, we can also need to assign values to each element of an array using the
following syntax. In these initializations, comma (,) must be put after every initialization except last
initialization which is shown in bellow:
105
School of Science and Technology DCSA Program
1. int array[3][2] = {
{1, 4},
{5, 2},
{6, 5}
}
2. float interest[4][3]={
{1.50, 1.20, 0.02},
{0.50, 2.50, 4.00},
{3.00, 2.50, 1.10},
{1.10, 1.40, 2.60}
};
2D arrays are stored in memory as shown in Fig. 2. A two-dimensional array can be considered as a
table which will have x number of rows and y number of columns. The memory representation of a 2D
array a, which contains four rows and three columns can be shown as follows –
int a[4][3];
Column 0 Column 1 Column 2
Row 0 a[0][0] a[0][1] a[0][2]
A two-dimensional array can be considered as a table which will have x number of rows and
y number of columns
In 2D arrays are stored in contiguous memory location row wise that is, array element of first location
a[0][0] can be stored any memory location (i.e., address), then next element a[0][1] will be stored next
memory location and so on. Since elements are stored row wise, so after elements of first row are stored
in appropriate memory location, elements of next row get their corresponding memory locations. For
instance, if array element of first location a[0][0] is stored in memory address 5000, then next array
element a[0][1] is stored next memory location like 5002. Here next memory address is calculated as
follows:
106
School of Science and Technology DCSA Program
Here, we declare integer array a so each element requires 2 bytes of memory, for float data type it is
required 4 bytes of memory and so on. So ultimate calculation is as follows:
For figure 6.3.2, the full memory location or address calculation is presented in the following table 2:
Programmatically, one of the nice things is that you can use two loops to manipulate or insert elements
to 2D array. When an array is declared, the values of each element are not set to zero automatically. In
some cases you want to initialize the array. The following example Program 6.3.1 illustrates insertion
procedure of 3 subject’s marks of 5 students in to the 2D array. The marks are given by user.
#include <stdio.h>
#include<conio.h>
void main ()
107
School of Science and Technology DCSA Program
{
clrscr();
int stumarks[3][5];
int row,col;
printf("Enter the 3 subjects mark of 5 students:\n");
for ( row = 0; row < 3; row++ )
{
for(col=0;col<5;col++) /* insert marks in to the 2D array */
{
printf("Enetr the marks of %d subject of %d student: ",row+1, col+1);
scanf("%d",&stumarks[row][col]);
}
}
getch();
}
…………………………………………………………………………………………..
Output
Enter the 3 subjects mark of 5 students:
Enetr the marks of 1 subject of 1 student: 50
Enetr the marks of 1 subject of 2 student: 60
Enetr the marks of 1 subject of 3 student: 70
Enetr the marks of 1 subject of 4 student: 44
Enetr the marks of 1 subject of 5 student: 56
Enetr the marks of 2 subject of 1 student: 78
Enetr the marks of 2 subject of 2 student: 56
Enetr the marks of 2 subject of 3 student: 55
Enetr the marks of 2 subject of 4 student: 34
Enetr the marks of 2 subject of 5 student: 78
Enetr the marks of 3 subject of 1 student: 88
Enetr the marks of 3 subject of 2 student: 90
Enetr the marks of 3 subject of 3 student: 54
Enetr the marks of 3 subject of 4 student: 55
Enetr the marks of 3 subject of 5 student: 76
Programmatically, one of the nice things is that you can use two loops to print or display or access each
element from 2D array. The following example Program 6.3.2 illustrates display or print stored
numbers from 2D array.
Program 6.3.2 Write a program to display or print store numbers from 2D array
#include <stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int stumarks[2][3];
int row,col;
printf("Enter the 2 subjects marks of 3 students:\n");
for ( row = 0; row < 2; row++ )
{
for(col=0;col<3;col++)
{ /* insert marks in to the 2D array */
108
School of Science and Technology DCSA Program
Program 6.3.3 Write a program in C that takes 12 integer numbers from user and display them
as 4X3 matrix.
#include<stdio.h>
#include<conio.h>
109
School of Science and Technology DCSA Program
void main()
{
clrscr();
int numbers[4][3];
int row,col;
printf("Enter the 12 values:\n");
for(row=0;row<4;row++)
{
for(col=0;col<3;col++)
{
scanf("%d",&numbers[row][col]);
}
}
printf(" Matrix as follows:\n ");
for(row=0;row<4;row++)
{
for(col=0;col<3;col++)
{
printf("%d ",numbers[row][col]);
}
printf("\n");
}
getch();
}
……………………………………………………………………………………….
Output
Enter the 12 values:
10
20
30
40
50
60
70
80
90
45
67
88
Matrix as follows:
10 20 30
40 50 60
70 80 90
45 67 88
Program 6.3.4 Write a program in C, that calculates the summation of all values of a 3X3
matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int numbers[3][3];
110
School of Science and Technology DCSA Program
int row,col,sum=0;
printf("Enter the 9 values:\n");
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
{
scanf("%d",&numbers[row][col]);
}
}
printf(" Summation of all values of 3X3 Matrix is: ");
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
{
sum=sum+ numbers[row][col];
}
}
printf("%d",sum);
getch();
}
……………………………………………………………………………………..
Output
Enter the 9 values:
10
20
30
40
50
60
70
80
90
Summation of all values of 3X3 Matrix is: 450
Program 6.3.5 Write a program in C that calculates of total items of individual salesmans
according to following table:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int salsmans[3][3];
int row,col,sum=0;
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
{
111
School of Science and Technology DCSA Program
Summary
Summary
In this lesson
We have covered about C language 2D array and its declaration.
Moreover we have learned how 2D is initialized.
We also have understood that how 2D array is presented graphically as well as we have seen
that 2D array memory representation.
We also have seen some 2D example, which knowledge is helped to implement another such
problems.
112
School of Science and Technology DCSA Program
ASSIGNMENT
4. The daily maximum temperature recorded in 5 cities during the month of December
have been tabulated as follows:
City/day 1 2 3 4 …………………….. 30 31
1 30 33 32 25 ………………….. 27 29
2 28 29 30 31 ………………….. 30 29
3 25 25 27 29 ………………….. 29 29
. …………………..
.
.
9
10 25 26 27 27 ……………….. 28 28
Now write a program in C, to read the table elements into 2D array named
“Temperature”, and to find the city and day corresponding to
a) The highest temperature.
b) The lowest temperature.
Write a program to read the data from the above table and determine the following:
a) Total marks obtained by each student
b) The highest marks in each subject and the student id of the student who scored it.
c) The student who obtained the highest total marks.
5 4 5 3 4 2
and
A 3 2 6 B 3 1 3
2 3 7 4 5 2
Now write a program in C, that will read the values of elements of A and B and
produce the product matrix C.
113
School of Science and Technology DCSA Program
Assessment
Write “T” for true and “F” for false for the following sentences
Assessment 1. Two dimensional (2D) arrays are defined with a double subscript
2. 2D arrays are generally known as matrix.
3. In 2D initialization, array size must be initialized before used.
1. Identify errors, if any, in each of the following array declaration statements:
i. int score(100);
ii. float values[10,15];
iii. float average[50],[30];
iv. char names[15]
v. int summation[ ];
2. Identify errors, if any, in each of the following array initialization statements:
i. static int num[ ]={0,0,0,0,0};
ii. float items[2][3]={2,3,4,5,6,7};
iii. static char test[ ]={‘N’, ‘A’, ‘M’, ‘E’};
iv. double
salary[2,4]={(30.98,45.00,4.00,50.00),{100.00,3.00,50.89,40.00
}};
v. float result[10]=0;
vi. for(i=1;i<=5;j++)
{
for(k=0;k<=5;i++)
a[i][j]=0;
}
Exercises
114
School of Science and Technology DCSA Program
scale
Lesson-4 Introduction to Strings
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
STRINGS
Usually, a string is a sequence of characters. In C language, we can define that, “Strings are array of
characters terminated by a null character '\0' ”. Actually, strings are one dimensional array of
characters. In such cases, strings are operated by programmers according to the requirement of
problems. Any group of characters defined between double quotation marks (“ ”) is a constant string.
A constant string example is given below:
115
School of Science and Technology DCSA Program
A string variable is any suitable C variable name and is all the time declared as an array. We have
already known about data types in C. In C language string data type is not supported. For this reason,
we cannot declare string using string data type. So instead of we use array of type character to create
string. The general structure or form of declaration of a string variable is as follows:
char String_Variable_name[size];
Here, char is the data type, which is only used for string declaration, String_Variable_name is the user
defined array name and size determines the number of characters in the String_Variable_name.
DECLARATION EXAMPLE
Character arrays are initialized when they are declared. In C programming language a character array
to be initialized in either of the following two structures:
116
School of Science and Technology DCSA Program
Solution:
C, E, and G are the correct statements ( Remember your study)
In C programming language, two concepts are imagined to read strings from user or terminal such as
(i) Reading words and (ii) Reading a line of text
Reading Words
The well-known input function scanf( ) is used with %s format specification to read in a string of
characters from user or terminal.
char cityname[12];
scanf(“%s”,cityname);
However, the problem with this scanf( ) is that, it terminates its input on first white space it finds. Here
white space means that, blanks, tabs, carriage return (Enter), form feeds, and new line. For that reason,
if the following line of text is typed by user at the terminal,
DHAKA CITY
Then only the string DHAKA will be read in to the array cityname. As a result, the string would get
cut off. The blank space after the word DHAKA will terminate the string.
In this situation, if you want to read the complete line using scanf( ) function, then you may use more
than one character arrays as you need.
It is noted that, in the case of character arrays, the ampersand sign (&) is not used before the variable
name. The scanf( ) function automatically terminates the string that is read with a null character.
In the case of character arrays, the ampersand sign (&) is not used before the variable
name.
117
School of Science and Technology DCSA Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char uniname1[40];
char uniname2[40];
char uniname3[40];
printf("Enetr your Text: \n");
scanf("%s",uniname1);
scanf("%s",uniname2);
scanf("%s",uniname3);
printf("\n");
printf("After Insertion text: \n");
printf("%s",uniname1);
printf(" ");
printf("%s",uniname2);
printf(" ");
printf("%s",uniname3);
getch();
}
…………………………………………………………………………………………
Output
Enetr your Text:
Bangladesh Open University
After Insertion text:
Bangladesh Open University
Or
If you enter the input as follows:
118
School of Science and Technology DCSA Program
Program 6.4.2 Write a program to read a line of text containing a series of words from the user.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char subject[81];
char character;
int count=0;
printf("Enter your Text: Press<Return/Enter> at end \n");
do{
character=getchar();
subject[count]=character;
count++;
}while(character!='\n');
count=count-1;
subject[count]='\0';
printf("After Inserting line of Text: \n");
printf("\n%s\n",subject);
getch();
}
………………………………………………………………………………….
Output
Enter your Text: Press<Return/Enter> at end
Programming C is interesting subject
After Inserting line of Text:
Programming C is interesting subject
Enter your Text: Press<Return/Enter> at end
I am a man, I am a student of BOU. My subject is DSCA-1302.
After Inserting line of Text:
I am a man, I am a student of BOU. My subject is DSCA-1302
gets( ) and puts( ) Functions
We have already seen the problems of scanf( ) function in previous section. To solve this scanf()
function problem, we use the function gets(). This is the built-in standard library function, which is
belongs to stdio.h header file. This function receives series of characters words that is this function
waits until the user hits the enter key before it cuts off the input. This function writes a string to stdout
up to but not including the null character. Normally a newline character is appended to the output. The
general syntax of gets() is as follows:
gets(char_array_variable);
gets() function takes just one argument such as a char pointer, or the name of a char array, it
automatically prints out a newline character, making the output a little neater.
puts() function is similar to gets() function. It is also a built-in function and belongs to stdio.h header
file. It has also one argument such as a char pointer or the name of a char array. This also automatically
adds a newline character after printing out the string. This is the alternative of printf() function.
Sometimes this can be a disadvantage, so printf() could be used instead. The general syntax of puts() is
as follows:
puts(char_array_variable);
119
School of Science and Technology DCSA Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char names[100];
printf("Type your full name: ");
gets(names);
printf("\n\n");
puts(names);
getch();
}
Summary
Summary
In this lesson we have
Learned about Strings variable and its declaration and its initialization.
Also understood how strings are read from user and disply to screen.
Uunderstood significance of gets( ) and puts( ) library functions.
ASSIGNMENT
1. Find out the errors and mention why errors are occurred for the following:
A. c=c-1;
line[c]= ‘\o’
printf(“%d”,line);
B. string names[20];
Assignment
scanf(“%s”,&name[i]); printf(“%s”,&names);
C. char dept[5]={“‘D’, ‘C’ ‘S’ ‘A’”};
while(1)
{
char val=puts(dept);
}
D. char uniname[10]= “C PROGRAMMING”;
printf(%s,uniname);
2. What will be the output for the following program segments:
A. char city[9]= “NEW YOURK”;
printf(“%s”,city);
B. void main()
{
char word1[40]= “Oxford”, word2[40]= “University”,word3[40]=
“London”;
printf(“\n”); printf(“output will be:\n”);
printf(“%s”,word1);
printf(“ ”);printf(“%s”,word2);
printf(“ ”);
printf(“%s”,word3);
}
120
School of Science and Technology DCSA Program
Assessment
Write “T” for true and “F” for false for the following sentences
1. Strings are one dimensional array of characters.
Assessment 2. In C language string data type is supported.
3. In C programming language, it permits us to initialize a character array
without identified the number of elements.
4. When the new line character (‘\n’) is entered, then the reading is terminated
and the null character (‘\0’) is inserted at the end of the string.
2. If you want to print a string with double quote, what is the correct sysntax?
a) printf(“open university”) b) printf(“\n open university”);
c) printf(“\ “open university\” ”); d) printf(“\open university/” ”);
3. gets() and puts() function are belong to
a) ctype.h b) string.h c) stdio.h d) math.h
4. scanf( ) function is used to read—
a) A line containing more than one word.
b) A first single word from a line
c) Two word from a line
d) None of these
5. gets() and puts() functions have—
a) Only one argument b) Two arguments
c) No arguments d) None of these
6. Which initialization is valid?
a) int name[ ]= “DCSA”;
b) char book[ 5]= {“D,C,S,A”};
c) char book[4]= “DCSA”;
d) char book[5]={‘D’, ‘C’, ‘S’, ‘A’, ‘\0’};
7. The ampersand sign (&) is not used before
a) integer variable name b) the string variable name
c) float type variable name d) char type variable name
Exercises
1. What is string? How do you declare and initialize strings in C programming language?
2. Mention the problems of scanf( ) function with suitable example.
3. Explain the procedure of reading strings from user with proper example.
4. Discuss the significance of gets( ) and puts( ) functions with an example.
5. Write a program to read a line of text containing a series of words from the user.
121
School of Science and Technology DCSA Program
scale
Lesson-5 Understanding String Handling Functions
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
Basically a standard library in computer programming is the library that made obtainable across
implementations of a programming language. These libraries are traditionally expressed in
programming language specifications. Standard library functions in C programming are built-in
functions. Many data definitions and function prototypes of these functions are written in their
respective header file. However, some of the commands in C language are not really commands at all,
but these are functions, is called library functions. For instance, we already know some library functions
such as printf( ), scanf( ), rand( ), gets( ), puts( ) etc. These standard functions are included with C
compilers and while these are not really part of the language, but these are not rewritable.
Naturally, strings are habitually needed to be operated or manipulated by programmer or user according
to the need of problems. All strings manipulation process can be done manually by the programmer but,
this makes programming complex and large. To solve this problem, the C library sustains a large
number of string handling functions. Sting manipulation library functions are belongs to “string.h”
header file. So when you use string library functions in your program, you must be included “string.h”
header file.
122
School of Science and Technology DCSA Program
We will describe how each of these functions can be used in the processing of strings.
strcat( ) Function
strcat() means string concatenation. This function is used to concatenate (Join) two strings together.
This function takes two arguments, i.e., two strings and resultant string is stored in the first string
specified in the argument.
The general form of strcat( ) function is as follows:
strcat(string1, string2);
Here, string1 and string2 are character arrays which are already described in previous lesson. After
executed strcat( ) function , string2 is appended to string1. So the resultant value is stored in string1. In
this case removing the null character at the end of string1 and placing string2 from there. C language
also permits nesting of strcat() functions which is shown in example-2. Nesting function syntax is as
follows:
strcat(strcat(string1,string2),string3);
The nesting function is allowed and concatenates all the three strings together and the resultant string
is stored in string1.
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main( )
{
clrscr();
char string1[ ]="Welcome Bangladesh Open ";
char string2[ ]=" University";
strcat(string1,string2);
puts(string1);
getch();
}
………………………………………………………………………..
Output:
Welcome Bangladesh Open University
123
School of Science and Technology DCSA Program
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main( )
{
clrscr();
char string1[ ]="Welcome Bangladesh Open ";
char string2[ ]="University";
char string3[ ]=" DCSA-1301";
strcat(strcat(string1,string2),string3);
printf("%s",string1);
getch();
}
……………………………………………………………………………
Output:
Welcome Bangladesh Open University DCSA-1301
strcmp() Function
strcmp( ) means string compare. This function is used to compare two stings, recognized by the function
arguments and has two arguments string1 and string2 and the strcmp() function returns an integer value
as follows:
if Return value < 0 then it indicates that string1 is less than string2.
if Return value > 0 then it indicates that string1 is greater than string2.
if Return value = 0 then it indicates that string1 is equal to string2.
strcmp(string1,string2);
here, string1 and string2 may be character type string variables or string constant. Some examples are
as follows:
strcmp(name1,name2);
strcmp(name1, “AMRAN”);
strcmp(“RAM”, “ROM”);
Some examples are given below:
Program 6.5.3 Write a C program to compare two strings
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main ()
{
clrscr();
char string1[15]= “abcdef”
char string2[15]= “ABCDEF”;
int ret;
ret = strcmp(string1, string2);
if(ret < 0)
124
School of Science and Technology DCSA Program
{
printf("string1 is less than string2");
}
else if(ret > 0)
{
printf("string1 is greater than string2");
}
else
{
printf("string1 is equal to string2");
}
getch();
}
…………………………………………………………………………….
Output:
string1 is greater than string2
Program 6.5.4 Write a program to compare two names either equal or not
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
clrscr();
char name1[30],name2[30];
printf("Enter first name as string: ");
gets(name1);
printf("\nEnter second name as string: ");
gets(name2);
if(strcmp(name1,name2)==0)
printf("Both names are equal !!! ");
else
printf("Name are unequal !! ");
getch();
}
……………………………………………………………………………..
Output:
Enter first name as string: MAMUN
Enter second name as string: MAMUN
Both names are equal !!!
strcpy() Function
strcpy() means string copy. This function is used to copies one string over another string. It works like
assignment operator. It has two parameters. One is destination and another is source. Destination may
be character type array variable and source is character type array variable or c string constant. The
content of source variable or string constant is copied to the destination array variable. The general
syntax of strcpy( ) function is as follows:
125
School of Science and Technology DCSA Program
strcpy(city, “Gazipur”);
strcpy(city1,city2);
from the example, the statement-1 will assign the string “Gazipur” to the string variable city and the
statement-2 will assign the contents of the string variable city2 to the string variable city1. Here, the
size of the array city1 should be large enough to receive the contents of city2.
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
clrscr();
char city1[40];
char city2[100];
strcpy(city1, "Gazipur");
strcpy(city2, city1);
printf("Final copied string to city2 is : %s\n", city2);
}
……………………………………….........................................................
Output:
Final copied string to city2 is: Gazipur
Program 6.5.6: Write a program to read the string from user and copy the contents to another
variable
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
{
clrscr();
char str1[50],str2[50];
printf("Enter your string: ");
gets(str1);
strcpy(str2,str1);
printf("Copied string is : ");
puts(str2);
}
……………………………………………………………………………
Output:
Enter your string: C programming Subject
Copied string is : C programming Subject
strlen() Function
strlen( ) means string length. This is used to determine or count and return the number of characters in
a string. The return value is received by integer type variable. The general structure of strlen( ) is as
follows:
count = strlen(string);
126
School of Science and Technology DCSA Program
Here, string is the user provided string whose length is to be computed and count is integer type variable
which receives the value of the length of string and counting is halt when first null character (‘\0’) is
found.
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main ()
{
clrscr();
char string[50];
int count;
strcpy(string, "School of Science and Technology");
count = strlen(string);
printf("\n Length of string is: %d ", count);
}
…………………………………………………………………………….
Output:
Length of string is: 32
Solution:
A, F, and G are the correct statements ( Remember your study)
Summary
In this lesson we have
Learned about Strings library function.
Learned the syntax of string library functions.
Also understood how strings are read from user and disply to screen.
Mentioned significance of strcat( ), strcpy( ),strcmp( ) and strlen( ) functions with examples.
127
School of Science and Technology DCSA Program
ASSIGNMENT
1. Write a program that reads the 10 students name and their phone number, the
program counts the character of every students name and phone number.
2. Write a program that read your first name, middle name and last name and store
them to separate three variables and join them with space after you first name,
middle name and last name and display your full name.
Assignment
3. Write a program which will read a text and count total number of characters of
the text.
Assessment
Write “T” for true and “F” for false for the following sentences
Exercises
1. What do you mean by library function? Mention the significance of string library functions.
2. Distinguish between strcmp() and strcpy() functions with their syntax.
3. Assume str1, str2, and str3 are three string variables. Write a program to read two strings and
store these into str1 and str2 and compare whether they are equal or not. If they are not, join
them together. Then copy the contents of str1 to the variable str3. At the end, the program
should print the contents of all the three variables and their lengths.
128
School of Science and Technology DCSA Program
Functions Unit
7
INTRODUCTION
In the previous unit 6 we have learned important topics such as different types of arrays and strings
and their declarations, initializations, structures and applications. We think that, we have able to
usages of these topics when we will work on our programming fields. In this unit we will describe
about another important topic in C language like functions. Actually we have used functions earlier
in every program that we have discussed so far. We have already seen some functions like printf(),
scanf(), gets(), puts(), main(), sqrt(), strcat(), strcmp(), strlen() etc. In this unit, we will describe in
detail how a function is designed, mentioned, how two or more functions are situate together and
how functions are communicated with one another.
Timeframe
How long ?
Unit Structure
Lesson- 1 : Introduction to C functions
Lesson- 2 : Function Prototype and Definition
Lesson- 3 : Categories of Functions
Lesson- 4 : Function With No Arguments and No Return Value
Lesson- 5 : Function With No Arguments and Return Value
Lesson- 6 : Function With Arguments And No Return Value
Lesson- 7 : Functions With Arguments And Return Value
Lesson- 8 : Recursive Function
Lesson-9 : Uses of Local and Global Variables in Function
129
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
FUNCTION IN C
The C programming language is related to most contemporary programming languages in that it agrees
to the use of functions, self-controlled modules of code that receive inputs, perform computation, and
generate outputs. A function is defined as “A function is a block of code that performs a particular
task”. Every C program has at least one function, which is main(), and all the most trivial programs
can define supplementary functions. We can break up or divide up our code into separate functions.
Actually, how we divide up our code among dissimilar functions is up to our concept, but logically the
partition is such that each function performs a definite task. C functions are fundamental building blocks
in a program. Generally C programs are written using functions to improve re-usability,
understandability and to keep track on them. Elaborately we also say that “A function is a section of
code that takes information does some calculation, and returns a new piece of information based on the
parameter information. C language provides an approach in which you need to declare and define a
group of statements once and that can be called and used whenever required.
TYPES OF FUNCTION
Library functions
User defined functions
Library functions
Library functions are those functions which are defined by C library. For example printf(), scanf(),
strcat(), strlen(), gets(), puts(), sqrt() etc. If we want to use library function we just need to include
appropriate header files to use these functions. These are already declared and defined in C libraries.
130
School of Science and Technology DCSA Program
developed by the programmer or user at the time of writing a program. Actually we will describe about
the user defined functions in this unit.
A function is a block of code that performs a particular task. Every C program has at
least one function, which is main(), and all the most trivial programs can define
supplementary functions.
In practical, if the program may become too large and difficult then the task of debugging, testing and
maintaining becomes difficult. In this case, if a program is divided into more than one functional part,
then each part may be separately coded and later combined into a single unit. For removing these
complexity of a program we need user define function. Actually user defined functions are extremely
necessary for complex programs
Summary
Summary
In this lesson we have
Learned about function definition and declaration.
Learned about the user defined and libraray functions.
Also understood how a function is called in a program .
Assessment
Write ‘T’ for true and ‘F’ for false for the followings sentences
Assessment 1. printf(), scanf() are the library function.
131
School of Science and Technology DCSA Program
Exercises
1. What is function? Explain user define function definition and declaration procedure.
2. Explain the necessity of user defined function in a program.
132
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Here, data_type means the data type of arguments or parameters such as int, float, double, char etc. and
arg_1, argu_2… arg_N means that how many arguments or parameters are defined in the parameter
list.
There can be more than one argument passed to a function or none at all, and also a function does not
have to return a value. Functions that do not return values have a return type of void. Let's look at a
function prototype or declaration
133
School of Science and Technology DCSA Program
1. return-type: A function may return a value. The return-type is the data type (int, float, char,
double) of the value the function returns. If a function performs the desired operations without
returning a value, then the return_type is the keyword void.
2. function-name: function name specifies the actual name of a function. The function name is
any valid C identifier and therefore must follow the same rule of formation as other variables
in C.
3. parameter list: The parameter list declares the variables that will receive the data sent by
calling program. A parameter is like a placeholder. When a function is invoked, we pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters. These parameters are also used to send values to
calling program.
4. function-body: The function body contains a collection of statements and declaration of
variables that define what the function does. The body is enclosed within curly braces { } and
consists of three parts.
Example:
Given below is the source code for a function called summation(). This function takes two parameters
value1 and value2 and returns the summation of two values.
#include <stdio.h>
int summation(int value1, int value2); Function prototype
134
School of Science and Technology DCSA Program
void main()
{
..............................
..............................
summation( );
...........
...........
Step-1 Function Calling
}
Example:
Given below is example of a function calling process:
void main()
{
int mulvalue;
mulvalue = multiplication(20,5);
printf(“%d”, mulvalue);
}
When a program calls a function, the program control is transferred to the called function. In the above
example, when the compiler encounters a function (multiplication(20,5)) call, the control is transferred
to the function multiplication(x,y) which is already defined in program. This function is then executed
and returns a value when a return statement is encountered and then the return value is stored or assigned
to mulvalue variable.
When a program calls a function, the program control is transferred to the called
function.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void powerval( );
void main( )
{
powerval( );
getch( );
135
School of Science and Technology DCSA Program
}
void powerval( )
{
long int x,y,z;
printf("Enter the value of base (x):");
scanf("%ld",&x);
printf("\nEnter the value of power (y):");
scanf("%ld",&y);
z= pow(x,y);
printf(" \nThe power value is: %ld ",z);
}
……………………………………………………………………………………
Output
Enter the value of base (x): 5
Enter the value of power (y):2
The power value is: 25
Program 7.2.2 Write a program to calculate the summation of 5 integer numbers using function
#include<stdio.h>
#include<conio.h>
void summation( );
void main( )
{
summation( );
getch( );
}
void summation( )
{
int i,sum=0;
int summ[10];
printf("Enter 5 numbers:\n ");
for(i=0;i<5;i++)
scanf("%d",&summ[i]);
for(i=0;i<5;i++)
{
sum=sum+summ[i];
}
printf(" \nThe Summation of entered values is:= %d ",sum);
}
………………………………………………………………………………….
Output
Enter 5 numbers:
10
30
12
11
45
The Summation of entered values is:= 108
136
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned about functions prototypes and definition.
Also understood how a function is called in a program.
Understand that how user defined functions are used in program.
137
School of Science and Technology DCSA Program
ASSIGNMENT
1. Write a program to determine the greatest common divisor (GCD) and least
common multiple (LCM) of two integer number using function.
……………………………………………………………………………………..
………………………..……..…………………………………………………….
2. Write a program using function, that reads n numbers from the user and determine
Assignment
the maximum and minimum number from n numbers
………………………..……..……………………………………………………..
………………………..……..……………………………………………………..
Assessment
Exercises
1. What is function? Explain user define function definition and declaration procedure?
2. Write a program to calculate factorial value of a number using function.
3. Write a program using function, that reads n numbers from the user and determine the
maximum and minimum number from n numbers.
138
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
CATEGORY OF FUNCTIONS
We have already known that, when we write large difficult programs, it becomes difficult to maintain
track of the source code of a program. The work of functions is to divide the large program to many
separate modules based on their functionality. So a function depending on whether arguments are
present or not and whether a value is returned or not, may belong to one of the following categories:
Summary
Summary
In this lesson we have
Learned about categories of functions and its definitions
Assessment
1. Write down the function categories
….……………………………………………………………………………
Assessment ….……………………………………………………………………………
Exercises
139
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
When a function has no arguments, it does not receive data from the calling function as well as when it
does not return value, the calling function does not receive data from the called function. If a function
does not return value, we may be used keyword void as return type. The general syntax of this type of
function is as follows:
void function_name( )
{
……………………………
Statements or function body
…………………………..
}
EXAMPLE
Program 7.4.1 Write a program to check whether a number entered by user is prime or not using
function with no arguments and no return value.
#include <stdio.h>
#include<conio.h>
void prime_number( );
void main( )
{
clrscr( );
prime_number( ); /*No argument is passed to prime_number ()*/
getch();
}
void prime_number ( )
{
int number,i,flag=0;
printf("Enter positive number to check:\n");
scanf("%d",& number);
for(i=2;i<= number /2;++i)
{
if(number % i==0)
{
flag=1;
}
140
School of Science and Technology DCSA Program
}
if (flag==1)
printf("%d is not Prime Number", number);
else
printf("%d is Prime Number", number);
}
………………………………………………………………………………….
Output:
Enter positive number to check:
5
5 is Prime Number
If a function does not return value, we may be used keyword void as return type.
1. Write down the benefits of function with no arguments and no return value by your
own idea.
…….……….………………………………………….……………………………
Activity …………...…………………………………………….……………………………
…………..…………………………………………….……………………………
2. Create a function named as “power” to determine power of xy using function with
arguments and no return value concept.
………….……………………………….….……………………………………..
…..……..…………………………………..………………………………………
1. Determine the output of the following program:
void main()
{
Study skills product( );
}
void product()
{
int x = 5,p;
int y = 20;
p = x*y;
printf(“Output is:=%d”,p);
}
Summary
Summary
In this lesson we have
Learned about categories of functions with no arguments and no return value concept and its
declaration and definition.
Also understood how a function is called in a program.
141
School of Science and Technology DCSA Program
ASSIGNMENT
𝑥3 𝑥5 𝑥7
1. Write a program to evaluate f(x)= 𝑥 − 3! + 5! − 7! + − − − − − − using
function with no arguments and no return value concept.
……….…...……………………………………………………………………..
..…………..……………………………………………………………………..
Assignment
Assessment
Exercises
142
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
EXAMPLE
Program 7.5.1 Write a program to calculate average of two numbers using function with no
arguments and return value.
#include<stdio.h>
#include<conio.h>
float average( );
void main( )
{
float result;
result=average( );
printf("Average value of two numbers is: %f",result);
getch();
}
float average( )
{
int num1,num2;
float aveg,value;
printf("Enter the first Number: \n");
scanf("%d",&num1);
printf("Enter the Second Number: \n");
scanf("%d",&num2);
value=num1+num2;
143
School of Science and Technology DCSA Program
aveg=value/2;
return aveg;
}
……………………………………………………………………………………..
Output:
Enter the first Number:
10
Enter the Second Number:
15
Average value of two numbers is: 12.500000
1. Write down the benefits of function with No arguments and return value by your
own idea.
….. ……………………………………………………………………….……….
Activity ….…………………………………………………………………………………
2. Create a function named as “power” to determine power of xn+1 using function
with no arguments and return value concept.
.….………………………………………………………………………………..
………..…………………………………………………………………………..
3. Write a program to calculate the value of following formula A=2πr3 using function
with no arguments and return value concept.
………………..………………………………………………………………….
……….………..………………………………………………………………….
Summary
In this lesson we have
Learned about categories of functions with no arguments and return value concept.
Learned how a function is worked in a program.
Understood how a function is called in a program and returned value to calling function .
144
School of Science and Technology DCSA Program
ASSIGNMENT
1 1 1 1
1. Write a program to evaluate Y =1 + 2! + 3! + 4! + ⋯ + 𝑛! using function with no
arguments and return value concept.
……..………………………..………………………………………………..
………………………………………………………………………………..
Assignment 2. Write a program to calculate interest of employee loan using function with no
arguments and return value
…..………….…………………………………………………………………
…..…………………………………………………………………………….
Assessment
Exercises
1. Explain function with no arguments and return value procedure with an example.
2. Write a program to calculate factorial value of a number using function with no arguments
and return value procedure.
3. Write a program using function with no arguments and return value procedure that will
generate and print first n Fibonacci numbers.
145
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
void function_name(arguments/parameters)
{
…………………………………
Statements / function body
………………………………..
……………………………….
}
Here, arguments also known as parameters means different data type or same data type value or variable
list. There are two types of arguments such as (i) actual arguments and (ii) formal arguments. The
arguments of calling function are called actual arguments and the arguments of called function are
called formal arguments. The actual and formal parameters or arguments should match in number, type,
and order. The values of actual arguments are assigned to the formal arguments on a one to one manner,
starting with the first argument. Illustration of arguments passing between the function calling and the
called function is shown in following figure 7.6.1:
main( )
{
Statement—1; Actual arguments
Statement—2;
Calling function Function_1( a1, a2, a3,………..an);
Statement—n Arguments passing
}
Called function void Function_1(v1,v2,v3,…………vn)
{
Statement—1;
Statement—2;
} Formal arguments
146
School of Science and Technology DCSA Program
The arguments of calling function are called actual arguments and the arguments of
called function are called formal arguments
The data type should be matched between actual arguments and formal arguments. In case the actual
arguments are more than formal arguments, the extra actual arguments are discarded. On the other hand,
if the actual arguments are less than the formal arguments, the unmatched formal arguments are
initialized to some garbage values. Any mismatch in data type may also result in passing of garbage
values. Formal arguments must be valid variable names and the actual arguments may be variable
names, expressions, or constants. The variables used in actual arguments must be assigned values before
the function call is made. The following example shows the arguments passing procedure between
calling and called function.
main( )
{
………………..
…………………
Value_check(10.5,20); Calling function
…………………….
…………………….
}
void Value_check(float num1, int num2) Called function
{
…………………..
…………………..
………………….
}
In this above example, when Value_check( ) function calls with float type value 10.5 and integer type
value 20, then these values are assigned to num1 and num2 variable of called function respectively.
Formal arguments must be valid variable names and the actual arguments may be
variable names, expressions, or constants
EXAMPLE
Program 7.6.1 Write a program to calculate greatest common divisor (GCD) of two numbers
using function with arguments and no return value.
#include <stdio.h>
#include<conio.h>
void gcd(long int n1,long int n2);
void main()
{
clrscr();
long int num1, num2,temp;
printf("Enter two integers: ");
scanf("%ld %ld", &num1, &num2);
if(num1>num2)
{
temp=num1;
147
School of Science and Technology DCSA Program
num1=num2;
num2=temp;
}
gcd(num1,num2);
getch();
}
void gcd(long int n1,long int n2)
{
long int number1,number2;
number1=n1;
number2=n2;
while (n1 != 0)
{
long int r = n2 % n1;
n2 = n1;
n1 = r;
}
printf("GCD of %ld and %ld is: %ld\n",number1,number2,n2);
}
………………………………………………………………………………….
Output:
Enter two integers: 420 96
GCD of 420 and 96 is: 12
1. Write down the benefits of function with arguments and no return value by your own
idea.
……………………………………………………………………………….……
Activity ..……………………………………………………………………………………
148
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned about categories of function with arguments and no return value concept.
Learned how various types of functions are worked in a program.
ASSIGNMENT
Assessment
Exercises
1. Explain the function with arguments and no return value with an example.
2. Write a program using function with arguments and no return value procedure, that calculates the
value of Y in following series:
Y=12*32*52+……………………………………..*N2
3. Write a program using function with arguments and no return value procedure, that calculates the
value of Y in following series: Y=n(n-1)(n-2)(n-3)…………………….1.
149
School of Science and Technology DCSA Program
Learning Outcomes
Outcomes
Upon completion of this lesson you will be able to
Explain the function with arguments and return value concept.
return_type function_name(arguments/parameters)
{
…………………………………
Statements / function body
………………………………..
……………………………….
return value/ variable name;
}
Here, arguments also known as parameters means different data type or same data type value or variable
list. There are also two types of arguments such as (i) actual arguments and (ii) formal arguments
which are describe in previous section. The data type should be matched between actual arguments and
formal arguments. In case the actual arguments are more than formal arguments, the extra actual
arguments are discarded. On the other hand, if the actual arguments are less than the formal arguments,
the unmatched formal arguments are initialized to some garbage values. Any mismatch in data type
may also result in passing of garbage values. Formal arguments must be valid variable names and the
actual arguments may be variable names, expressions, or constants. The variables used in actual
arguments must be assigned values before the function call is made.
main( )
{
………………..
…………………
result=Value_check(10.50,20.50); Calling function
…………………….
…………………….
}
float Value_check(float num1, float num2) Called function
{
value=num1+num2;
avg=value/2;
return avg;
150
School of Science and Technology DCSA Program
}
In this above example, when Value_check( ) function calls with float type values 10.50 and 20.50, then
these values are assigned to num1 and num2 variables of called function respectively and then calculates
summation and average of two numbers and then return the average value (avg) to calling function
using keyword return. So the result variable of calling function will receive or assign average value.
EXAMPLE
Program 7.7.1 Write a program to calculate least common multiple (LCM) of two numbers using
function with arguments and return value.( Formulae: LCM=(number1*number2)/GCD )
#include <stdio.h>
#include<conio.h>
int lcm(long int n1,long int n2);
void main()
{
clrscr();
long int num1, num2,temp,result;
printf("Enter two integers: ");
scanf("%ld %ld", &num1, &num2);
if(num1>num2)
{
temp=num1;
num1=num2;
num2=temp;
}
result=lcm(num1,num2);
printf("LCM of %ld and %ld is: %ld ",num1,num2,result);
getch();
}
int lcm(long int n1,long int n2)
{
long int i,lcm, number1,number2;
int gcd;
number1=n1;
number2=n2;
while (n1 != 0)
{
long int r = n2 % n1;
n2 = n1;
n1 = r;
}
gcd=n2;
lcm=(number1*number2)/gcd;
return lcm;
}
…………………………………………………………………………………..
Output:
Enter two integers: 420 96
LCM of 420 and 96 is: 3360
151
School of Science and Technology DCSA Program
1. Write down the benefits of function with arguments and return value by your
own idea.
……..…………………………….………………………………………….……
Activity ..……………………………………..……………………………………………
…..…………………………………...……………………………………………
2. Write down the benefits of function with arguments and return value by your own
idea.
……..…………………………….………………………………………….……
..……………………………………..……………………………………………
…..…………………………………...……………………………………………
1. Determine the output of the following program:
void main()
{
Study skills int x=15,p;
int y=20;
p=product(x,y);
printf(“%d”,p);
}
int product(int a, int b)
{
return (a*b);
}
2. Identify the errors of the following program segments:
i. main()
{
int p, q;
Calculate(p,q)
printf(“%d,” p);
}
float Calculate( x, y)
{
int t=0;
t=x/y;
return t;
}
ii. void main()
{
int x,y;
float z;
Z=x%y;
Z=valuetest(z,x,y)
printf(“ output is :%d”,z);
getch( );
}
valuetest(float p, q, int t)
{
Float v;
v=(pow(t,q)/p);
return v;
}
3. What will be the output of the program 2(ii) after error correction?
152
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned about categoriey of function with arguments and return value concept.
Learned how various types of functions are worked in a program.
Also understood how a function is called in a program and returned value to calling function.
ASSIGNMENT
1. Write a program to find out greatest number from n numbers using function
with arguments and return value technique.
……………………………………………….………………………………
……………………………………………….………………………………
2. Write a program to print prime number list from 1 to 100 using function with
Assignment
arguments with return value concept
………………………………………………………………………………
………………………………………………………………………………
Assessment
Write ‘T’ for true and ‘F’ for false for the following sentences
Assessment 1. The data type should be matched between actual arguments and formal
arguments.
2. In function if the actual arguments are less than the formal arguments, the
unmatched formal arguments are initialized to some garbage values.
3. The variables used in actual arguments must be assigned values after the
function call is made.
Exercises
1. Explain the function with arguments and return value concept using an example.
2. Write a program to determine the volume of sphere using function with arguments and
return value concept. The formulae of volume of sphere is as follows:
4
3
𝜋𝑟 3 ,Where r is the radius of sphere.
153
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
RECURSION
In programming language, recursion is a technique or process to calling a function repeatedly. In
general, recursion is nothing more than a function that calls itself. When a function calls itself, this type
of function is called recursive function. The majority computer programming languages support
recursion by allowing a function to call itself within the program text. In programming language, while
using recursion, programmers need to be careful to define an exit condition from the function; otherwise
it will go into an infinite loop. Therefore, every recursive function must be provided with a way to end
the recursion. Recursive functions are very helpful to explain and solve many mathematical problems,
such as calculating the factorial of a number, generating Fibonacci series, summation of n numbers etc.
Consider the following example to understand the recursion technique, where the program to calculates
sum of first n numbers using recursion.
#include <stdio.h>
int summation(int n);
void main( )
{
int number,add;
printf("Enter a positive integer:\n");
scanf("%d",&number);
add= summation (number);
printf("summation of numbers: %d",add);
}
int summation (int n)
{
if(n==0)
return n;
else
return n+ summation(n-1); /*self call to function summation() */
}
…………………………………………………………………………..
Output
Enter a positive integer:
6
summation of numbers: 21
154
School of Science and Technology DCSA Program
In, this example, summation( ) function is invoked from the same function. If n is not equal to 0 then,
the function calls itself passing argument 1 less than the previous argument it was called with. Suppose,
user enter the value of n is 6 initially. Then, during next function calls, 5 is passed to function and the
value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is
returned which is the summation of numbers from 6 to 1. So the result will be 21.
For better visualization of recursion in this example is shown in bellow step by step wise:
summation(6)
=6+ summation (5)
=6+5+ summation (4)
=6+5+4+ summation (3)
=6+5+4+3+ summation (2)
=6+5+4+3+2+ summation (1)
=6+5+4+3+2+1+ summation (0)
=6+5+4+3+2+1+0
=6+5+4+3+2+1
=6+5+4+3+3
=6+5+4+6
=6+5+10
=6+15
=21
EXAMPLE
Program 7.8.1: Write a program to generate the Fibonacci Series for a given number using a
recursive function.
#include <stdio.h>
#include<conio.h>
int fibonacci(int i)
{
if(i = = 0)
{
return 0;
}
if(i = = 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
void main()
{
clrscr();
int i,n;
printf("Enter the Fibonacci Range: \n");
scanf("%d",&n);
printf(" Fibonacci series is : \n");
for (i = 0; i < 10; i++)
{
printf("%d\t", fibonacci(i));
}
getch();
}
155
School of Science and Technology DCSA Program
…………………………………………………………………………….
Output
Enter the Fibonacci Range:
10
Fibonacci series is :
0 1 1 2 3 5 8 13 21 34
Program 7.8.2: Write a program to calculate factorial value of a given number using a recursive
function.
#include<stdio.h>
#include<conio.h>
int factorial(int n);
void main()
{
clrscr();
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f= factorial (num);
printf("\n Factorial value of %d is: %d",num,f);
getch();
}
int factorial (int n){
if(n==1)
return 1;
else
return(n* factorial (n-1));
}
…………………………………………………………………………….
Output
Enter a number: 6
Factorial value of 6 is: 720
When a function calls itself, this type of function is called recursive function
1. Recursion is well-designed and requires few variables which make program clean.
2. It is used to avoidance of unnecessary calling of functions.
3. It is used to as a substitute for iteration where the iterative solution is very complex.
For instance to reduce the code size for Tower of Honai application, a recursive
function is best suited.
4. Recursion tremendously useful when applying the same solution.
5. Recursion can be used to replace complex nesting code by dividing the problem into
the same problem of its sub-type.
6. It is very flexible in data structure such as stacks, queues, linked list and quick sort.
156
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned about recursion and recursive functions and its definitions.
Also understood how a recursive function is called in a program.
Shown different types of program using recurisive functions.
ASSIGNMENT
𝑥3 𝑥5 𝑥7
1. Write a program to evaluate f(x)= 𝑥 − 3! + 5! − 7! + − − − − − − using
recursive function.
………………………………………………………………………………..
.……………………………………………………………………………….
Assignment 2. Write a program using recursive function to display the following pattern:
1
12
123
1234
12345
123456
Assessment
Write ‘T’ for true and ‘F’ for false for the following sentences
Assessment 1. Functions should be arranged in the order in which they are called.
2. C functions can return only one value.
3. A function can call itself.
4. A function in C should have at least one argument.
5. Every function should have a return statement.
6. While using recursion, programmers need to be careful to define an exit
condition.
7. Recursion technique uses stack data structure.
157
School of Science and Technology DCSA Program
Exercises
1. What is recursion and recursive function? Mention the significance of recursion in program.
2. Mention the advantages and disadvantages of recursive function.
3. Write a program to calculate factorial value of a number using recursion process.
4. Write a program using recursive function that will generate and print first n Fibonacci
numbers.
158
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
main( )
{
int number; Local variable in main( ) function
…………
Myfunction( );
}
void Myfunction( )
{
float area;
Local variables in Myfunction( ) function
int value;
…………….
}
We can also use the keyword auto to declare automatic/local variables explicitly as follows:
void Myfunction( )
{
auto int value;
…………….
}
In this case, one significant characteristic of automatic variables is that their value cannot be changed
accidentally by what happens in other functions in the program. For this reason, we can declare and use
the same variable name in different functions in same program without causing any puzzlement to the
compiler.
The following illustration shows that how automatic or local variables work in a program:
159
School of Science and Technology DCSA Program
#include<stdio.h>
#include<conio.h>
void valuetest1( );
void valuetest2( );
void main( )
{
clrscr();
int num=2000;
valuetest2( );
printf(" %d\n",num);
getch();
}
void valuetest1( )
{
int num=20;
printf(" %d\n",num);
}
void valuetest2( )
{
int num=200;
valuetest1( );
printf(" %d\n",num);
}
……………………………………………………………………………..
Output
20
200
2000
In this above program has two functions valuetest1( ) and valuetest2( ). This program, num is local
variable and it is declared at the beginning of each function. It is (i.e., num variable) initialized to
20,200, and 2000 in valuetest1( ), valuetest2( ) and main function respectively. When executed this
program, main calls valuetest2( ) which also calls valuetest1( ). When main is active, then num=2000;
but when valuetest2( ) is called, the main’s function num is temporarily put on the shelf and the new
local variable num =200 becomes active. Similarly when valuetest1( ) is called, both the previous values
of num are put on the shelf and the latest value of num =20 becomes active. As soon as valuetest1(
)(num=20) is finished , valuetest2( )(num=200) takes over again then, main(m=2000) takes over. For
these reasons, the value assigned to num is one function does not affect its value in the other functions
and the local value of num is destroyed when it leaves a function. The clear outputs are shown in
illustration.
On the other hand, a global variable is a variable that is declared outside all functions. Global variables
are also referred to as external variables. It is good practice to declare global variable before main
function. Global variables are both alive and active throughout the entire program. For this reason,
global variables can be accessed by any function in the program. Once a variable has been declared as
global, any function can use it and change its value and then successive functions can reference only
that new value.
160
School of Science and Technology DCSA Program
For instance, the external or global declaration of integer number and float area might appear as:
……………
int number;
Global variable declaration
float area;
main()
{
…………..
…………..
}
valuetest1( )
{
……….
………
}
valuetest2( )
{
……….
………
}
Here, the variables number and area are available for use in all the three functions such as main,
valuetest1, valuetest2. If a local variable and a global variable have the same name, in this case, the
local variable will have precedence over global variable in the function where it is declared. Consider
the following illustration:
……………
int value;
main( )
{
value=10;
………….
…………
}
void valuetest( )
{
int value=20;
………….
………….
value=value+2;
}
Here, we have seen that, global and local variable name (value) is similar. When the valuetest( )
references the variable value, it will be referencing only its local variable, not global variable one. The
value of value variable in main function will not be affected.
The following illustration shows that how global variables work in a program:
#include <stdio.h>
#include<conio.h>
int add_numbers( void );
int num1, num2, num3;
int sum_numbers( void )
{
auto int result;
161
School of Science and Technology DCSA Program
A global variable is a variable that is declared outside all functions. Global variables
are also referred to as external variables.
Actually, the scope and life time of a variable depends on the location where a variable is declared.
Therefore, according to their declaration, variables are classified into the following three (03)
categories:
1. Block variables
2. Local or internal variables
3. Global or external variables
Block variables
When variables are declared within a pair of braces { } this procedure is called block variables.
A block { } may be a self-governing with any control structure but, not with a f. Consider the following
statements of block variable declaration procedure:
…………………….
…………………….
{
/* independent block */
}
if(x<y)
{
/* block with control structure */
}
162
School of Science and Technology DCSA Program
#include<stdio.h>
int main()
{
…………
Entering into the block { /*outer block*/
int p=20;
{ /*inner block*/ Scope of
printf(“value of p= %d”,p); block
} variable
printf(“\n value of p= %d”,p);
}
Exit from the block return 0;
}
……………………………………………………..
Output
value of p=20
value of p=20
Here p variable is declared in the outer block, disappears only when control come out the outer block.
Hence, it is available for both inner and outer blocks.
163
School of Science and Technology DCSA Program
#include<stdio.h>
#include<conio.h>
void display_number();
void main()
{
int num=10;
display_number( ); Scope of local variable num
getch();
}
void display_number( )
{
printf("number is=%d",num);
}
…………………………………………………………………………….
Output
Error: undefined symbol “num” in function display_number()
#include<stdio.h>
#include<conio.h>
void display_number ( );
int main()
{
clrscr();
int num=40;
printf("number is =%d",num); Scope of local variable num in
display_number(); main function
printf("\nnumber is =%d",num);
getch();
return 0;
}
void display_number ( )
{
int num=100; Scope of local variable num in
display_number function
164
School of Science and Technology DCSA Program
printf("\nnumber is =%d",num);
}
………………………………………………………………………………..
Output
nnumber is =40
nnumber is =100
nnumber is =40
Program 7.9.5: Write a C program to demonstrate life time procedure of local variable
#include<stdio.h>
void display_numbers();
int main()
{
display_numbers();
display_numbers();
display_numbers();
return 0;
}
void display_numbers()
{
int num=20;
nump=num+20;
printf("\n number is: %d",num);
}
……………………………………………………………………………..
Output
number is: 40
number is: 40
number is: 40
In this example, num is a local variable to the function display_numbers( ), it doesn’t keep its values
for the next execution because it loses its life at the end of every execution. Hence, for every execution
num is allocated and assigned with 20. So, the result would be same for every function call.
165
School of Science and Technology DCSA Program
#include<stdio.h>
#include<conio.h> /* Global/External variable declaration */
int num=100;
void display_numbers();
void main()
{
printf("number is: =%d",num);
display_numbers( ); Scope of global/external variable num
printf("\nnumber is: =%d",num);
getch();
}
void display_numbers()
{
num=num+100; /* Changing global/external variable */
}
………………………………………………………………………………..
Output
number is: =100
number is: =200
The main scope concept of global variables is that, these variables are visible only to
the functions, which are down to their definition; these can’t be accessed from the
functions above to their definition
#include<stdio.h>
#include<conio.h>
void display_numbers();
voidt main()
{
166
School of Science and Technology DCSA Program
printf("number is:=%d",num);
display_numbers();
printf("\nnumber is:=%d",num);
getch();
} /* Global/external variable definition */
int num=10;
void display_numbers()
{
printf("\nnumber is:=%d",num); Scope of global/external variable num
num=num+100;
}
…………………………………………………………………………………….
Output
Error: undefined symbol num in function main().
The time period for which a variable exists in the memory is known as lifetime of
variable
1. Mention the lines which are belongs as scope of variable test from the following
program segment
#include<stdio.h>
Study skills ...................
void main()
{
...........................
float x,y;
test();
}
void test()
167
School of Science and Technology DCSA Program
{
int test=200;
if(test<500)
{
test=300;
printf(“the value of test variable is:=%d”,test);
}
else
test=400;
}
2. Mention the lines which are belongs as scope of variable count from the following
program segment
#include<stdio.h>
int count= 5;
Void main()
{
...........................
float x,y;
test(count);
}
void test(int Z)
{
count=count++;
if(count>=10)
{
count=0;
printf(“the value of count variable is:=%d”,count);
}
else
count++;
}
Summary
Summary
In this lesson we have
Learned about local and global variables.
Learned how local and global variables are executed in a program.
Learned about scope and life time of variables.
168
School of Science and Technology DCSA Program
ASSIGNMENT
𝑥3 𝑥5 𝑥7
1. Write a program to evaluate f(x) =𝑥 + 3! + 5! + 7! + − − − − − − using local
and global variable concept.
……..………………………………………………………………………..
……………………………………………………………………………….
Assignment 2. Write a multifunction program to illustrate the properties of global variables
……….………………………………………………………………………
……….………………………………………………………………………
Assessment
Write ‘T’ for true and ‘F’ for false for the following sentences
Assessment 1. A global variable can be used only in main function.
2. Global variables cannot survive in the memory as long as the program is
running.
3. A local variable is a variable that is declared outside a particular function.
4. Life time is the time interval for which a variable exists in the memory.
5. We can declare and use the same variable name in different functions in same
program.
169
School of Science and Technology DCSA Program
In the previous unit 7 we have studied about C functions and their declarations, definitions,
initializations. Also we have learned importance of local and global variables and their scope and life
time. In this unit we will describe about another important topic in C language like structures. We
have seen that, arrays can be used to represent a group of same data items. In the some cases, if we
want to represent a collection of data items of different types using a single name, then we cannot
use an array. For this reason, C language supports an assembled data type known as structure. In this
unit, we will describe in detail how a structure is defined, initialized, and how structure works in a
program.
Timeframe
How long ?
Unit Structure
Lesson- 1 : Introduction to C Structures
Lesson- 2 : Structure Initialization
170
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
STRUCTURES IN C
We have studied that, an array is one kind of data structures that can be used to demonstrate a group of
data items that belongs to the same type like int, float, char, double etc. But if we want to represent or
demonstrate a collection of different types of data items using a single name, then we cannot use an
array. For this reason, in C language supports a user defined data type known as structure. Actually,
structure is user defined data type available in C that allows combining different kinds of data items
using a single name.
On the other word, a structure is a well-situated tool for handling a collection of logically related data
items. It is used to represent a record or a set of attributes, such as student_name, roll_number,
obtained_mark and cgpa etc. It is a powerful concept that we can often need to use in our program
design.
STRUCTURE DEFINITION/DECLARATION
A structure is a collection of deferent type variables under a single name. Structures assist to arrange
complex data in a more meaningful. A structure declaration or definition generates a format that can be
used to declare structure variables. To define a structure, we must use the keyword struct statement.
The keyword struct statement defines a new data type, with more than one member. It declares a
structure to hold the details of member fields. The general format of the structure definition is as
follows:
struct struct_tag_name
{
data_type member-1;
data_type member-2;
data_type member-3; Structure fields or
………… …. …. elements or member
……….. …. ….
data_type member-n;
} one or more structure variables;
Here, the struct_tag_name is called structure tag name and it is optional and each member definition is
a normal variable definition, such as int a, float b, char c or char c[] etc; or any other valid variable
171
School of Science and Technology DCSA Program
definition. The tag name may be used subsequently to declare variables that have the tag structure. The
fields are called structure elements or members. Each member may belong to different type of data. At
the end of the structure's definition, before the final semicolon, you can specify one or more structure
variables. Let us use an example to illustrate the process of structure definition and the creation of
structure variables. Consider a book data base consisting of book title, author name, subject, number of
pages, price and book id. We can define a structure to hold this information as follows:
struct Books
{
char title[50];
char author[50];
char subject[100];
int pages;
float price;
int book_id;
}book; Structure variable
We can declare structure variables using structure tag name anywhere in the program. For instance, the
statement
declares book, book1, book2 and book3 as variables of type struct Books.
For example
book.title
book.price
book. book_id
are the variables representing the title, price and book id of book and can be treated like any other
ordinary variable. Here is how we should assign values to the members of book:
strcpy(book.title, “ C Programming”);
strcpy(book.author, “ Amran Hossain”);
book.pages=300;
book.price=500.00;
book.book_id=34521;
We can also use scanf() function to give the values through the keyword
scanf(“%s\n”,book.title);
scanf(“%s\n”,book.author);
scanf(“%d\n”,book.pages);
scanf(“%f\n”,book.price);
172
School of Science and Technology DCSA Program
scanf(“%d\n”,book.book_id);
are valid input statements.
Program 8.1.1: Write a C program that defining and assigning value to structure members.
#include <stdio.h>
#include <string.h>
#include<conio.h>
struct Books
{
char title[100];
char author[100];
char subject[100];
int pages;
float price;
int book_id;
} Book1,Book2; /* Declare Book1 and Book2 of type Books */
void main( )
{
clrscr();
/* Book 1 specifications */
strcpy( Book1.title, "C Programming Language");
strcpy( Book1.author, "Mr. Amran Hossain");
strcpy( Book1.subject, "C Programming Structure Tutorial");
Book1.pages=300;
Book1.price=300.50;
Book1.book_id = 32456;
/* Book 2 specifications */
strcpy( Book2.title, "Operating Systems");
strcpy( Book2.author, "Dr. Nasim Akhter");
strcpy( Book2.subject, "Linux Tutorial");
Book2.pages=400;
Book2.price=350.50;
Book2.book_id = 12345;
/* print Book1 information */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 page : %d\n", Book1.pages);
printf( "Book 1 price : %f\n", Book1.price);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 information */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 page : %d\n", Book2.pages);
printf( "Book 2 price : %f\n", Book2.price);
printf( "Book 2 book_id : %d\n", Book2.book_id);
getch();
}
173
School of Science and Technology DCSA Program
…………………………………………………………………………….
Output
Program 8.1.2: Define a structure type, struct personal that would contain person name, person
designation, date of joining and salary. Using this structure, write a program to read this
information for one person from the keyboard and print the same on the screen.
#include<stdio.h>
#include<conio.h>
struct personal
{
char person_name[50];
char person_desig[30];
int day;
char month[12];
int year;
float salary;
};
void main()
{
clrscr();
struct personal person;
printf("Enter Person Name:\n");
scanf("%s",person.person_name);
printf("Enter Person Designation :\n");
scanf("%s",person.person_desig);
printf("Enter person joining day:\n");
scanf("%d",&person.day);
printf("Enter Person joining month:\n");
scanf("%s",person.month);
printf("Enter Person joining year:\n");
scanf("%d",&person.year);
printf("Enter person Salary:\n");
scanf("%f",&person.salary);
printf("All informations are:\n");
printf("%s %s %d %s %d %.2f\n",person.person_name,
person.person_desig,person.day,person.month,person.year,person.salary);
getch();
}
……………………………………………………………………………………
Output:
174
School of Science and Technology DCSA Program
If we want to access any member or field of a structure, we may use the “member access
operator (.)” also called dot operator or period operator.
struct examtest
{
char name[];
int year, day;
double cgpa;
}
void main()
{
struct examtest;
printf(“ Input Values: \n”);
scanf(“%d %d %d %ld”, name, year, day, cgpa);
………………………
}
175
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned about C structures definition and declaration.
Learned initialization procedure of structure.
Also understood how structure variables are compared.
ASSIGNMENT
1. Write a program to determine the greatest common divisor (GCD) and least common
multiple (LCM) of two integer number using structure.
…..………………………………………………………………………….…..
………………………………………………………………………………….
2. Define a structure that can describe a hotel. It should have members that include the
Assignment
hotel name, address, grade, room charge, room category and number of rooms.
………………………………………………………………………………..
………………………………………………………………………………..
3. Define a structure called company that will describe the following information:
Company Name
Company location
Total employees
Salary status
Bonus system
Assessment
Exercises
176
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
STRUCTURE INITIALIZATION
Similar to any other data type, a structure variable can be initialized. When initializing an object or
member of structure, it must be a non-empty, brace-enclosed, comma-separated list of initializers for
the members. Consider the following example for structure initialization as follows:
struct student_record
{
int marks;
int age;
float cgpa;
}student={70,24,3.20};
Here, the above initialization procedure, assigns the value 70 to student.marks, 24 to student.age and
3.20 to student.cgpa member variables respectively. There is one-to-one correspondence between the
members and their initializing values. Various processes are possible in initializing a structure. The
following statements initialize three structure variables. Here, it is necessary to use a structure tag name.
Consider the following initialization example:
struct student_record
{
int marks;
int age;
float cgpa;
};
struct student_record student1={80,20,4.00};
struct student_record student2={60,22,3.50};
Another process is to initialize a structure variable inside the main function as follows:
struct student_record
{
int marks;
int age;
float cgpa;
} student1={80,20,4.00};
void main()
177
School of Science and Technology DCSA Program
{
struct student_record student2={60,22,3.50};
………………………..
………………………..
}
Two variables of the same structure type can be compared the same way as normal variables. If
student1 and student2 belong to the same structure, then the following operations are possible:
Operation Description
student1= student2 Assign student1 values to student1
student1= =student2 Compare all members of student1 and
student2. If they are equal then return 1,
otherwise return 0.
student1 != student2 If all the members of student1 and student2
are not equal then return 1 otherwise return 0.
Figure 8.2.1: Comparison of structure variables
#include<stdio.h>
#include<conio.h>
struct student_record
{
char student_name[30];
int marks;
int age;
float cgpa;
};
void main()
{
clrscr();
int record;
struct student_record student1={"Amran",78,24,3.89};
struct student_record student2={"Mamun",70,30,3.50};
struct student_record student3;
student3=student2;
record=((student3.marks= =student2.marks)&&(student3.cgpa= =student2.cgpa))?1:0;
if(record = =1)
{
printf("\n Student2 and Student3 marks and cgpa are same!!\n\n\n ");
printf("%s %d %d %f", student3.student_name, student3.marks,
student3.age,student3.cgpa);
}
else
{
printf("\n Student 2 and student 3 are different\n\n");
}
getch();
178
School of Science and Technology DCSA Program
}
………………………………………………………………………………….…………..
Output
Student2 and Student3 marks and cgpa are same!!
Mamun 70 30 3.500000
Two variables of the same structure type can be compared the same way as normal
variables.
Summary
Summary
In this lesson we have
Learned initialization procedure of structure.
Also understood how structure variables are compared.
179
School of Science and Technology DCSA Program
ASSIGNMENT
1. Define a structure called company that will describe the following information
and initialize all information’s using structure initialization procedure:
Company Name
Company location
Total employees
Assignment
Salary status
Bonus system
Assessment
Exercises
180
School of Science and Technology DCSA Program
Pointers Unit
9
INTRODUCTION
In the previous unit 8 we have studied about C structure and their declarations, definitions,
initializations. Also we have taught importance of C structures and their applications. In this unit we
will describe about another important feature of C language like pointer. In this unit, we will describe
in detail how a pointer is defined, initialized; how pointer works in a program and we will know the
benefits of uses of pointer.
Timeframe
How long ?
Unit Structure
Lesson- 1 : Introduction to C Pointers
Lesson- 2 : Pointer Declaration and Initialization
Lesson- 3 : Accessing Variable and Pointer Expression
181
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
Pointers are the powerful feature of C language. It is easy and fun to learn. Actually, pointers are used
in C program to access the memory and manipulate the memory address. A number of C programming
tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation.
Dynamic memory allocation cannot be performed without using pointers. So it becomes necessary to
learn pointers to become a perfect C programmer.
Benefits of pointers in c
The usages of pointers will give the following benefits:
Disadvantages of pointers in C
The drawbacks of pointers in c are mentioned bellow:
182
School of Science and Technology DCSA Program
2. Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory
leak.
3. Pointers are slower than normal variables.
4. If pointers are updated with incorrect values, it might lead to memory corruption.
WHAT IS POINTER?
A pointer is a nothing but a variable that contains an address of another same type of variable. Since, a
pointer is a variable; its value is stored in the memory in another location. Suppose, we have two
variables such as value1 and value2 and we want to assign the address of value1 to variable value2.
The link between the variables value1 and value2 can be visualized as shown in figure 9.1.1.
Here, the address of value2 is 80548. Since, the value of the variable value2 is the address of the variable
value1, we may access the value of value1 by using the value of value2 and therefore, we say that the
variable value2 points to the variable value2. Therefore, value2 is said to be pointer that points the
value1.
A pointer is a nothing but a variable that contains an address of another same type of
variable.
value2=&value1;
Study skills
183
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned about basic idea about C pointers.
Learned advantages and disadvantaages of pointer.
Also understood how varaibles are accessed by pointer in program.
ASSIGNMENT
1. Declare three integer type variables and two integer type pointers and show
how the variables are accessed by declared pointers.
….……………………………………………………………………………
Exercises
1. What is pointer?
2. Explain the advantages and disadvantages of pointer
3. How pointers access the address of a variable? Explain.
184
School of Science and Technology DCSA Program
Outcomes
DECLARING A POINTER
We know that a pointer is a variable that contains an address of another same type of variable. Since
pointer variables contain addresses that belong to a separate data type, they must be declared as pointers
before we use them. The general syntax or form of pointer declaration is as follows:
data-type * pointer_name;
Here, data-type is the valid C data type and pointer_name is the pointer variable name. The above
declaration tells the compiler three things about the variable pointer_name :
Declaration Example
For example,
int *ptr;
declares the variable ptr as a pointer variable that points to an integer (i.e., int) data type. Likewise the
following statement,
float *ptr;
declares ptr as a pointer to floating point variable. Once a pointer has been declared, it can be made to
point to a variable using an assignment operator like:
int *ptr, value;
ptr = &value;
Where ptr to point variable value so pointer variable ptr contains the address of value. This process is
also called pointer initialization. Before a pointer is initialized, it should not be used.
Such valid pointer declaration example as follows:
int a,b,*ptr;
float x,*y;
ptr = &a;
y = &x;
185
School of Science and Technology DCSA Program
Pointers are used in C program to access the memory and manipulate the memory
address
int a,b,*ptr;
float x,*y;
ptr = &x; //Error, type mismatch, because pointer variable always points to same type of data.
y = &a; //Error, type mismatch, because pointer variable always points to same type of data.
In general, pointer initialization is the process of assigning address of a variable to pointer variable.
Pointer variable contains address of variable of same data type. In C language address operator ‘&’ is
used to determine the address of a variable. In C, it is possible to initialize and declaration together.
For example:
int p = 100 ;
int *ptr ; //pointer declaration
ptr = &p ; //pointer initialization
or,
int *ptr = &p ; //initialization and declaration together
Here, p is integer variable and ptr is pointer variable. So initializes ptr to the address of p. Here note
that this is an initialization of ptr, not *ptr and also remember that the target variable p is declared first.
Summary
In this lesson we have
Learned about C pointers definition and declaration.
Learned initialization procedure of pointers.
Also understood how pointers are used in program.
Also understood pointer expression.
186
School of Science and Technology DCSA Program
ASSIGNMENT
1. Write a program to determine the greatest common divisor (GCD) and least
common multiple (LCM) of two integer number using structure.
…………………..………………………………………………………………...
………………….…………………………………………………………………
Assignment
Assessment
Write ‘T’ for true and ‘F’ for false for the following statements:
Assessment a) Pointer is a variable that contains an address of another same type of variable.
b) The asterisk (*) tells that pointer_name is a pointer variable.
c) Before a pointer is initialized, it should be used.
Exercises
187
School of Science and Technology DCSA Program
Outcomes
Upon completion of this lesson you will be able to
In the above statements, the 1st line declares data and x as integer variables and p as a pointer variable
that pointing to an integer. The 2nd line assigns the value1000 to variable data and then 3rd line assigns
the address of data to the pointer variable p and then 4th line contains the indirection operator *. When
the operator * is placed before a pointer variable in an expression, the pointer returns the value of the
variable of which the pointer value is the address. In this situation, * p returns the value of the variable
data, because p is the address of data. For this reason, the value of x would be 1000. In the above
statements, the two lines like
p=&data;
x=*p;
are equivalent to x=*&data;
and also is equivalent to x=data;
Program 9.3.1 Writes a program to illustrate use of indirection operator (*) to access the value.
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,*p;
a=200;
188
School of Science and Technology DCSA Program
p=&a;
b=*p;
printf(“ Value of a is:= %d\n”,a);
printf(“ The content of pointer p is:=%d \n”,*p);
printf(“ The content of variable b is:=%d\n”,b);
getch();
}
………………………………………………………………………..…………………….
Output
Value of a is:=200
The content of pointer p is:=200
The content of variable b is:=200
POINTER EXPRESSIONS
According to arithmetic operations or expression of other variables, pointer variables can be used in
expressions. For instance, if p1 and p2 are declared as pointers then we can say that the following
statements are valid:
p1 + 10;
p2 - 10;
p1- p2; are also valid statements.
We can also use short hand operators with the pointers such as
p1+ = 10;
sum + = *p2;
p1++; --p2; etc. are valid statements.
In C we can also compare pointers by using relational operators. The expressions such as
p1 > p2
p1= = p2 and
p1! = p2 are valid expressions.
But we cannot use pointers in division or multiplication. For instance, following expressions such as
p1/p2;
p1*p2;
p1/3; etc are not valid statements.
Program 9.3.2 Write a program to illustrate the use of pointers in arithmetic operations.
#include<stdio.h>#include<conio.h>
void main()
{
int A,B,*p1,*p2,x,y,z;
A=20;B=10;p1=&A;p2=&B;
x=*p1 * *p2-5;
y=((10* (-(*p2)))/(*p1))+30;
printf(“value of A = %d, and B = %d\n”,A,B);
printf(“value of x = %d, and y= %d\n”, x,y);
189
School of Science and Technology DCSA Program
Summary
Summary
In this lesson we have
Learned how variables are accessed by pointer.
Also understood how pointers are used in program and understood pointer expression.
ASSIGNMENT
Write ‘T’ for true and ‘F’ for false for the following statements
Assessment 1. Accessing a variable through the pointer we should follow three steps.
2. Like other variables, pointer variables can be used in expressions.
3. We cannot use pointers in division or multiplication.
Exercises
190
School of Science and Technology DCSA Program
Unit 1 : Lesson 4 : 1 a, 2 b, 3 a, 4 b, 5 b
Unit 2 : Lesson 4 : 1 d, 2 c
Unit 3 : Lesson 2 : 1 c, 2 a, 3 a
Unit 4 : Lesson 1 : 1 c, 2 a
Lesson 2 : 1 a, 2 a
Unit 6 : Lesson 5 : 1 a, 2 a, 3 c, 4 b
Unit 7 : Lesson 1 : 1 c, 2 a, 3 b, 4 a
Lesson 2 : 1 a, 2 c
Lesson 4 : 1 a, 2 b
Lesson 5 : 1 a, 2 c
Lesson 6 : 1 c, 2 d, 3 a, 4a
Lesson 7 : 1 a, 2 c
Lesson 8 : 1 b, 2 a, 3 c, 4 a
Lesson 9 : 1 a, 2 a, 3 b, 4 c, 5 a
Unit 8 : Lesson 1 : 1 a, 2 b, 3 c, 4d
Lesson 2 : 1 b, 2 d, 3 b, 4 a
Unit 9 : Lesson 1 : 1 a, 2 a, 3 b, 4 a, 5 a
Lesson 2 : 1 a, 2 b, 3d
191