0% found this document useful (0 votes)
112 views

Computer Programming Book Final-Version-2

This document is the preface to the second edition of a textbook on computer programming in C language for distance learners. It discusses the importance of programming and the C language. The textbook is divided into 9 units covering fundamental programming concepts like algorithms, data types, operators, arrays, functions, structures and pointers. It aims to introduce students to C programming in a simple, understandable manner. Feedback is welcomed to further improve the book.

Uploaded by

Vishal V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

Computer Programming Book Final-Version-2

This document is the preface to the second edition of a textbook on computer programming in C language for distance learners. It discusses the importance of programming and the C language. The textbook is divided into 9 units covering fundamental programming concepts like algorithms, data types, operators, arrays, functions, structures and pointers. It aims to introduce students to C programming in a simple, understandable manner. Feedback is welcomed to further improve the book.

Uploaded by

Vishal V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 199

Computer Programming

DCSA-1303

Bangladesh Open University


School of Science and Technology
School of Science and Technology

Computer Programming
DCSA-1303

Course Development Team


Writer
Amran Hossain
Department of Computer Science and Engineering
Dhaka University of Engineering & Technology, Gazipur

Mohammad Mamunur Rashid


School of Science and Technology
Bangladesh Open University

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

BANGLADESH OPEN UNIVERSITY


First Edition: 1998

Second Edition: April 2017

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

©Bangladesh Open University

Bangladesh Open University


School of Science and Technology
Gazipur-1705
Website: www.bou.edu.bd
Contents
Unit 1 1
Programming Fundamentals ………………………………………………...... 1
Lesson-1: Introduction to Computer Programming……………………………... 2
Lesson-2: Algorithm and Flowchart …….……………………………………… 5
Lesson-3: Overview of C language ………………………………………........... 7
Lesson-4: Basic Structure of C Program ………………………………………... 9

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

Programming Fundamentals Unit


INTRODUCTION
1
In order to communicate with each other, we use natural languages like Bengali, English, Hindi,
Urdu, French, Gujarati etc. We have different language around us in our real life to communicate
with each other. Basically, human beings cannot speak or write in computer language, and
since computers cannot speak or write in human language, an intermediate language had to be devised
to allow people to communicate with the computers. These intermediate languages, known as
programming languages, allow computer programmer to direct the activities of the computer. In
this unit, we shall be exposed to general terms related to computer programming such as languages,
algorithms and flowcharts. You will be familiar with these terms after reading this unit. The
importance of an algorithm in a programming language can be realized. This unit overviews history
of C language in addition basic structure of a C program is discussed.

Timeframe

We expect that this unit will take maximum 8 hours to complete.

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

Lesson-1 Introduction to Computer Programming


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define computer programming.


 State Why Programming.
 State the Categories of programming language.
 Define machine, assembly and high-level language.

Keywords Computer, Language, Program, Assembly, Machine

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.

Program is a series of instructions that guides the computer to solve a particular


problem.

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.

1. Mention the significance of Computer programming by your own concept.


…………………………………………………………………………………..
…………………………………………………………………………………...
Activity ..………………………………………………………………………………….

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 Low Level Language – Machine Oriented


 Assembly language

 High Level Language

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

0011 1110 Load A register with value 7


0000 0111 value 7
0000 0110 Load B register with 10
0000 1010 A= A + B
1000 0000 Store the result
0011 1010 into the memory location
0110 0110
0000 0000 whose address is 100 (decimal)
0111 0110 Halt processing

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:

LDA, 7 Load register A with 7


LDB ,10 Load register B with 10
ADD A,B AA + B
LD(100), A Save the result in the location 100
HALT Halt process

HIGH LEVEL LANGUAGE


 High Level Languages are user-friendly languages which are similar to English with
vocabulary of words and symbols.
 High level languages are simple language that use English and mathematical symbols like +, -
, %, /, etc. for its program construction.
 High level language has to be converted to machine language for the computer to understand.
 High level languages are easy to learn and use. It is because that they are similar to the
languages used by us in our day-to-day life.
 The code is then translated into object code, using a translator called Compiler or Interpreter.
The programs can easily be debugged and are machine independent.
 For Example: FORTRAN, COBOL, PASCAL C, C++, Java, C#, Visual Basic etc.

4
School of Science and Technology DCSA Program

Lesson-2 Algorithm and Flowchart


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define algorithm.
 Write algorithm.
 Define flowchart.
 Explain Flowchart symbols & their meanings.
 Draw flowchart.

Keywords Algorithm, flowchart, Symbol

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

 Process of drawing a flowchart for an algorithm is called flowcharting.


 Boxes are connected by solid lines having arrow marks to indicate exact sequence in which the
instructions are to be executed.
Symbols of Flowchart

For example

Advantages of Flowchart
 Efficient coding
 Systematic debugging
 Systematic testing
 Proper documentation

6
School of Science and Technology DCSA Program

Lesson-3 Overview of C language


Learning Outcomes

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.

Keywords History, Unix, Portable

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.

CREATION, COMPI LATION AND EXECUTION OF C PROGRAM


Environment Setup

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.

COMPILER AND INTERPRETER


As we write the code in English and we know that computers can understand only 0s and 1s. So we
need a translator which translates the code of our program into machine language. There are two kinds
of translators which are known as Interpreter and Compilers. These translators translate our program
which is written in C-Language into Machine language.
Compilers also translate the English like language (Code written in C) into a language (Machine
language) which computers can understand. The Compiler read the entire (whole) program first and
then translates it into machine language completely. The program written by the programmer in higher-
level language is called source program. After this program is converted to machine language by the
compiler it is called object program. A compiler can translate only those source programs, which have
been written, in that language for which the compiler is meant for. For example, FORTRAN compiler
will not compile source code written in COBOL language. Interpreters translates the program line by
line that means it reads one line of program and translates it into machine language and executes it
immediately, then it reads second line, translate it into machine language and executes it immediately
and so on. Here translation and execution are carried out for each statement. It differs from compiler,
which translate the entire source program into machine code and then involve in its execution.
The benefit of it is that we get the errors as we go along and it is very easy to correct the errors. The
drawback of the interpreter is that the program executes slowly as the interpreter translates the program
line by line. Another drawback is that as interpreters are reading the program line by line so they cannot
get the overall picture of the program hence cannot optimize the program making it efficient.
The difference between interpreter and compiler is that compiler will stop translating if it finds an error
and there will be no executable code generated whereas Interpreter will execute all the lines before error
and will stop at the line which contains the error. So Compiler needs syntactically correct program to
produce an executable code.

8
School of Science and Technology DCSA Program

Lesson-4 Basic Structure of C Program

Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain basic element of C program.

Keywords Comments, printf, scanf, Compound, Statement

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

Let's look at the elements of the program.


/* first program in C */
Known as comments. Comments are like helping text in your C program and they are ignored by the
compiler and Can appear almost anywhere. They start with /* and terminate with the characters */
#include <stdio.h>
#include, the first word of any C program. It is also known as pre-processor. The main work of pre-
processor is to initialize the environment of program, i.e to link the program with the header file
<stdio.h>. Standard header files are provided with each compiler, and cover a range of areas like string
handling, mathematical functions, data conversion, printing and reading of variables. To use any of the
standard functions, the appropriate header file must be included. This is done at the beginning of the C
source file. For example, to use the printf() function in a program, the line #include <stdio.h> is
responsible.
main()
The next important line is main(). main() function is a function that must be used in every C program.
main() function starts the execution of C program. Parentheses “( )” is used to indicate a function.
Braces ({ and }) indicate a block. The bodies of all functions must be contained in braces.
printf( "Welcome to C" );
The printf() is a library function to send formatted output to display on the screen. Printf() instructs
computer to perform an action; specifically, prints the string of characters within quotes (“ ”). There is
a semicolon (;) at the end of the above statement. In a C program, the semicolon is a statement

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,..);

Example of printf() function


int a=10;
double d=13.4;
char c='A';
printf("%f%d",d,a,c);

SIMPLE AND COMPOUND STATEMENT

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. ……….. developed the C language.


Assessment
2. printf() is used to ……. the output and scanf() is used to ……... the input.
3. C programs are stored with ………. Extension.
Multiple Choice Questions (MCQ)

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

a) algorithm c) control of flow


b) flowchart d) UML diagram
3. The C language has been developed at?
a) AT & T Bell Labs c) IBM
b) Borland International d) Sun Microsystems
4. What is the only function that all C programs must contain?
a) start() c) system()
b) main() d) program()
5. Which of the following is the correct way of writing comments?
a) */comments/* c)**comment**
b) /*comment*/ d){comment}
Exercises

1. Define computer programming language.


2. Define machine, assembly and high-level languages.
3. Differentiate between an interpreter and compiler.
4. Compare an algorithm with a flowchart.
5. Explain the symbols for flowchart.
6. Write the syntax of printf and scanf function.
7. Define simple and compound statement.
8. Write the format specifier available in C language.

12
School of Science and Technology DCSA Program

Keyword, Variable and Data Type Unit


INTRODUCTION 2
C tokens, Identifiers and Keywords are the basics and are part of the syntax in a C program. All are
explained in this unit with definition and simple example programs. Also, you will learn about
variables, rules for naming a variable, constants and different type of constants in C programming.
Through this unit you will learn about data types which are very important in programming. C data
types are defined as the data storage format that a variable can store a data to perform a specific
operation. Size of variable, constant and array are determined by data types. C language has some
predefined set of data types to handle various kinds of data that we use in our program.
Timeframe

We expect that this unit will take maximum 8 hours to complete.

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

Lesson -1 Keyword and Identifier


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define token.
 Define identifier.
 Define keyword.

Keywords Identifier, Token

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.

auto else long switch break enum register typedef


case extern return union char float short unsigned
const for signed void continue goto sizeof volatile
default if static while do int struct _Packed double

Keywords cannot be used as constants or variables or any other identifier names.

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

 C does not allow punctuation characters such as @, $, and % within identifiers.


 Only 31 characters are significant.
 Can not be the same as C keywords and should not have the same name as functions that are in
C library.
 C is a case-sensitive programming language. Thus, Name, names, NAME are three different
identifiers in C.
 Must not contain white space
Here are some examples of acceptable identifiers:
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

1. Let’s do simple exercise. In this exercise we will match valid and invalid identifier.

Match the column


Activity
(a)_no
valid identifier (b) 34_
(c) char
(d) _char
invalid identifier (e)num ber
(f) @no

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.

Keywords Variable, Declaration

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.

In programming, a variable is a container (storage area) to hold data. To indicate the


storage area, each variable should be given a unique name (identifier). Variable name is
just the representation of a memory location. Every variable must be individually

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.

STORING VALUES IN VARIABLES


You have seen how to declare variables in the previous section. Now, let's store some values in those
variables:
int a;
int b;
a = 10;
b = 20;
Here we are storing 10 in variable a and 20 in variable b. Almost all the programming languages have
similar way of storing values in variable where we keep variable name in the left side of an equal sign
= and value we want to store in the variable, we keep that value in the right side. When above statement
is executed, the memory location named a will hold 10 and memory location b will hold 20.

17
School of Science and Technology DCSA Program

Some more examples:


int a, b, sum;
a = 50;
b = 60;
sum = a + b;
We can also assign value at the time of declare as follows
int a = 50, b = 60, sum;
sum = a + b;
CATEGORY OF C VARIABLE

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

printf(“%d”,a);//Accessing inner local variable a.


}
printf(“%d”,a); //Accessing outer local variable a.
return 0;
}
Output: 30 15
RULES FOR NAMING VARIABLES
To use variables in your C programs, you must know how to create variable names. In C, variable names
must adhere to the following rules:
 The name can contain letters, digits, and the underscore character (_).
 The first character of the name must be a letter. The underscore is also a legal first character, but its
use is not recommended.
 Case matters (that is, upper- and lowercase letters). Thus, the names count and Count refer to two
different variables.
 C keywords can't be used as variable names. A keyword is a word that is part of the C language
The following list contains some examples of legal and illegal C variable names:

Variable Name Legality


Percent Percent Legal
y2x5__ fg7h Legal
annual_ profit Legal
_1990_tax Legal but not advised
savings#account Illegal: Contains the illegal character #
double Illegal: Is a C keyword
9winter Illegal: First character is a digit

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.

Keywords Constants, 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

"x" //string constant having single character.


"Bangladesh Open University\n" //prints string with newline

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

1. Determine which of the following are valid character constants?

a) `a`
Activity b) `$`
c) `\n`
d) `/n`
e) `\\`
f) `\a`
g) `T`
h) `\0`
i) `xyz`
j) `\052`.

2. Determine which of the following are valid string constants?

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

Lesson-4 Data Type


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define data type.


 Describe the data type in C.
 Understand the declaration of data type.

Keywords integer, float, double.

INTRODUCING C DATA TYPE


Every programming language deals with some data. For example to print any message it requires
charterer or string type of data. To solve any mathematic expression it requires integral as well as real
number (floating type) of data. C is very rich in data type. Data types specify how we enter data into
our programs and what type of data we enter. C language has some predefined set of data types to
handle various kinds of data that we use in our program. These data types have different storage
capacities. Data types are used to define a variable before to use in a program. Size of variable, constant
and array are determined by data types. There are four data types in C language.
C DATA TYPES
Types Data Types
Basic data types int, char, float, double
Enumeration data type enum
Derived data type pointer, array, structure, union
Void data type void

INTEGER DATA TYPE


 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using 16 bitprocessor, 2
byte (16 bit) of memory will be allocated for int data type. Like wise, 4 byte (32 bit) of memory
for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is allocated for int
datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can go for “long
int” and “long long int” for which the limits are very high.

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

float - data type


float is used to define floating point numbers.

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';
}

DERIVED DATA TYPE IN C LANGUAGE


Array, pointer, structure and union are called derived data type in C language. You will learn about
these from the next units.
Size of data types in c
DATA TYPE SIZE (IN BYTE)
int 2
short int 2
long int 4
float 4
double 8
long double 10
char 1

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

1. A character constant which uses ………………..around characters.


Assessment
2. Variable is a ………………………to hold data.

Multiple Choice Questions (MCQ)

1. Which of the following are tokens in C?


a) Keywords
b) Variables
c) Constants
d) All of the above
2. Which of the following is not a keyword
a) void
b) int
c) main
d) for

Exercises

1. Describe the keywords and identifiers in C.


2. What is variable? Discuss how to declare variables and assign values to variables with an
example.
3. What is constant?
4. What is the difference between a constant and a variable?
5. What is a string constant? How do string constants differ from character constants? Do
string constants represent numerical values?
6. Write simple programs using constants and variables
7. What is data type? Describe the data types in C.?

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

We expect that this unit will take maximum 3 hours to complete.

How long ?

Unit Structure
Lesson- 1 : Operator part -1
Lesson- 2 : Operator part -2

26
School of Science and Technology DCSA Program

Lesson -1 Operator Part-1


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to
 Define Operator.
 Classify Operator.
 Explain arithmetic operator.

Keywords Operator, Arithmetic, Precedence

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

OPERATOR OPERATION DESCRIPTIONS C EXAMPLE


EXPRESSION
+ Addition Adds two operands x+y x + y = 30
- Subtraction Subtracts second x-y x-y = 10
operand from the first
* Multiplication Multiplies both operands x*y x * y = 200
/ Division Divides numerator by x/y x/y=2
de-numerator
% Modulus provide remainder of an x%y x%y=0
integer division

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?

3. Does 7 % 2 produce the same result as 4 % 3?

29
School of Science and Technology DCSA Program

Lesson-2 Operator Part-2


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define relational operator.


 Use logical Operator.
 Explain assignment operator.

Keywords Relational, Logical, Bitwise

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

Multiple Choice Questions (MCQ)


1. Which of the following is not an arithmetic operation?
e) a *= 10;
f) a /= 10;
g) a != 10;
h) a %= 10;
2. The operator + in a+=4 means
a) a=a+4
b) a + 4 = a
c) a = 4
d) a = 4 + 4

3. The most commonly used assignment operator is


a) =
b) ==
c) >=
d) :=
Exercises
1. State C operators and their classification.
2. What is an operand? What is the relationship between operators and operands?
3. Write the difference between = and == in C programming.
4. Describe the arithmetic, relational, logical, assignment, increment, decrement and
conditional operators with suitable example.
5. Describe the precedence of arithmetic operators.
6. Write programs using operators.
7. Describe the four relational operators include in C. With what type of operands can they be
used?

32
School of Science and Technology DCSA Program

Decision Making and Branching Unit


4
INTRODUCTION

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

We expect that this unit will take maximum 10 hours to complete.

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

Lesson-1 Basic Concept on Decision Making Statements


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand basic idea about decision making statements.

Keywords Decision making, Statements, Control, Execution

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

Figure 4.1.1 General form of decision making structure

C language handles decision-making by supporting the following statements:

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.

 if statement: if statement is used to control the flow of execution of statements. It allows


evaluate the condition or expression first and then, depending on whether the value of the
expression is true or false.
 if-else statement: if-else statement is used to carry out a logical test and then take one of two
possible actions depending on the result of the test.
 Nesting if-else statement: nesting if-else statements are used, when a series of decisions are
concerned, we may have to employ more than one if-else statement.
 else-if ladder statements: else-if ladder statements are used, when multipath decisions are
concerned. A multipath decision is a chain of ifs in which the statement associated with each
else is an if.
 switch case statement: switch statement checks the value of a given expression against a list of
case values and when a match is found a block of statements associated with the case is
executed.

Summary

Summary
In this lesson
 We have understood about C language decision making statements.

Assessment
Fill in the blanks

1. if statement is used to ……………………. of execution of statements.


Assessment
2. A multipath decision is a chain of………………….
3. if-else statement is used to carry out a ……….. test.

Multiple Choice Questions (MCQ)

1. C language handles decision-making by supporting-


a) 3 statements b) 4 statements c) 5 statements d) 6 statements
2. Nesting if-else statements are used-
a) When a series of decisions are b) When a single of decision is
concerned concerned
c) No decision are allowed d) None of these

Exercises

1. What do you mean by control statement?


2. Explain shortly various decision making statements.

35
School of Science and Technology DCSA Program

Lesson-2 Decision Making Using if and if-else Statements


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand about the if statement.


 Understand about the if-else statement.

Keywords Statement, If, If-else, Execution, Expression, Condition

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.

The general structure of a simple if statement is as follows:

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.

The general flow chart of if statement is shown in below:

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

Consider the following program segment:

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);
}

printf("Have a nice Day!!");


getch();
}
……………………………………………………………………………………
Output
Enter Integer Number:-10
You entered -10.
Have a nice Day!!
Enter Integer Number: 50
Have a nice Day!!

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);

if(salary < 20000)


{
salary=salary+5000;
}

printf("Employee Salary is:%ld\n",salary);


getch();
}
…………………………………………………………………………………….
Output
Enter Basic salary of an employee: 10000
Employee Salary is:15000

Enter Basic salary of an employee: 30000


Employee Salary is:30000

SIMPLE IF-ELSE STATEMENT

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.

The general flow chart of if-else statement is shown in below:

Entry

True Test False


Condition/expression
?

True statements-block False statements-block

Statement-n

Figure 4.2.2: flowchart of if-else control statement

Consider the following program segment:

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.

Consider another programming example is as follows:

void main()
{
int age;

printf(" Enter your real age:");


scanf("%d",&age);

if(age >= 18)


{
printf("you are eligible for voting.");
}
else
{
printf("you are not eligible for voting.");
}
}

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;

printf("Enter a integer number:");


scanf("%d",&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;

printf("Enter Employee Basic salary: ");


scanf("%ld",&bsalary);

if(bsalary > 20000)


{
msalary=bsalary+bsalary*0.4+1500;
printf("Employee Monthly Salary is: %ld",msalary);
}
else
{
msalary=bsalary+bsalary*0.55+1000;
printf("Employee Monthly Salary is: %ld",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

1. Determine the output of the following program segment


void main( )
{
Study skills .......................
......................
Test= 50;
if( Test>=10)
{
printf(“%d”,Test);
}
Test= Test+100;
printf(“%d”,Test);
}
2. Determine the output of the following program segment
void main( )
{
.......................
.......................
Test= 50;
if( Test>=10)
{
printf(“%d”,Test);
}
else
{
Test= Test+100;
printf(“%d”,Test);
}
}
3. Find out the errors from the following program segments:
a. ..........................
.........................
If(x+y=p && z=1)
Printf(“ ”);

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

What will be the values of X and Y if n=1 and n=0.

1. Write a program to check you are either YOUNG or OLD.


….………………………………………………………………………………
.…………………………………………………………………………………
Activity
2. Write a program to find the number of and sum of all integers greater than 100 and
less than 200 that are divisible by 7.
…..………………………………………………………………………………
……..……………………………………………………………………………
Summary

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

1. Mention the main differences between if and if-else statements.


……..…………………………………………………………………………
….………….…………………………………………………………………
2. Write a program to check whether a year is leap year or not.
………..………………………………………………………………………..
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.

Multiple Choice Questions (MCQ)

1. In the if-else statement, if the test condition or expression is true then-


a) true statements-block is executed b) false statements-block is executed
c) both true and false statements are d) none of these
executed
2. if statement is-
a) two-way decision making b) single way decision making statement
statement
c) no way decision making statement d) none of these

Exercises

1. What do you mean by control statement?


2. Differentiate between if and if-else conditional statements with an example.
3. Explain if control statement with flowchart and an example.
4. Explain if-else control statement with flowchart and an example.

43
School of Science and Technology DCSA Program

Lesson-3 Decision Making Using Nesting of if-else Statements


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain nesting if-else statements.

Keywords Statement, If-else, Execution, Expression, Nesting

NESTING OF IF-ELSE STATEMENTS

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.

The general structure of nesting of if-else statement is as follows:

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

False Test True


Expression-1
?

Test True
Expression-2
?

False

Block Statement-3 Block Statement-2 Block Statement-1

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.

1. Mention the significance of using nesting if-else by your own concept.


……………………………………………………………………………………..
……………………………………………………………………………………..
Activity
2. Write the nested if-else statements syntax with five if and three else.
…………………………………………………………………………………….
…………………………………………………………………………………….

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;

printf("Enter three integer numbers:\n ");


scanf("%d %d %d",&num1,&num2,&num3);

if(num1 > num2)


{
if(num1 > num3)
{
printf("Largest Number is: %d\n", num1);

}
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!!!"

Enter Your Username: a


Enter Your Password:12345
Login successful

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

Enter your sex: F


Enter your balance: 15000
Monthly Balance will be: 16500

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

1. Write down the benefits of nesting if-else in C program.


……..………………………………………………………………………..
………………………………………………………………………………

2. Determine the roots of the quadratic equation 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0 using the well


Assignment
known quadratic formula:
−𝑏 ± √(𝑏 2 − 4𝑎𝑐)
𝑥=
2𝑎

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

1. Define nesting if-else statements.


2. What are the benefits of using nesting if-else statements?
3. Draw and explain the flow graph of nesting if-else statements.
4. Write a C program to determine maximum and minimum number from three integer
numbers using nesting if-else statements.

49
School of Science and Technology DCSA Program

Lesson-4 Decision Making Using else-if Ladder Statements


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain else-if ladder statements.


 Explain else-if ladder general syntax.
 Explain else-if ladder flowchart.

Keywords Statement, If-else ladder, Execution, Flowchart

ELSE-IF LADDER STATEMENTS

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

Figure 4.4.1: Flowchart of if-else ladder

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:

Obtained marks Grade Obtained marks Grade


80 to 100 A+ 55 to less than 60 B
75 to less than 80 A- 50 to less than 55 C+
70 to less than 75 A 45 to less than 50 C
65 to less than 70 B+ 40 to less than 45 D
60 to less than 65 B- Less than 40 F
Now write a C program to Calculate students’ grade using if–else ladder concept.

#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

printf("Your Grade is C");


}
else if(marks<45 && marks>=40)
{
printf("Your Grade is D");
}
else
{
printf("Your Grade is F");
}
}
getch();
}
……………………………………………………………………………….
Output
Enter your Marks: 78
Your Grade is A-
Enter your Marks: 120
Invalid Marks. Marks must be less than or equal 100

Program 4.4.2 Assume that DESCO power distribution company charges its domestic
customers as follows:

Consumption Units Rate of charge Consumption Units Rate of charge


0-100 1.00 taka per unit 401-500 3.50 taka per unit
101-200 1.50 taka per unit 501-600 4.70 taka per unit
201-300 2.00 taka per unit 601-700 5.00 taka per unit
301-400 2.75 taka per unit 701 or above 8.50 taka per unit
Now write a C program that reads power consumed unit and prints the amount to be paid by
the customer.

#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:

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.

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

1. What are the benefits of using nesting if-else ladder statements?


2. Draw and explain the flow graph of if-else ladder statements.

55
School of Science and Technology DCSA Program

Lesson-5 Decision Making Using Switch Case Statement


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain switch case statement.


 Explain switch case general syntax.
 Explain switch case flowchart.

Keywords Statement, Switch, Case, Execution, Expression, Flowchart

SWITCH CASE STATEMENT

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:

switch (variable or expression)


{
case Constant-1:
block-code-1;
break;
case Constant-2:
block-code-2;
break;
case Constant-3:
block-code-3;
break;
……………………………
……………………………
case Constant-n:
block-code-n;
break;

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:

Obtained marks Grade Obtained marks Grade


80 to 100 A+ 50 to less than 60 C
70 to less than 80 A- 40 to less than 50 D
60 to less than 70 B Less than 40 F
Now write a C program to Calculate students’ grade using Switch case concept.

#include<stdio.h>
#include<conio.h>
void main()
{

int marks, value;

printf("Enter the marks: ");


scanf("%d",&marks);

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

1. What is switch in C program? Why is switch case statement used in C program?


2. Draw and explain the flowchart of switch case statement.
3. Briefly explain the general syntax of Switch case statement.
4. In what ways does a switch statement differ from an if statement?

59
School of Science and Technology DCSA Program

Decision Making and Looping Unit


INTRODUCTION
5
In the previous lessons we have learned about the programming structure, decision making procedure,
how to write statements, as well as different types of decision or conditional statements and some
basic control statement based program. In this unit we will learn about definition of loop, declaration
and initialization of loop, various types of loop in C program and its applications and also how to
handle loops in program. In C programming language loop is very useful statement.
Timeframe

We expect that this unit will take maximum 10 hours to complete.

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

Lesson-1 Basic Concept On Loop Control Structures


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define programming loop.


 Understand the loop control structures.
 Explain uses of loop in program.

Keywords Program, Loop, Control Structure, Entry, Exit

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 is a sequence or arrangement of instruction(s) that is continually repeated


until a certain condition is reached.

LOOP CONTROL STRUCTURES

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

Body of the loop

Figure 5.1.1: Entry-controlled loop structure


Exit-controlled loop
In the exit-controlled loop, the control conditions are tested at the end of the body of the loop. As result
the body is executed unconditionally for the first time. The flowchart of exit-controlled loop is shown
in below:

Input Entry

Body of the loop

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

Usually in a looping process, would include the subsequent four steps:

1. Setting and initialization of a counter variable.


2. Execution of the statements in the loop.
3. Test for a specified conditions for execution.
4. Increment or decrement the counter variable.

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.

1. Mention the significance of using loop in C language by your own concept.


……………………………….……………………………………………………..
……………………………………………………………………………………...
Activity …………………………..………………………………………………………….

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

Lesson-2 Understanding While Loop


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define the while loop.


 Explain the while loop with syntax.
 Explain the while loop flowchart and example.

Keywords Program, Loop, While loop, Syntax, Flowchart

THE WHILE LOOP

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

Body of the loop

Figure 5.2.1: Flowchart of while loop

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.

A while loop in C programming repeatedly executes a target statement as long as a


given condition is true.

Program 5.2.1 write a C program that prints 10 to 15 using while loop

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

1. What will be the output of the following code segment


#include <stdio.h>
#include <conio.h>
Activity void main ()
{
int p = 5;
while( p >20 ) {
printf("value of a: %d\n", p); p++;
}
printf(" Hello Good day!!");
}
2. Find out errors from the following code segment
void main ()
{
int p = 5;
while p =5 ;
{
printf("%d\n", a); p;
}printf(" Hello Good day!!");
}

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.

Multiple Choice Questions (MCQ)


1. In while loop body of the loop or statement(s) may be
a) A single statement or a block of b) Only single statements
statements
c) Only two blocks d) None of these
2. A while loop in C programming repeatedly executes a target statement as long as a
given
a) Condition is true.
b) Condition is false
c) Both true and false is possible
d) None of these
3. In while loop when the Test-condition is tested and the result is false, body of the
loop will be-
a) Printed b) Terminated c) Executed d) Skipped

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

Lesson-3 Understanding Do-While Loop


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define do-while loop.


 Explain the do-while loop with syntax.
 Explain the do-while loop flowchart and example.

Keywords Program, Loop, Do-while loop, Syntax, Flowchart

THE DO-WHILE LOOP

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

Figure 5.3.1: Flowchart of do-while loop

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

}while((letter[count] = getchar())!= EOL);


value = count;
count=0;
do
{
putchar(toupper(letter[count]));
++count;
}while(count < value);
getch();
}
………………………………………………………………………………
Output
Type text or line as lowercase:
i am a man. i read in bangladesh open university
I AM A MAN. I READ IN BANGLADESH OPEN UNIVERSITY

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

1. What will be the output of the following code segment:


#include<stdio.h>
void main()
Activity {
int value=2;

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

Lesson-4 Understanding For Loop


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define the for loop.


 Explain the for loop with syntax.
 Explain the for loop flowchart and example.

Keywords Program, Loop, For Loop, Syntax, Flowchart

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.

The general form or syntax of for loop is as follows:

for(initialization; Test-condition; increment/decrement)


{
Body of the loop or statements;
}
The execution procedure of for loop is described below:

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

The execution procedure is shown clearly as follows

for(initialization; Test-condition; increment/decrement)


{

Body of the loop or statements;

The flowchart of for loop is shown in bellow:

Initialization

Test False
Condition

True

Body of the loop or


Statements

Increment/decrement

Exit

Figure 5.4.1: Flowchart of for loop

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

Program 5.4.1 Write a C program that display 1 to 10 using for loop.

#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

Enter the value N of series: 20


The Total value of series is: 1330

NESTING OF FOR LOOP

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:

for ( initialization; Test-condition; increment/decrement )


{
for (initialization; Test-condition; increment/decrement)
{ Inner Outer loop
Body of the loop or statement(s); loop
}

Body of the loop or statement(s);


}

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

Lesson-5 Understanding Break And Continue Statements


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define break statement.


 Define continue statement.
 Explain uses of break and continue statements in program.

Keywords Program, Break, Continue, Statement, Exit, Flowchart

JUMPING PROCESS IN LOOPS

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

for(init, Test-condition; increment) for((init, Test-condition; increment)


{ {
……………….. …………………………
………………. …………………………
if(condition) for(init, Test-condition; increment)
break; {
…………… ………………..
…………… ……………….
} if(condition)
……………………… break;
……………
……………
}
………………..
}
(c) break in for loop (d) break in nested for loop

Figure 5.5.1 break used in while, do-while and for loops

The flowchart of break statement is shown in below:

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

printf("The program calculates maximum 10 Numbers.\n");


printf("The program will terminate, if enter negative number.\n");
for(i = 1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%f",&number);
/* If user enters negative number, loop is terminated*/
if(number < 0.0)

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

So End of an infinite loop...

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);

(a) continue in while loop (b) continue in do-while loop


for(initialization, Test-condition; increment)
{
………………..
……………….
if(condition)
continue;
……………
……………
}
(c) continue in for loop

Figure 5.5.3: Uses of continue in different types of loops

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

The flowchart of continue statement is shown in below:


Entry loop

Test condition
of loop
False

True

Yes
continue?
con
No
Exit loop
Remaining body of
loop

con Flowchart of continue statement


Figure 5.5.4

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

1. what will be the output of the following program segment:


#include <stdio.h>
#include<conio.h>
Activity void main()
{
int i=0,x=0;
for(i=1;i<10;++i)
{

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

1. What will be the output of the following program


#include <stdio.h>
#include<conio.h>
Assignment void main(){
int i,j,k,x=0;
for(i=0;i<5;++i){
for(j=0;j<i;++j){
switch(i+j-1){
case -1:
case 0:
x+=1; break;
case 1:
case 2:
case 3:
x+=2;
default:
x+=3;
} printf("%d",x);
} printf("\nx=%d",x);}
}
Assessment
Write “T” for true and “F” for false the following sentences:
1. C permits jump from one statement to another within a loop as well as jump
Assessment out of the loop.
2. The break statement allows us to exit a loop from any point within its body.
3. When the break statement is encountered inside a loop, the loop is immediately
terminated.

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.

Multiple Choice Questions (MCQ)

1. When loops are nested, the break would only-


a) Exit from the loop containing it
b) Continue from the loop containing it
c) Nested from the loop containing it
d) None of these
2. The break statement allows us to departure a loop from any point within
its body-
a) avoiding its regular termination process or expression
b) permitting its regular termination process or expression
c) exit from the loop containing it
d) continuing its regular termination process or expression
3. The continue statement tells the compiler-
a) Continue the following statements and skip with the next iteration
b) Skip the following statements and continue with the next iteration
c) Test the following statements and continue with the next iteration
d) None of these

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

Lesson-6 Understanding goto Statement


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define goto statement with syntax.


 Explain the uses of goto statement.

Keywords Program, goto, Statement, Exit, Flowchart

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

while(Test-condition) for(int; Test-condition; increment)


{ {
if(condition-error) …………………………..
goto stoplebel; for( int; Test-condition; increment)
……………… Exit {
if(condition) from ……………………….
goto label1; Loop if(error condition)
Jump
Within …………… goto Error;
Loop …………… ………………………
Exit
label1: }
From
………..... two ………………………..
} Loops }
stoplebel: Error:
…………… …………………….
…………… ……………………

Figure 5.6.1 Jumping within and exiting from the loops with goto statement

The flowchart of goto statement is shown in below:

Label 1 Statement(s) 1

Label 2 Label 3
Statement(s) 2

Label 3 Statement(s) 3

Rest of the code

Figure 5.6.2 flowchart of 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

The use of goto statement is extremely discouraged in any programming language


because it makes tough to trace the control flow of a program, making the program hard
to understand and rigid to change. Any program that uses a goto can be redrafted to avoid
them
Some goto programming examples are shown in below:

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

Exit from loop


SUM = 1.265800; No. of terms = 7
Enter the value of x: .75

Exit from loop


SUM = 3.999774; No. of terms = 34

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

/* This message does not print: */


printf( "Loop exited. p = %d\n", p );

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

1. what will be the output of the following program segment:


void main () {
int num = 10;
Activity LOOP: do {
if( num = = 15) {
num = num + 1;
goto LOOP;
}
printf("value of Num: %d\n", num);
num++;
}while( num < 20 );
}
Summary

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

1. Write the importance of uses of goto statement in C program.


……………………………………………………………………………………
……………………………………………………………………………………
2. Find errors if any and correct them and mention the output of the following program
segment after correcting the errors:
Assignment
void main ()
{
int num = 10;
TEST do{
if( num = 14){
num = + 2;
goto;
}
printf("value of a: %d\n", num);
num++;
}while( test < 20 )}
Assessment
Write “T” for true and “F” for false the following sentences:
1. The goto statement is used to exit the normal sequence of C program execution.
Assessment 2. The goto statement provides a conditional jump from the 'goto' to a labeled
statement in the same function.
3. The goto statement can transfer the program control to any place in a program.
Multiple Choice Questions (MCQ)

1. In goto statement the Label_name can be any ordinary text except C-


a) Keyword b) Expression c) Variable d) Constant
2. The goto statement is used to change the normal sequence of C program execution
by transferring-
a) Control to any place of the b) Control to only specified place of the
program program
c) Control to end of the program d) None of these
3. In goto statement every labeled statement within the program must have a
a) Different label b) unique label c) Multiple label d) None of these
4. The goto statement provides an unconditional jump from the 'goto' to a labeled
statement in the-
a) Same function b) Same constant c) Same variable d) Multiple function

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

Arrays and Strings Unit


6
INTRODUCTION

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

We expect that this unit will take maximum 10 hours to complete.

How long ?

Unit Structure

Lesson- 1 : Familiar with Arrays


Lesson- 2 : Familiar with One Dimensional Array
Lesson- 3 : Familiar with Two Dimensional Arrays
Lesson- 4 : Introduction to Strings
Lesson- 5 : Understanding String Handling Functions

92
School of Science and Technology DCSA Program

Lesson-1 Familiar With Arrays


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define, describe, and explain the array data structure.


 Understand the declaration of an array.
 Be aware of initialization of an array.

Keywords Array, Declaration, Initialization, Pictorial Representation

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.

An array is used to store a collection of same type of data.

WHY DO WE USE ARRAY?

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.

1. Mention the significance of using an array in C language by your own concept.


………………….…………………………………………………………………..
……………………………………………………………………………………...
Activity ……..……………………………………………………………………………….

ARRAY DECLARATION PROCEDURE

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

data- type variable_name[array_size];

After array declaration you must put semicolon (;).

SOME DECLARATION EXAMPLE

1. If we want to store 6 integer type values in an array, we can write in C:


int numbers[6];
2. If we want to store 100 float type values in an array, we can write in C:
float marks[100];
3. If want to store 10 double type values in an array, we can write in C:
double marks[10];
4. If we want to store 20 char type values in an array, we can write in C:
char name[20];

Which of the following is true?


A. An array is stored various types of data at a time.
B. A particular component or element in an array is accessed by an index.

Study skills
Solution:
B. We know that an array is stored only same type of data and every element
is accessed by array index.

ARRAY INITIALIZATION PROCEDURE

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

Figure 6.1.1: Pictorial representation of an array


1. Suppose we want to store 10 students CGPA number as grade. Which declaration is
correct?
A. int number[10];
Study skills B. int CGPA[10];
C. float grade[10];
D. Char grade[20];

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

1. An array is a one kind of ……………………….. that can store a …………….


Assessment
sequential collection of elements of the ……………………..
2. An array must be declared ………………. it can be used in the program.

Multiple Choice Questions (MCQ)

1. After array declaration you must put—


a) Comma (,) b) Semicolon (;) c) Desh (-) d) Hash symbol (#)
2. The elements of the array occupy-
a) adjacent locations in memory b) Separate locations in memory
c) No locations in memory d) None of these
3. What is the correct declaration of float type array?
a) int num[10]; b) double test[10]; c) float value[10]; d) None of these
Exercises
1. What is an array? How do you declare an array in C language?
2. Explain the declaration and initialization procedure of an array with suitable example.
3. Discuss the pictorial presentation of an array with an example.

95
School of Science and Technology DCSA Program

Lesson-2 Familiar With One Dimensional Array


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand the various types of arrays


 Understand about one dimensional array
 Understand about two dimensional array
 Understand how to access the various arrays

Keywords Classification, 1D array, Pictorial Representation

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 (1D) ARRAY

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

The following declares an array called ‘numbers’ to hold 5 integers value:

int numbers[5];

SOME 1D ARRAY DECLARATION EXAMPLE

1. If we want to store 100 integer type values in an 1D array, we can write in C:


int numbers[100];

96
School of Science and Technology DCSA Program

2. If we want to store 50 float type values in an 1D array, we can write in C:


float marks[50];
3. If want to store 50 double type values in an 1D array, we can write in C:
double CGPA[50];
4. If we want to store 20 char type values in an 1D array, we can write in C:
char name[20];

One dimensional array is defined with a single subscript.

1. Mention the significance of using a 1D array in C language by your own concept.


……………………………………………………………………………………..
……………………………………………………………………………………..
Activity

1D ARRAY INITIALIZATION PROCEDURE

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.

There are two ways of 1D array initialization such as:

 Array Size is Specified Directly


 Array Size is Specified Indirectly

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

MEMORY REPRESENTATION OF 1D ARRAY


Which are the following is true?
A. float CGPA[5]={2.50,3.30,3,40,4.00,3.75}
B. integer values[5]={20.00,30,50.00,3.45,100}
C. int NUM[ ]={30,30,40,50,60,70,80,100}
Study skills
Solution:
Both A and C
In an n-element one dimensional array, the array elements are a[0],a [1],a[2],………..,a[n-1], as
illustrated in figure 4.2.1.

a[0] a[1] a[2] a[n-2] a[n-1]

Figure 6.2.1: Memory representation of one dimensional array with n-element

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;

numbers [0] numbers[1] numbers[2] numbers[3] numbers[4]

100 200 400 250 500


Figure 6.2.2: Memory representation of one dimensional array with five (5) elements

Which are the following is true?


A. The last index of 1D array is n-1.
B. A 1D array consists of different types of values.
C. In Specified Indirectly method array size declaration is not mandatory.
Study skills
Solution:
Both A and C

ELEMENT INSERTION PROCEDURE TO 1D ARRAY

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.

Program 6.2.1: Write a program that insert elements insertion to an 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

ELEMENTS DISPLAY OR PRINT FROM 1D ARRAY

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

scanf(“%d”,& numbers [ i ]); /* insert elements in the numbers array */


}
printf(“Array Values are:\n”);
for (j = 0; j < 10; j++ )
{
printf(“%d ”, numbers [ j ]); /* display or print elements from array */
}
getch();
}
…………………………………………………………………………………………..
Output
Enter the ten numbers:
10
50
48
30
400
33
456
678
100
500
Array Values are:
10 50 48 30 400 33 456 678 100 500

1. Which lines are used to insert elements to 1D array in program-1?


……. ………………………………………………………………………………..
..……………………………………………………………………………………..
Activity 2. Which lines are used to print elements from 1D array in program-2?
………………………………………………………………………………………..
………………………………………………………………………………………..

SOME EXAMPLE OF 1D ARRAY

Program 6.2.3 Write a program to calculate summation of 10 integer’s numbers.

#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

Enter the 5 number:50


The average value is: 30.00000

Program 6.2.5 Write a program to calculate the summation of following series.


22+42+62+………………………………………………………+1002

#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

Enter the 3 number:60


Enter the 4 number:600
Enter the 5 number:40
Greatest Number is:600

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

1. The lowest address corresponds to the ……………….. and the


Assessment
…………………to the………………… element.
2. In the ………………array, the size is specified by a ……..
3. When an array is declared, the values of each element are not set to……..

Multiple Choice Questions (MCQ)

1. In the Specified Indirectly method, we do not provide …


a) size to an array b) size to an data type
c) character type values d) none of these
2. One dimensional (1D) array is also known.
a) As data structure b) As simple array
c) As OOP d) None of these
3. When an array is declared, the values of each element are not set to—
a) One by b) Zero by c) Zero d) None of
default default automatically these
4. Which is used to manipulate 1D array?
c) Loop d) Data type e) Pointer f) None of these

Exercises

1. How do you define 1D array? Mention the benefits of 1D array.


2. Explain the declaration and initialization procedure of 1D array with suitable example.
3. Explain the memory representation of one dimensional array with proper example.
4. Write a program in C to sort a list and find its median

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

 Understand about two dimensional array.


 Understand how 2D array is declared in program.
 Be aware of memory representation of 2D array.

Keywords 2D array, Declaration , Initialization, Example

TWO DIMENSIONAL (2D) ARRAY

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

In general, the declaration form of two-dimensional (2D) array is expressed as


data-type array-name[row-size][column-size];
Where data-type is the valid data type in C and array-name is the user defined array name and row size
and column size is a positive valued integer expression, which indicates the row number and column
number of array respectively.

Two dimensional (2D) arrays are defined with a double subscript

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];

Data Type Column Size

Row Size
Array Name

Figure 6.3.1 Array declaration procedure


Consider the following data table, which shows the value of sales of three items by three salesmans:

104
School of Science and Technology DCSA Program

ItemNo 1 ItemNo 2 ItemNo 3


Salesmans#1 300 200 365
salesmans#2 200 100 150
salesmans#3 260 500 280

Table 1: Sales table of items


The table contains a total 9 values, three in each line. We can think of this table as a matrix consisting
of three (03) rows and three (03) columns. Here, each row represents the values of sales by a particular
salesmans and each column represents the values of sales of a particular item. So we can represent the
above concepts as a two dimensional matrix as follows:
int salesmans[3][3];

SOME 2D ARRAY DECLARATION EXAMPLE

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];

1. Mention the significance of using a 2D array in C language by your own concept.


……………………………………………………………………………………..
……………………………………………………………………………………..
Activity …….……………………………………………………………………………….
2. Suppose you are an assistant programmer of a software firm. Your firm has fifteen
employees. Now you need to create a program that gives the monthly salary of all
employees. For this purpose which type of array is required? And also show the
declaration procedure of array.
……………………………….……………………………………………………
………………………………….…………………………………………………

2D ARRAY INITIALIZATION PROCEDURE

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[3][3] = {1, 2, 3 ,4,5,6,7,8,9 } /* Valid declaration*/

int totalvals[4][3] = {1, 2, 3 ,4,5,6,7,8,9,10,11,12} /* Valid declaration*/

int totalvals [ ][2] = {1, 2, 3 ,4 } /* Valid declaration*/

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}
};

MEMORY REPRESENTATION OF 2D ARRAYS

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]

Row 1 a[1][0] a[1][1] a[1][2]

Row 2 a[2][0] a[2][1] a[2][2]

Row 3 a[3][0] a[3][1] a[3][2]

Figure 6.3.2: 2D array memory representation


Here, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is
the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'. In 2D,
the first index selects the row and second index selects the column within that row. Here, a[0][0] means
0th row and 0th column, a[0][1] means 0th row and 1th column, a[2][1] means 2nd row and 1st column
and so on.

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:

a[0][1]=a[0][0]+ size of data type


a[0][2]=a[0][1]+ size of data type
a[1][0]=a[0][2]+ size of data type

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:

a[0][1]=a[0][0]+ size of data type


=5000+ 2
=5002
a[0][2]=a[0][1]+ size of data type
=5002+ 2
=5004
a[1][0]=a[0][2]+ size of data type
=5004+ 2
=5006

For figure 6.3.2, the full memory location or address calculation is presented in the following table 2:

Elements Memory location/Address Elements Memory location/Address


a[0][0] 5000 a[2][0] 5012
a[0][1] 5002 a[2][1] 5014
a[0][2] 5004 a[2][2] 5016
a[1][0] 5006 a[3][0] 5018
a[1][1] 5008 a[3][1] 5020
a[1][2] 5010 a[3][2] 5022
Table 2: Memory location for array int a[4][3]

1. Which are the following is true?


A. float CGPA[5][2]={2.50,3.30,3,40,4.00,3.75}
B. int matrix[2][3]={20,30,50,45,100,90}
C. int NUM[ ][ ]={30,30,40,50,60,70,80,100,70,40,44,23}
Study skills
Solution:
Both B and C because, in B, the matrix size is identified, the row size is 2 and column
size is 3, so the stored values are total is 6 on the other hand, in C array sizes are not
identified, but it is identified by initialization values by compiler.
2. Which are the correct statements?
A. In 2D array, array size must be declared before access.
B. In 2D array, initialization is not mandatory if it is not declared array size.
C. A 2D array can be considered as a table, which has x number of rows and y
number of columns
Solution:
Both A and C

ELEMENT INSERTION PROCEDURE TO 2D ARRAY

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.

Program 6.3.1Write a program to insert elements to 2D array.

#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

ELEMENTS DISPLAY OR PRINT OR ACCESS FROM 2D ARRAY

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

printf("Enetr the marks of %d subject of %d student: ",row+1, col+1);


scanf("%d",&stumarks[row][col]);
}
}
printf("The marks of students are as follows:\n");
for ( row = 0; row < 2; row++ )
{
for(col=0;col<3;col++)
{ /* Display or print marks from the 2D array */
printf(" Marks of %d subject of %d student is: %d ",row+1,col+1,
stumarks[row][col]);
printf("\n");
}
printf("\n");
}
getch();
}
…………………………………………………………………………………………………
Output
Enter the 2 subjects marks of 3 students:
Enter the marks of 1 subject of 1 student: 30
Enter the marks of 1 subject of 2 student: 50
Enter the marks of 1 subject of 3 student: 70
Enter the marks of 2 subject of 1 student: 55
Enter the marks of 2 subject of 2 student: 60
Enter the marks of 2 subject of 3 student: 55
The marks of students are as follows:
Marks of 1 subject of 1 student is: 30
Marks of 1 subject of 2 student is: 50
Marks of 1 subject of 3 student is: 70

Marks of 2 subject of 1 student is: 55


Marks of 2 subject of 2 student is: 60
Marks of 2 subject of 3 student is: 55

1. Which lines are used to insert elements to 2D array in program-3?


…….…………….……………….………………………………………………..
…….…………….………………………..………………………………………..
Activity 2. Which lines are used to print elements from 2D array in program-4?
…..….……………………………….……………………………………………..
…..…………. …….. ……………….……………………………………………..
3. Suppose you have a 2D array with the named “ float CGPA[4][4]” and its first
element is stored at memory location 1004, what will be the addresses of remaining
elements?
…………………………………….…………………………………………….

SOME EXAMPLE OF 2D ARRAY

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:

Item No 1 Item No 2 Item No 3


Salesmans#1 300 200 365
salesmans#2 200 100 150
salesmans#3 260 500 280

#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

printf("Enter the value of item number %d : of sales man %d ",col+1,row+1);


scanf("%d",&salsmans[row][col]);
printf("\n");
}
}
for(row=0;row<3;row++)
{
printf("\n");
printf(" The total items of sales man %d is: ",row+1);
for(col=0;col<3;col++)
{
sum=sum+salsmans[row][col];
}
printf("%d\n",sum);
sum=0;
}getch();
}
……………………………………………………………………………………………
Output
Enter the value of item number 1 : of sales man 1 300
Enter the value of item number 2 : of sales man 1 200
Enter the value of item number 3 : of sales man 1 365
Enter the value of item number 1 : of sales man 2 200
Enter the value of item number 2 : of sales man 2 100
Enter the value of item number 3 : of sales man 2 150
Enter the value of item number 1 : of sales man 3 260
Enter the value of item number 2 : of sales man 3 500
Enter the value of item number 3 : of sales man 3 280
The total items of sales man 1 is: 865
The total items of sales man 2 is: 450
The total items of sales man 3 is: 1040

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

1. Write a program in C, that calculates summation of diagonal elements of a 3X3


matrix
2. Write a program in C, that calculates summation of non-diagonal elements of a
3X3 matrix
3. Suppose you are a programmer of a software firm. Your firm has fifteen employees.
Assignment
Now you need to write a program that gives the total salary of four month of all
employees.

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.

5. The annual examination results of 5 students are listed as follows:

Student Id Subject-1 Subject-2 Subject-3 Subject-4


1 45 50 70 60
2 47 57 69 70
3 78 67 89 77
4 66 55 45 40
5 67 68 69 70

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.

6. Given the two matrix A and B as follows:

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;
}

Multiple Choice Questions (MCQ)

1. Two Dimensional array stores the values in the form of-


a) Pointer
b) Matrix
c) Colum
d) None of these
2. Which is the valid initialization in 2D?
a) Matrix[2][2]={4 4 5 6}
b) Matrix[3][3]={5,6,7,3,8,9,10,11,12};
c) float
salary[3][2]={{1000.00,2000.50},{500.34,800.25},{3000.90,400
0.00}};
d) float
salary[3][2]={{1000.00,2000.50},{500.34,800.25},{3000.90,400
0.00},};

Exercises

1. How do you define 2D array? Mention the benefits of 2D array.


2. Distinguish between 1D and 2D array with proper example.
3. Explain the declaration and initialization procedure of 2D array with suitable example.
4. Explain the memory representation of two dimensional arrays with proper example.

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

 Understand about basic concept on Strings.


 Understand how strings are declared in C language.
 Understand how strings are initialized and accesses in C language.

Keywords Strings, Declaration , Initialization, Example

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:

“Bangladesh Open University”


If you need to include a double quote in the string, then you must be included a back slash as follows:

“\ “Bangladesh Open University\” ”


If you want to print or display a string with double quote then you should write the following line:

printf(“\“Hello ! Bangladesh Open University!!\” ”);


The output of this line is:

“Hello ! Bangladesh Open University!!”


But if you write the following line:

printf(“Hello ! Bangladesh Open University!!”);


Then the output will be:

Hello ! Bangladesh Open University!!


Generally, character type strings are frequently used to construct significant and understandable
programs. The common functions executed on character strings are as follows:

i. Reading and writing strings


ii. Joining strings together
iii. Copying one string to another string
iv. Comparing strings for equality
v. Pull out or extracting a portion of a string

115
School of Science and Technology DCSA Program

DECLARING STRING VARIABLES

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.

Strings are array of characters terminated by a null character '\0'.

DECLARATION EXAMPLE

Some examples are as follows:


char country[20];
char city[10];
char uniname[25];
Here, country, city and uniname are the string array variables name respectively. When the compiler
allocates a character string to a character array, it automatically supplies a null character (‘\0’) at the
end of the string. As a result, the size should be equal to the highest number of characters in the string
plus one (1).

When the compiler allocates a character string to a character array, it automatically


supplies a null character (‘\0’) at the end of the string.

INITIALIZING STRING VARIABLES

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:

char country[11]= “BANGLADESH”;


char country[11]={‘B’, ‘A’, ‘N’, ‘G’, ‘L’, ‘A’, ‘D’, ‘E’, ‘S’, ‘H’, ‘\0’};
The reason here that, the variable country had to be 11 elements long are that the string BANGLADESH
contains 10 characters and one element space is supplied for the null terminator (‘\0’). It is noted that,
when we initialize a character array by listing its elements, we must supply explicitly the null terminator
(‘\0’). In C programming language, it permits us to initialize a character array without identified the
number of elements. In such cases, the size of the array will be decided automatically, based on the
number of elements initialized. Consider the following example:

char department[ ]={‘S’, ‘S’, ‘T’, ‘\0’};


This example statement defines the array department as a three (3) element array.

116
School of Science and Technology DCSA Program

Which are the correct statements of the following?


A. Strings are summation of characters
B. ‘\o’ is the null terminator at the end of the strings
C. Strings are one dimensional array of characters
Study skills D. String data type is available in C language
E. When the compiler allocates a character string to a character array, it
automatically supplies a null character at the end of the string.
F. int name[8]= “ENGLAND”;
G. char city[9]= “NEW YORK”;
H. char department[11]= {‘O’, ‘P’, ‘E’, ‘N’, ‘ ’, ‘S’, ‘C’, ‘H’, ‘O’, ‘O’, ‘L’};

Solution:
C, E, and G are the correct statements ( Remember your study)

1. Mention the significance of strings in C language by your own concept.


…………………………………………………………………………………..
…………………………………………………………………………………..
Activity ………….……………………………………………………………………….
2. Suppose you are an assistant programmer of a software firm. Your firm has fifteen
employees. Now you need to create a program that stores all employee names in
Empname character type array. Mention the array declaration for this program.
…………………………………………………………………………………
…………………………………………………………………………………

READING STRINGS FROM USER

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.

Consider following example to read city name from user:

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

Consider the following example:


Program 6.4.1 Write a program to read a series of words from user at terminal using scanf( )
function.

#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:

Enetr your Text:


Bangladesh
Open
University
After Insertion text:
Bangladesh Open University
Reading a Line of Text
Practically, many programming applications, we need to read in an entire line of text from the user. It
is not possible to use scanf( ) function to read a line containing more than one word. We have already
known about getchar( ) function, that reads single character from the user. So by using this getchar( )
function repeatedly to read successive single characters from the input and place them into a character
array. Therefore, a entire line of text can be read and stored in an array. In this case, 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. Consider the following program:

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);

The following is shown as the gets() and puts() example

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.

Multiple Choice Questions (MCQ)

1. Strings are array of characters terminated by


a) a null b) a ‘\o’ c) a integer d) any character
character '\0' character value value

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

 Learn about syntaxes of some string handling functions.


 Learn how string handling functions are used in program with example.

Strings, Library functions , Concatenation, String compare,


Keywords
String copy, String length

STANDARD LIBRARY FUNCTIONS

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.

STRING HANDLING FUNCTIONS

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.

Following are the most commonly used string handling functions:

Function Name Description


strcat () This is used to concatenate two strings
strcmp( ) This is used to compares two strings

strcpy() This is used to copies one string over another string

strlen() This is used to determine the length of a string

122
School of Science and Technology DCSA Program

We will describe how each of these functions can be used in the processing of strings.

Standard library functions in C programming are built-in functions

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.

Some strcat() function example are given below:

Program 6.5.1 Write a C program to concatenate two strings

#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

Program 6.5.2 Write a C program to concatenate three strings

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

The general syntax of strcmp( ) function is:

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:

strcpy(destination array, source arry/source_string);

Consider the following examples:

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.

Program 6.5.5: Write a program to copy the contents of source to destination

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

Program 6.5.7 Write a program to count the length of string

#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

Which are the correct statements of the following?


A. rand() is a library function
B. ‘\o’ is the null terminator at the end of the strings
C. strcpy() is used to copy one string to another string
Study skills D. String compare syntax is as follows:
strcmp(string1,string2,string3);
E. String length function has two parameters.
F. String concatenation function has two parameters.
G. In strlen() function returns integer number.

Solution:
A, F, and G are the correct statements ( Remember your study)

1. Mention the significance of strings library function in C language by your own


concept.
2. Write a program to identify the length of the following string
Activity “Thank you!! You are welcome”
Summary

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

Assessment 1. Rands() is a string library function


2. The strcmp() function returns an integer value.
3. In C strcpy() function works like assignment operator.
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.

Multiple Choice Questions (MCQ)

1. Which one is the header file for strcmp() function?


a) sting.h b) strlib.h c) stdio.h d) none of these
2. strlen() function is used to
a) Determine the number of character b) Identify the value of character
in a line
c) Compare two strings d) None of these
3. Standard functions are included with C compilers, which are –
a) modifiable in b) rewriteable c) not rewritable d) none of these
program

4. strcat() function means


a) comparing two strings
b) joining two or more strings
c) copy source strings to destination
d) none of these

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

We expect that this unit will take maximum 15 hours to complete.

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

Lesson-1 Introduction to C functions


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand basic idea about C functions and its types.


 Learn necessity of functions in program.

Keywords Function, Necessity of Function, Types

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

In C, functions can be classified into two types such as:

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

User defined functions


C allows programmer or user to define their individual function according to their prerequisite. These
types of functions are known as user-defined functions. User defined functions are those functions
which are defined by or developed by the user at the time of writing program. The most important
difference between library functions and user defined functions is that library functions are not required
to be written by programmer or user, on the other hand a user defined function has to be defined or

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.

NEED FOR USER DEFINED FUNCTION


We mentioned earlier, a function is a block of code that performs a particular task. We can either use
the built-in library functions or we can create our own defined functions. In every C program must have
a main function to designate where the program has to start its execution. While it is probable to code
any program utilizing only main function, it leads to a number of problems.

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

Necessity of user defined function as follows:

1. User defined function provides modularity to the program.


2. The piece of a source program can be reduced by using user defined functions at proper places.
3. It is easy to locate and segregate a defective function for further exploration.
4. User defined functions helps to decompose the large program into small segments which makes
programmer easy to understanding, maintaining, debugging and testing.
5. It is easy to code reusability. We just have to call the function by its name to use it from
anywhere of a program.
6. A user defined function may be used by many other programs.

1. Mention the significance of using function in C language by your own idea.


…..……………………………………………………………………….……
…………………………………………………………………………………
Activity

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

2. A function is a block of code that performs a specific task.


3. User defined function provides modularity to the program.
4. A user defined function may be used by only specific programs.

Multiple Choice Questions (MCQ)

1. Every C program has at least one function, which is—


a) include
b) define
c) main()
d) return
2. A function is--
a) a block of code that performs a particular task
b) set of statements
c) a block of code that performs a verities task
d) set of modules
3. sqrt() function is a
a) user defined function
b) library function
c) main function
4. User defined functions helps to decompose the large program-
a) Into small segments
b) Into large segments
c) Into variable segments
d) None of these

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

Lesson-2 Function Prototype and Definition


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand function prototype.


 Explain function definition or declaration.
 Understand how a function is declared in program.
 Explain function calling procedure.

Keywords Function, Declaration, Prototype, Calling function

FUNCTION PROTOTYPE OR DECLARATION


User defined functions that a programmer writes will generally require a prototype. In programming, a
function prototype is a declaration of a function that specifies the function's name and type signature or
arguments and return type, but omits the function body. The function prototype gives basic structural
information such as (i) It tells the compiler what the function will return, (ii) What the function will be
called, and (iii) what arguments the function can be passed. Function prototype is declared before it is
defined in a program. Generally it is typed before main function of a program.

The general format for a function prototype or declaration is:

return-type function_name ( data_type arg_1,data_type arg_2 ..., data_type arg_N );

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

int addition( int num1, int num2 );


In this declaration or prototype example specifies that the function addition will accept two arguments,
both are integers, and function will return an integer type value. Here, do not forget the trailing semi-
colon (;). Without semicolon the compiler will possibly think that you are trying to write the actual
definition of the function.

Function prototype is declared before it is defined in a program. Generally it is typed


before main function of a program.

FUNCTION DEFINITION SYNTAX

The general form of function definition syntax in C programming language is as follows:

133
School of Science and Technology DCSA Program

return-type function_name( parameter list )


{
function-body
}
In the function definitions, the first line return-type function-name(parameter list) is known as
function header and the statement within curly braces { } is called function body. Function body is
combination of more than one statement.
We will describe all the parts of a function as follows:

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.

 Local variable declaration.


 Function statement that performs the tasks of the function.
 A return statement that return the value evaluated by the function.

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.

/* function returning the summation of two values */


int summation(int value1, int value2)
{
int result; /* local variable declaration */
result= value1+value2
return result;
}
HOW USER-DEFINED FUNCTION WORKS IN C PROGRAMMING?
We mentioned earlier, that every C program starts from main() function and program starts executing
the codes inside main() function. When the control of program reaches to function name inside main()
function the control of program jumps to function definition part and executes the codes inside it. When
all the codes inside that user-defined function are executed, control of the program jumps to the
statement just after function name from where it is called.

Considering the following example:

#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
}

Step-2 int summation(int value1, int value2)


Function {
return
………………………………..
………………………………..
……………………………….
}
In this above example, when function summation() is called from main() function the control jumps to
function definition part and executes all statements of summation() function and after executing all
statements it returns to statement just after function name summation() from where it is called.
FUNCTION CALLING
In C program, whereas creating a function, we give function definition of what the function has to do.
To use a function, we will have to call that function to perform the defined task. A function can be
called by using the function name in a statement of program.

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.

Program 7.2.1 Write a program to calculate the value z = xy using 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

1. Mention the significance of using function in C language by your own idea.


………………….…………………………………………………………….……
…………………………………………….………………………………………
Activity 2. Create a function named as “average” to find out average value of 10 numbers with
function definition.
…………………..…………………………..……………………………………..
……………………………………………..………………………………………
3. Write a program to determine the greatest common divisor(GCD) and least
common multiple (LCM) of two integer number using function
…………………………………………………….……………………………….
…………………………………………………….……………………………….

1. Suppose we want to determine summation in a range of 10 to 100 numbers using


function. Which is the correct declaration?
A. float number[10]; B. int summation[10,100]; C. double summation(1,100);
Study skills D. int summation (10,100);
Solution:
According to function declaration “D” is the correct function declaration.

2. Which is the correct answer?


a. Mul(x,y)=p; b. Mul[10,2]=x; c. X= mul[x,y]; d. X=mul(x,y);
Solution:
According to function declaration “D” is the correct function declaration.

3. Which are the incorrect function declarations?


A. Mul(x,y)=p; B. Int record(2,x); C. Float calculation(p,Q); D. P= mul(x,y);
Solution:
According to function definition and declaration “A”, “B”, and “C” are the incorrect
function declaration.

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

Multiple Choice Questions (MCQ)


Assessment 1. Function prototype is
a) declared before it is defined in a program
b) declared after it is defined in a program
c) declared any place in a program
d) declared after main() function
2. A function body consists of
a) Four parts
b) Two parts
c) Three parts
d) None of these

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

Lesson-3 Categories of User Defined Functions


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Classify different types of functions.


 Understanding difference between calling and called functions.

Keywords Categories, Calling function, Called function

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:

1. Function with no arguments and no return value


2. Function with no arguments and return value
3. Function with arguments and no return value
4. Functions with arguments and return value

In the next lessons we will describe these categories with example.

Summary

Summary
In this lesson we have
 Learned about categories of functions and its definitions

Assessment
1. Write down the function categories
….……………………………………………………………………………
Assessment ….……………………………………………………………………………

Exercises

1. Explain function categories with their definitions?


2. Explain the necessity of user defined function in a program.

139
School of Science and Technology DCSA Program

Lesson-4 Function With No Arguments and No Return Value


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain function with no arguments and no return value technique.

Keywords Function, Arguments, Return, Value

FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE

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

Multiple Choice Questions (MCQ)


Assessment 1. When a function has no arguments it does not-
a) receive data from the calling function
b) receive data from the called function
c) return data to calling function
d) none of these
2. If a function does not return value, we may be-
a) Used keyword float as return type
b) Used keyword void as return type
c) Used keyword int as return type
d) None of these

Exercises

1. Explain function categories with their definitions?


2. Write a program using function with no 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 no arguments and no return value procedure, that
calculates the value of Y in following series:
Y=12+34+56+……………………………………..+Nn

142
School of Science and Technology DCSA Program

Lesson-5 Function With No Arguments and Return Value


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain the function with no arguments and return value concept.

Keywords Function, No arguments, Return Value

FUNCTION WITH NO ARGUMENTS AND RETURN VALUE


When a function has no arguments but it may return a value so, we may be used return type.
The general syntax of this type of function is as follows:
return_type function_name( )
{
……………………………
Statements or function body
…………………………..
…………………………..
return variable-name/value
}
Here, return_type is data type name which is returned by function. In this type of function after
complete all statements of function; the keyword return with value or variable name may be used which
is shown in syntax.

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

1. Determine the output of the following program:


void main( ){
int X;
Study skills X =calculate( ); printf(“%d”,X);
}
float calculate( ){
float a,b; a= 2; b=5; return (pow(a,b));
}
2. Identify the errors of the following program segments:
void main(){
float p, q;
q= Calculate( ); printf(“%d,” q);
}
int Calculate( ){
float x=15,y=2; float t=0; t=x/y; return t;
}
Summary

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

Multiple Choice Questions (MCQ)


Assessment 1. A function has no arguments but it may-
a) Return a value
b) No return value
c) Call a function
d) None of these
2. Values of actual arguments are assigned to the-
a) actual parameters on a one to one manner
b) formal arguments on a one to many manner
c) formal arguments on a one to one manner
d) None of these

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

Lesson-6 Function With Arguments And No Return Value


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain the function with arguments and no return value concept.

Keywords Categories, With Arguments, No Return, Value

FUNCTION WITH ARGUMENTS AND NO RETURN VALUE


In this type of function category a function takes arguments from calling function but it does not return
value. In this case, we could make the calling function to read data from the user or terminal and pass
it on to the called function.

The general syntax of this type of function is as follows:

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

Figure 7.6.1: Arguments passing between calling and called function

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

1. Identify the errors of the following program segments:


i) main(){
int p, q;
Study skills Calculate(p,q); printf(“%d,” p);
}
void 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;
}
2. What will be the output of the program 1(ii) after error correction?

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

1. Create a function named as “power” to determine power of xy using function with


arguments and no return value concept.
………………………………………………………………………………..
…..……………………………………………………………………………
Assignment
2. Write a program to determine the volume of sphere using function with arguments
and no return value concept. The formulae of volume of sphere is as follows:
4
3
𝜋𝑟 3 , Where r is the radius of sphere.
………….……………………………………………………………………....

Assessment

Multiple Choice Questions (MCQ)


Assessment 1. Values of actual arguments are assigned to the-
a) actual parameters on a one to one b) formal arguments on a one to many
manner manner
c) formal arguments on a one to one d) None of these
manner
2. If the actual arguments are more than formal arguments, then-
a) the extra formal arguments are discarded
b) the extra actual arguments are changed
c) the extra formal arguments are discarded
d) the extra actual arguments are discarded
3. Formal arguments must be valid variable names and –
a) the actual arguments may be variable names, expressions, or constants
b) the actual arguments only variable names
c) the actual arguments may be constants
d) none of these
4. The arguments of calling function are called actual arguments and the arguments of
called function are called-
a) Formal b) Informal c) Actual d) None of
arguments arguments arguments these

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

Lesson-7 Functions With Arguments And Return Value

Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to
 Explain the function with arguments and return value concept.

Keywords Categories, Calling function, Called function

Function With arguments and Return Value


In this type of function category a function takes arguments from calling function and it returns a value
to calling function. So in this case, a variable must be used to receive value which is returned form
called function. In this category, we could make the calling function to read data from the user or
terminal and pass it on to the called function.
The general syntax of this type of function is as follows:

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.

Multiple Choice Questions (MCQ)

1. In function any mismatch in data type may also result in passing of –


a) garbage values
b) integer values
c) float types values
d) global values
2. The data type should be matched between actual arguments and
a) Global arguments
b) Local arguments
c) Formal arguments
d) Actual arguments

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

Lesson-8 Recursive Function


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define recursive function.


 Understand how recursive function executes in program.
 Learn the benefits of recursive functions.

Keywords Recursive function, Advantages, Disadvantages

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

ADVANTAGES AND DISADVANTAGES OF RECURSIVE FUNCTIONS

Advantages of recursive functions are as follows:

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

7. The length of the program can be reduced by using recursion technique.

Disadvantages of recursive functions are as follows:

1. Recursion technique is hard to think the logic of a recursive function.


2. It is also difficult to debug the code containing recursion.
3. It needs extra storage space.
4. This type of function is not efficient in execution speed and time

1. What is the benefit of recursive function in program?


……………………………………………………………………………….……
.……………………………………………………………………………………
Activity

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

Multiple Choice Questions (MCQ)

1. If a function does not return value, we may be-


a) Used keyword float as return type
b) Used keyword void as return type
c) Used keyword int as return type
d) None of these
2. When a function calls itself, this type of function is called
a) Recursive function.
b) Nested function
c) User defined function
d) None of these
3. Recursive function is flexible in
a) Array
b) Linked list
c) Data structure
d) Variable declaration
4. Every recursive function must be provided with-
a) A way to start the recursion
b) A way to end the recursion.
c) A way of length of the program
d) None of these

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

Lesson-9 Uses of Local and Global Variables in Function


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Define local and global variable.


 Understand the scope and lifetime of variables in functions.

Keywords Local and Global Variable, Scope, Lifetime of Variables

LOCAL AND GLOBAL VARIABLES


We have already known that C allows us to create functions of some sort and also known that functions
are used to break up large programs to overcome the program complexity. In programming language,
the variables can be categorized depending on the place of their declaration, as internal (i.e., local) or
external (i.e., global). A local variable is a variable that is declared inside a particular function. Local
variables are also referred to as automatic variables or internal variables. Local variables are declared
inside a function and they are created when the function is called and automatically destroyed when the
function is exited. Hence, they are called automatic.
Local variable example is shown in below:

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

Program 7.9.1: Write a C program to demonstrate local variable.

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

A local variable is a variable that is declared inside a particular function. Local


variables are also referred to as automatic variables or internal variables.

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:

Program 7.9.2: Write a C program to demonstrate global variable.

#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

result = num1+ num2+ num3;


return result;
}
void main()
{
clrscr();
auto int result;
num1 = 10;
num2 = 20;
num3 = 30;
result = sum_numbers();
printf("The sum of %d+%d+%d is:= %d\n",num1, num2,num3,result);
getch();
}
……………………………………………………………………………..
Output
The sum of 10+20+30 is:= 60

A global variable is a variable that is declared outside all functions. Global variables
are also referred to as external variables.

SCOPE AND LIFE TIME OF VARIABLES IN FUNCTION


We have already studied that how global and local variables are worked in function. In this section we
will study about scope and life time of variables in function. Scope is the area where a variable can be
accessed is known as scope of variable on the other hand life time is the time period for which a variable
exists in the memory is known as lifetime of variable.

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

Scope of block variables


It is notify that, block variables can be accessed within the block in which they are declared and can
also be accessed into the inner block which is within the current block but, can’t be accessed outside
the block. Following illustration is shown scope of block variables:

Program 7.9.3: Write a C program to demonstrate scope procedure of block variable

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

Life time of block variables


In this declaration block variables come into view as the control enters into the block and disappears as
the control go out of the block. Hence these variables can’t be accessed outside the block.
#include<stdio.h>
int main()
{
if(20<30)
{
int p=10; Scope of block
printf("p=%d",p);
variable
}
printf("\np=%d",p); /* can't be accessed */
return 0;
}
………………………………………………………………..
Output
Error: Undefined symbol “p” in function main()

Figure 7.10.1: Block variable life time example


Here, “if statement” has compound statement with a block. There is a conditional expression so the
variable p appears as control enters into the block and disappears on exit from the block. Hence variable
is not available outside the block.

163
School of Science and Technology DCSA Program

Scope of local variable


We have already known that a local variable is a variable that is declared inside a particular function.
Local variable can be used only in the function in which it is declared. The declaration and access area
is called scope of local variable. The visibility of local variables is limited to the home function in which
they are declared, local variables belongs to one function can’t be accessed from another function.
Consider the following program example:

Program 7.9.4: Write a C program to demonstrate scope procedure of local variable

#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()

Figure 7.10.2: Local variable scope example-1


Here, num variable is the local variable to main( ) function, it can’t be accessed from display_number(
) function, because the scope of num variable is limited to the main( ) function only. For this reason an
error will occur.

Again, consider the following program example:

#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

Figure 5.10.3: Local variable scope example-2


Here variable num is declared for two times that is in main( ) function and again in display_number( )
function. They are different memory locations; visibility of which is limited to their home functions. So
we have conclude that, variable belongs to one function can’t be accessed from another function.

The declaration and access area is called scope of local variable.

Life time of local variables


We know that the time period for which a variable exists in the memory is known as lifetime of variable.
Lifetime of local variables starts when control enters the function in which it is declared and it is
destroyed when control exists from the function. Local variables of a function do not remain their values
from one execution to another of a function because they lose their life at the end of every execution.
We have described this procedure in the previous section. Consider the following example as life time
of local variables.

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

Scope of global variable


We know that a global variable is a variable that is declared outside all functions. Global variables are
also referred to as external variables. The global variable can be used by all functions in the program.
These types of variables are globally accessed from any part of the program like function. These are
declared before main function. The global variable declaration area is called scope of global variable.
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.
Therefore, global variables are declared before main function. Consider the following program
example:

Program 7.9.6: Write a C program to demonstrate scope procedure of global variable

#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

Figure 7.10.4: Global variable scope example-1


Here, in the above example, variable num is declared on top of all the functions. It is global to both the
functions main( ) and display_numbers( ). The change in its value (num=num+100) in the function
display_nnumbers() reflected the change in main() because num is a common variable to both the
functions.

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

Consider the following another example:

#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().

Figure 7.10.5: Global variable scope example-2


Here, in the above example num is an global/external variable because declared outside both the
function main() and display_numbers(). But it is declared below the main() and above the
display_numbers() function, so it is global to display_numbers( ) but, not to the main() function.
Therefore, num can’t be accessed from the main(), so compiler produces an error. Global variables are
initialized with zero if not assigned with any value by the program.

Life time of global variable


We already knew that, the time period for which a variable exists in the memory is known as lifetime
of variable. Global variables survive in the memory as long as the program is running. These variables
are destroyed from the memory when the program terminates. Therefore, these variables occupy
memory longer than local variables.

The time period for which a variable exists in the memory is known as lifetime of
variable

1. What are the benefits of local and global variables?


…….…………………………………………………………………….……
..………………………………………………………………………………
Activity

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.

Multiple Choice Questions (MCQ)


1. Local variables are also referred to as-
a) Automatic b) External c) Fixed type d) None of
variables. variables variables these
2. a global variable is a variable that is declared-
a) Outside all b) Inside of main c) Outside only d) Only outside of
functions function a function main function
3. Global variables are
a) Only alive in the entire program b) Both alive and active throughout the
entire program
c) Only active throughout the entire d) None of these
program
4. The area where a variable can be accessed is known as
a) Block of b) Non block c) Scope of d) Life time of
variable of variable variable variable
5. Block variables are declared
a) within a pair of b) within a pair c) within a pair ( ) d) None of
braces { } of [ ] these
Exercise
1. Define local and global variable and explain with their properties with an example.
2. Explain the necessity of global variables in a program.
3. Distinguish between global and local variables.
4. What do you mean by scope and life time of variable? Explain with proper example.

169
School of Science and Technology DCSA Program

Structures and Unions Unit


8
INTRODUCTION

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

We expect that this unit will take maximum 5 hours to complete.

How long ?

Unit Structure
Lesson- 1 : Introduction to C Structures
Lesson- 2 : Structure Initialization

170
School of Science and Technology DCSA Program

Lesson-1 Introduction to C Structures


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand basic idea about C structures.


 Learn necessity of structures in C program.
 Understand how a structures are declared and defined in program.

Keywords Structure, Definition, Declaration, Member

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

struct Books book, book1, book2, book3;

declares book, book1, book2 and book3 as variables of type struct Books.

A structure is a collection of deferent type variables under a single name. Structures


assist to arrange complex data in a more meaningful.

ACCESSING STRUCTURE MEMBERS


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. The member access operator (.) is coded as a period between
the structure variable name and the structure member that we wish to access.

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.

1. Describe what is wrong in the following structure declaration:


struct
{
int number;
Study skills float price;
}
void main()
{
……………
}
2. Find the error(s) from the following code segments:

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);
………………………
}

3. Describe what is wrong in the following structure declaration:


struct
{
int number;
float price;
}
void main()
{
……………
}

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

Multiple Choice Questions (MCQ)


Assessment 1. A structure is a well-situated tool for handling—

a) A collection of logically related data b) A collection of physical related data


items items
c) Single logically related data items d) None of these.
2. To define a structure, we must use the keyword—
a) Structure b) struct statement c) Structure tag d) None of these
statement statement
3. If we want to access any member of a structure, we may use the
a) (&) operator b) (%) operator c) (.) operator d) ( | | ) operator
4. Which of the following is correct?
a) structure student1=(100,20,400.50 , b) structure student1={100,20,400.50 ,
“XXX”); “XXX”};
c) struct student1= “100,20,400.50 , d) struct student1= {100,20,400.50 ,
“XXX””; “XXX”};

Exercises

1. What is structure? Explain structure declaration procedure with an example.


2. What do you mean by structure initialization? Explain with proper example.
3. How does a structure differ from an array?

176
School of Science and Technology DCSA Program

Lesson-2 Structures Initialization


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain procedure of structure initialization.


 Understand the comparison of structure variables.

Keywords Structure, Initialization, Comparison, Variable

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};
………………………..
………………………..
}

COMPARISON OF STRUCTURE VARIABLES

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

Program 8.2.1: Write a C program to illustrate the 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.

1. Mention the significance of using structure in C language by your own idea.


……………………………………………………………………………….……
.……………………………………………………………………………………
Activity
1. Describe what is wrong in the following structure declaration:
struct test_rec
{
int val1;
Study skills int val2;
float price;
}test={70,2.4,320};
2. Find the error(s) from the following code segments:
struct product
{
int pro_id;
char pro_name;
float pro_price;
int quantity;
} prolist={T80,20,47.50,5.00};
void main()
{
struct prolist2={600, ‘B’,22,3.50};
………………………..
………………………..
}

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

Multiple Choice Questions (MCQ)


Assessment 1. To define a structure, we must use the keyword—
a) Structure statement
b) struct statement
c) Structure tag statement
d) None of these
2. Which of the following is correct?
a) structure student1=(100,20,400.50 , “XXX”);
b) structure student1={100,20,400.50 , “XXX”};
c) struct student1= “100,20,400.50 , “XXX””;
d) struct student1= {100,20,400.50 , “XXX”};
3. Two variables of the same structure type can be compared the-
a) Same way as formal variables of a function
b) Same way as normal variables
c) Same way as array initialization
d) None of these
4. When initializing an object of structure, it must be-
a) Non-empty, brace-enclosed, comma-separated
b) Empty, brace-enclosed
c) Only non-empty and brace-enclosed
d) Only comma-separated

Exercises

1. What do you mean by structure initialization? Explain with proper example.


2. How does a structure differ from an array?
3. Mention and describe the various comparisons of structure variables with an example.

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

We expect that this unit will take maximum 6 hours to complete.

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

Lesson-1 Introduction to C Pointers


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Understand basic idea about C Pointers.


 Learn necessity of pointers in C program.
 Understand the advantages and disadvantages of pointers.

Keywords Pointer, Advantages, Disadvantages, Address

PRELIMINARY CONCEPT OF POINTERS

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:

1. By using pointers we can access a data which is available outside a function.


2. By using pointer variable we can implement dynamic memory allocation.
3. Pointers provide a way to return more than one value to the functions.
4. Pointer reduces the storage space and complexity of the program.
5. Pointer reduces the execution time of the program and increases the execution speed of
program.
6. Provides an alternate way to access array elements.
7. Pointers can be used to pass information back and forth between the calling function and called
function.
8. A pointer allows us to perform dynamic memory allocation and de-allocation.
9. With the help of pointer we can build complex data structures such as linked list, stack, queues,
trees, graphs etc.
10. A pointer allows us to resize the dynamically allocated memory block.

Disadvantages of pointers in C
The drawbacks of pointers in c are mentioned bellow:

1. Uninitialized pointers might cause segmentation fault.

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.

Variable Value Address

value1 200 80500

value2 80500 80548

Figure 9.1.1: Pointer variable concept

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.

ACCESSING THE ADDRESS OF A VARIABLE


In C language, the address of a variable can be known with the help of the operator ‘&’. The operator
‘&’ immediately prior a variable returns the address of the variable associated with it. For instance, the
statement: value2=&value1; would assign the address 80500(the location of variable value1 in figure
7.1.1 to the variable value2. The ‘&’ operator can be said as ‘address of’. This operator can be used
only with a simple variable or an array element.

1. Mention the significance of using pointers in C language by your own idea.


………………………………………..……………………………………….……
……………………………………………………………………..………………
Activity
1. Mention the significance of the following statement:

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

Multiple Choice Questions (MCQ)


Assignment
1. A pointer is a variable that contains an address of-
Assessment
a) Another same type of variable b) Another different type of variable
c) Another function d) None of these
2. Dynamic memory allocation cannot be performed without-
Assessment a) Using pointers b) Using function c) Using variable d) Using array
3. Pointer reduces the
a) Programming speed b) Execution time of the program
c) Memory size d) None of these
4. Pointer increases the
a) Execution speed of program. b) Memory Size
c) Execution time of program d) None of these
5. The address of a variable can be known with the help-
a. Of the b. Of the c. Of the operator d. Of the operator
operator ‘&’ operator ‘#’ ‘$’ ‘@’

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

Lesson-2 Pointer Declaration and Initialization


Learning Outcomes

Outcomes

Upon completion of this lesson you will be able to

 Understand declaration procedure of pointer.


 Learn initialization procedure of pointer.

Keywords Pointer, Declaration, Initialization

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 :

i. The asterisk (*) tells that pointer_name is a pointer variable


ii. pointer_name needs a memory location
iii. pointer_name points to a variable of type data-type

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

Such invalid pointer declaration example as follows:

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.

INITIALIZATION OF POINTER VARIABLE

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.

1. Mention the significance of using * operator in pointer declaration.


……………………………………………………………………………….……
….…………………………………………………………………………………
Activity
1. State the errors from the following code segment
void main()
{
int ptr1, a,b;
Study skills float *ptr, x, y;
ptr1=&x;
ptr=&b;
x=&y;
y=*ptr;
}
Summary

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.

Multiple Choice Questions (MCQ)

1. Pointers are used in C program to access-


a) The memory and manipulate the memory address b) The variable
c) The functions d) None of these
2. Pointer variable contains address of variable of-
a) Different data b) Same data type c) Different type d) Different type array
type function
3. Pointer initialization is the process of assigning address of a variable to
a) Variable b) Function c) Array d) Pointer variable.

Exercises

1. Explain pointer declaration procedure with example.


2. Explain pointer initialization procedure with example.

187
School of Science and Technology DCSA Program

Lesson-3 Accessing Variable and Pointer Expression


Learning Outcomes

Outcomes
Upon completion of this lesson you will be able to

 Explain how pointers are accessed variable.


 Explain pointer expression in a program.

Keywords Pointer, Variable Access, Expression

ACCESSING A VARIABLE THROUGH ITS POINTER


When a pointer has been assigned the address of variable, in this situation the question is how to access
the value of the variable using the pointer. Accessing a variable through its pointer we should follow
three steps such as (a) at first we define a pointer variable (b) secondly, assign the address of a variable
to a pointer and (c) finally access the value at the address available in the pointer variable. This is done
by using indirection operator which is also known as unary operator (*), that returns the value of the
variable located at the address specified by its operand. Consider the following statements:

int data, *p, x;


data = 1000;
p=&data;
x=*p;

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:

A=*p1**p2; this is same as (*p1) * (*p2)


SUM=SUM+*p1;
B=10*-*p2/ *p1; this is same as (10*(-(*p2)))/(*p1)
*p2=*p2+100;
We can also add integers to or subtract integers from pointers as well as to subtract one pointer from
another pointer. For instance,

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

*p2 = *p2+10; *p1 =*p2-3;z = *p1 * *p2-5;


printf(“value of A = %d,and B = %d\n”, A,B);printf(“ value of z = %d\n”,z);
getch();
}
………………………………………………………..…………………………………….
Output
value of A = 20, and B = 10
value of x = 195, and y= 25
value of A = 17, and B = 20
value of z =335

1. Describe what is wrong in the following pointer declaration:


void main(){
int x,y,p1p2;p1=&x; p2=*p2;
}
Study skills 2. Find the error(s) from the following code segments:
void main(){
int *p1,*p2, x,y,z,mul,sum;
x=p1-p2; y=p2/10; sum=sum+p2;mul=mul*p2;
p2=&*x;z=*p1 + *p2++;
}

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

1. Write a program to determine the summation of three integers values using


pointers
…………………………………………………………………………………..
……….………………………………………………………………………….
Assignment
Assessment

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

1. Explain how variables are accessed using pointer.


2. Write a program that determines summation, subtraction, multiplication and division using
pointer variable.

190
School of Science and Technology DCSA Program

UNITS TRUE / FALSE ANSWER

Unit 4 : Lesson 2 : 1T, 2 F, 3T


Lesson 3 : 1T, 2 T
Lesson 4 : 1T, 2 F
Unit 6 : Lesson 5 : 1F, 2T, 3T, 4T
Unit 7: Lesson 1 : 1T, 2T, 3T, 4F
Lesson 7 : 1T, 2T, 4F
Lesson 8 : 1F, 2T, 3T, 4F, 5F, 6T, 7T
Lesson 9 : 1F, 2F, 3F, 4T, 5T
Unit 9: Lesson 2 : 1T, 2T, 3F
Lesson 3 : 1T, 2T, 3T

UNITS MCQ ANSWER

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, 4a
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, 4d
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, 3d

191

You might also like