0% found this document useful (0 votes)
8 views97 pages

Introduction To Computer Programming

Uploaded by

cpine0223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views97 pages

Introduction To Computer Programming

Uploaded by

cpine0223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SCS101 INTRODUCTION TO

COMPUTER PROGRAMMING
TUTORIAL
Dr. TIRUS MUYA

MURANG’A UNIVERSITY OF TECHNOLOGY


COMPUTER SCIENCE DEPT.

0|Page S C S 1 0 1 b y Dr. T I R U S M U Y A
Welcome to C Programming Language

C Programming Language is a very popular computer programming language through


which users and computers can communicate. Using this series of tutorials, one can
learn C Programming Language from the basics. Every topic in these tutorials is
explained with clear information and good examples. The content of all the topics
is prepared by very experienced and expert faculty.What is C?

C is a computer programming language used to design computer softwares and


applications.

Why do we use C?

C programming language is very popular computer language used to design computer


softwares and applications.

Who invented C?

C Programming Language was invented in the year of 1972 by Dennis


Retchie (Dennis MacAlistair Ritchie). He was an American Computer Scientist
worked at Bell Labs as researcher along with Ken Thompson. He was born on 9th
September 1941 and lived till 12th October 2011. He is said to be the Father of C.

Softwares used to create and execute C Program?

Following are the softwares and applications used to create and execute C
programs...

1. Turbo C -
2. Turbo C++ -
3. GNU C -
4. Code Blocks -
5. Net Beans –

Computer Languages

Generally, we use languages like english, hindi, telugu etc., to make communication
between two persons. That means, when we want to make communication between
two persons we need a language through which persons can express their feelings.
Similarly, when we want to make communication between user and computer or
between two or more computers we need a language through which user can give
information to computer and vice versa. When user wants to give any instruction to
the computer the user needs a specific language and that language is known as

1|Page SCS 101 by TIRUS MUYA


computer language. User interacts with the computer using programs and that
programs are created using computer programming languages like C, C++, Java etc.,

Computer languages are the languages through which user can communicate
with the computer by writing program instructions.

Every computer programming language contains a set of predefined words and a set
of rules (syntax) that are used to create instructions of a program.

Computer Languages Classification

Over the years, computer languages have been evolved from Low Level to High Level
Languages. In the earliest days of computers, only Binary Language was used to write
programs. The computer languages are classified as follows...

Low Level Language (Machine Language)

Low Level language is the only language which can be understood by the
computer. Binary Language is an example of low level language. Low level language
is also known as Machine Language. The binary language contains only two symbols
1 & 0. All the instructions of binary language are written in the form of binary
numbers 1's & 0's. A computer can directly understand the binary language. Machine
language is also known as Machine Code.

As the CPU directly understands the binary language instructions, it does not
requires any translater. CPU directly starts executing the binary language
instructions, and takes very less time to execute the instructions as it does not
requires any translation. Low level language is considered as the First Generation
Language (1GL).

Advantages

• A computer can easily understand the low level language.


• Low level language instructions are executed directly without any
translation.
• Low level language instructions require very less time for thier execution.

Disadvantages

2|Page SCS 101 by TIRUS MUYA


• Low level language instructions are very difficult to use and understand.
• Low level language instructions are machine dependent, that means a
program written for a particular machine does not executes on other
machine.
• In low level language, there is more chance for errors and it is very difficult
to find errors, debug and modify.

Middle Level Language (Assembly Language)

Middle level language is a computer language in which the instructions are created
using symbols such as letters, digits and special characters. Assembly language is an
example of middle level language. In assembly language, we use predefined words
called mnemonics. Binary code instructions in low level language are replaced with
mnemonics and operands in middle level language. But computer can not understand
mnemonics, so we use a translator called Assembler to translate mnemonics into
binary language. Assembler is a translator which takes assembly code as input and
produces machine code as output. That means, computer can not understand middle
level language, so it needs to be translated into low level language to make it
understandable by the computer. Assembler is used to translate middle level
language to low level language.

Advantages

• Writing instructions in middle level language is easier than writing


instructions in low level language.
• Middle level language is more readable compared to low level language.
• Easy to understand, find errors and modify.

Disadvantages

• Middle level language is specific to a particular machine architecture that


means it is machine dependent.
• Middle level language needs to be translated into low level language.
• Middle level language executes slower compared to low level language.

High Level Language

High level language is a computer language which can be understood by the users.
High level language is very similar to the human languages and have a set of grammar
rules that are used to make instructions more easily. Every high level language have
a set of predefined words known as Keywords and a set of rules known as Syntax to
create instructions. High level language is more easier to understand for the users
but the computer can not understand it. High level language needs to be converted
into low level language to make it understandable by the computer. We
use Compiler or interpretor to convert high level language to low level language.

Languages like COBOL, FORTRAN, BASIC, C ,C++, JAVA etc., are the examples of high
level languages. All these programming languages use human understandable
language like english to write program instructions. These instructions are converted
to low level language by the compiler so that it can be understood by the computer.

3|Page SCS 101 by TIRUS MUYA


Advantages

• Writing instructions in high level language is more easier.


• High level language is more readable and understandable.
• The programs created using high level language runs on different machines
with little change or no change.
• Easy to understand, create programs, find errors and modify.

Disadvantages

• High level language needs to be translated to low level language.


• High level language executes slower compared to middle and low level
languages.

The following figure provides few key points related to the computer languages.

From the above figure, we can observe the following key points...

• The programming languages like C, C++, Java etc., are written in High level
language which is more comfortable for the developers.
• High level language is more closer to the users.
• Low level language is more closer to the computer. Computer hardware can
understand only the low level language (Machine Language).
• The program written in high level language needs to be converted to low level
language to make communication between the user and the computer.
• Middle level language is not closer to both user and computer. We can
consider it as a combination of both high level language and low level
language. When we execute a C program it undergoes with following
process…

4|Page SCS 101 by TIRUS MUYA


Program Development Life Cycle

When we want to develop a program using any programming language, we follow a


sequence of steps. These steps are called phases in program development. The
program development life cycle is a set of steps or phases that are used to develop
a program in any programming language.

Generally, program development life cycle contains 6 phases, they are as follows….

• Problem Definition
• Problem Analysis
• Algorithm Development
• Coding & Documentation
• Testing & Debugging
• Maintenance

1. Problem Definition

In this phase, we define the problem statement and we decide the boundaries of the
problem. In this phase we need to understand the problem statement, what is our
requirment, what should be the output of the problem solution. These are defined
in this first phase of the program development life cycle.

5|Page SCS 101 by TIRUS MUYA


2. Problem Analysis

In phase 2, we determine the requirements like variables, functions, etc. to solve


the problem. That means we gather the required resources to solve the problem
defined in the problem definition phase. We also determine the bounds of the
solution.

3. Algorithm Development

During this phase, we develop a step by step procedure to solve the problem using
the specification given in the previous phase. This phase is very important for
program development. That means we write the solution in step by step statements.

4. Coding & Documentation

This phase uses a programming language to write or implement actual programming


instructions for the steps defined in the previous phase. In this phase, we construct
actual program. That means we write the program to solve the given problem using
programming languages like C, C++, Java etc.,

5. Testing & Debugging

During this phase, we check whether the code written in previous step is solving the
specified problem or not. That means we test the program whether it is solving the
problem for various input data values or not. We also test that whether it is providing
the desired output or not.

6. Maintenance

During this phase, the program is actively used by the users. If any enhancements
found in this phase, all the phases are to be repeated again to make the
enhancements. That means in this phase, the solution (program) is used by the end
user. If the user encounters any problem or wants any enhancement, then we need
to repeat all the phases from the starting, so that the encountered problem is solved
or enhancement is added.

Design Strategies

a) Top-Down Strategy

The top-down strategy uses the modular approach to develop the design of a system.
It is called so because it starts from the top or the highest-level module and moves
towards the lowest level modules.

In this technique, the highest-level module or main module for developing the
software is identified. The main module is divided into several smaller and simpler
submodules or segments based on the task performed by each module. Then, each
submodule is further subdivided into several submodules of next lower level. This

6|Page SCS 101 by TIRUS MUYA


process of dividing each module into several submodules continues until the lowest
level modules, which cannot be further subdivided, are not identified.

b) Bottom-Up Strategy

Bottom-Up Strategy follows the modular approach to develop the design of the
system. It is called so because it starts from the bottom or the most basic level
modules and moves towards the highest level modules.

In this technique,

a) The modules at the most basic or the lowest level are identified.
b) These modules are then grouped together based on the function performed
by each module to form the next higher-level modules.
c) Then, these modules are further combined to form the next higher-level
modules.
d) This process of grouping several simpler modules to form higher level modules
continues until the main module of system development process is achieved.

7|Page SCS 101 by TIRUS MUYA


C Program Basics

C is a structured programming language. Every c program and its statements must


be in a particular structure. Every c program has the following general structure...

Line 1: Comments - They are ignored by the compiler

This section is used to provide small description of the program. The comment lines
are simply ignored by the compiler that means they are not executed. In C, there
are two types of comments.

1. Single Line Comments: Single line comment begins with // symbol. We can
write any number of single line comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol
and ends with */. We can write any number of multiple lines comments in a
program.

In a C proogram, the comment lines are optional. Based on the requirment, we write
the comments. All the comment lines in a C program just provide the guidelines to
understand the program and its code.

Line 2: Preprocessing Commands

Preprocessing commands are used to include header files and to define constants.
We use #include statement to include header file into our program. We
use #define statement to define a constant. The preprocessing statements are used

8|Page SCS 101 by TIRUS MUYA


according to the requirment. If we don't need any header file,then no need to write
#include statement. If we don't need any constant, then no need to write #define
statement.

Line 3: Global Declaration

Global declaration is used to define the global variables, which are common for all
the functions after its declaration. We also use the global declaration to declare
functions. This global declaration is used based on the requirment.

Line 4: int main()

Every C program must write this statement. This statement (main) specifies the
starting point of the C program execution. Here, main is a user defined method
which tells the compiler that this is the starting point of the program execution.
Here, int is a datatype of a value that is going to return to the Operating System
after completing the main method execution. If we don't want to return any value,
we can use it as void.

Line 5: Open Brase ( { )

The open brase indicates the begining of the block which belongs to the main
method. In C program, every block begins with '{' symbol.

Line 6: Local Declaration

In this section, we declare the variables and functions that are local to the function
or block in which they are declared. The variables which are declared in this section
are valid only within the function or block in which they are declared.

Line 7: Executable statements

In this section, we write the statements which perform tasks like reading data,
displaying result, calculations etc., All the statements in this section are written
according to the requirment.

Line 9: Closing Brase ( } )

The close brase indicates the end of the block which belongs to the main method.
In C program every block ends with '}' symbol.

Line 10, 11, 12, ...: Userdefined function()

This is the place where we implement the userdefined functions. The userdefined
function implementation can also be performed before the main method. In this
case, the user defined function need not to be declared. Directly it can be
implemented, but it must be before the main method. In a program, we can define
as many userdefined functions as we want. Every user defined function needs a
function call to execute its statements.General rules for any C program

9|Page SCS 101 by TIRUS MUYA


1. Every executable statement must end with semicolon symbol (;).
2. Every C program must contain exactly one main method (Starting point of
the program execution).
3. All the system defined words (keywords) must be used in lowercase letters.
4. Keywords cannot be used as user defined names (identifiers).
5. For every open brace ({), there must be respective closing brace (}).
6. Every variable must be declared before it is used.

C Character Set

As every language contains a set of characters used to construct words, statements


etc., C language also has a set of characters which include alphabets,
digits and special symbols. C language supports a total of 256 characters.

Every C program contains statements. These statements are constructed using words
and these words are constructed using characters from C character set. C language
character set contains the following set of characters...

1. Alphabets
2. Digits
3. Special Symbols

Alphabets

C language supports all the alphabets from english language. Lower and upper case
letters together supports 52 alphabets.

lower case letters - a to z

UPPER CASE LETTERS - A to Z

Digits

C language supports 10 digits which are used to construct numerical values in C


language.

Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols

C language supports rich set of special symbols that include symbols to perform
mathematical operations, to check conditions, white spaces, back spaces and other
special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline


space NULL bell backspace verticaltab etc.,

Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.

10 | P a g e SCS 101 by TIRUS MUYA


Every C program is a collection of instructions and every instruction is a collection
of some individual units. Every smallest individual unit of a c program is called token.
Every instruction in a c program is a collection of tokens. Tokens are used to
construct c programs and they are said to the basic building blocks of a c program.

In a c program tokens may contain the following...

1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values

In a C program, collection of all the keywords, identifiers, operators, special


symbols, constants, strings and data values are called as tokens.

Keywords

In C programming language, keywords are special words with predefined meaning.


Keywords are also known as reserved words in C programming language.
In C programming language, there are 32 keywords. All the 32 keywords has their
own meaning which is already known to the compiler.

Keywords are the reserved words with predefined meaning which already
known to the compiler

Whenever C compiler come across a keyword, automatically it understands its


meaning.

Properties of Keywords

1. All the keywords in C programming language are defined as lowercase


letters so they must be use only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user defined names like variable, functions,
arrays, pointers etc...
4. Every keyword in C programming language, represents something or
specifies some kind of action to be performed by the compiler.

The following table specifies all the 32 keywords with their meaning...

11 | P a g e S C S 1 0 1 b y Dr. T I R U S M U Y A
C Identifiers

In C programming language, programmers can specify their own name to variable,


array, pointer, function, lable etc... Identifier is a collection of characters which
acts as name of variable, function, array, pointer, strcture, lable etc... In other
words, an identifier can be defined as user defined name to identify an enity
uniquely in c programming language that name may be of variable name, function
name, array name, pointer name, structure name or a lable.

Identifier is a user defined name of an entity to identify it uniquely during the


program execution

12 | P a g e SCS 101 by TIRUS MUYA


Example

int marks;

char studentName[30];

Here, marks and studentName are identifiers.

Rules for Creating Identifiers

1. An identifier can contain letters (UPPERCASE and


lowercase), numerics & underscore symbol only.
2. An identifier should not start with numerical value. It can start with a letter
or an underscore.
3. We should not use any special symbols in between the identifier even
whitespace. However, the only underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for length of an identifier. However, compiler consider first
31 characters only.
6. An identifier must be unique in its scope.

Rules for Creating Identifiers for better programming

The following are the commonly used rules for creating identifiers for better
programming...

1. The identifier must be meaningfull to describe the entity.


2. Since, starting with underscore may create conflict with system names, so
we avoid starting an identifier with underscore.
3. We, start every identifier with a lowercase letter. If identifier contains
more than one word then first word starts with lowercase letter and second
word onwords first letter is used as UPPERCASE letter. We can also use an
underscore to separate multiple words in an identifier.

Datatypes

Data used in c program is classified into different types based on its properties. In c
programming langauge, datatype can be defined as a set of values with similar
characteristics. All the values in a datatype have the same properties.

Datatypes in c programming language are used to specify what kind of value can be
stored in a variable. The memory size and type of value of a variable are determined
by varible datatype. In a c program, each variable or constant or array must have a
datatype and this datatype specifies how much memory is to be allocated and what
type of values are to be stored in that variable or constant or array. The formal
definition of datatype is as follows...

13 | P a g e SCS 101 by TIRUS MUYA


Datatype is a set of value with predefined characteristics. Datatypes are used
to declare variable, constants, arrays, pointers and functions.

In c programming language, datatypes are classified as follows...

1. Primary Datatypes (Basic Datatypes OR Predefined Datatypes)


2. Derived Datatypes (Secondary Datatypes OR Userdefined Datatypes)
3. Enumeration Datatypes
4. Void Datatype

Primary Datatypes

The primary datatypes in C programming language are the basic datatypes. All the
primary datatypes are already defined in the system. Primary datatypes are also
called as Built-In datatypes. The following are the primary datatypes in c
programming lanuage...

1. Integer Datatype
2. Floating Point Datatype
3. Double Datatype
4. Character Datatype

14 | P a g e SCS 101 by TIRUS MUYA


Integer Datatype

Integer datatype is a set of whole numbers. Every integer value does not have the
decimal value. We use the keyword "int" to represent integer datatype in c. We use
the keyword int to declare the variables and to specify return type of a function.
The integer datatype is used with different type modifiers like short, long, signed
and unsigned. The following table provides complete details about integer datatype.

Floating Point Datatypes

Floating point datatypes are set of numbers with decimal value. Every floating point
value must contain the decimal value. The floating point datatype has two
variants...

• float
• double

15 | P a g e SCS 101 by TIRUS MUYA


We use the keyword "float" to represent floating point datatype and "double" to
represent double datatype in c. Both float and double are similar but they differ in
number of decimal places. The float value contains 6 decimal places whereas double
value contains 15 or 19 decimal places. The following table provides complete
details about floating point datatypes.

Character Datatype

Character datatype is a set of characters enclosed in single quotations. The following


table provides complete details about character datatype.

The following table provides complete information about all the datatypes in c
programming language...

16 | P a g e SCS 101 by TIRUS MUYA


void Datatype

The void datatype means nothing or no value. Generally, void is used to specify a
function which does not return any value. We also use the void datatype to specify
empty parameters of a function.

Enumerated Datatype

An enumerated datatype is a user-defined data type that consists of integer


constants and each integer constant is given a name. The keyword "enum" is used
to define enumerated datatype.

Derived Datatypes

Derived datatypes are user-defined data types. The derived datatypes are also called
as user defined datatypes or secondary datatypes. In c programming language, the
derived datatypes are created using the following concepts...

• Arrays
• Structures
• Unions
• Enumeration

Variables

Variables in c programming language are the named memory locations where user
can store different values of same datatype during the program execution. That
means, variable is a name given to a memory location in which we can store different
values of sasme datatype. In other words a variable can be defined as a storage
container to hold values of same datatype during the program execution. The formal
definition of datatype is as follows...

Variable is a name given to a memory location where we can store defferent


values of same datatype during the program execution.

Every variable in c programming language must be declared in the declaration


section before it is used. Every variable must have a datatype that determines the
range and type of values to be stored and size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol. The following
are the rules to specify a variable name...

1. Variable name should not start with digit.


2. Keywords should not be used as variable names.
3. Variable name should not contain any special symbols except underscore(_).
4. Variable name can be of any length but compiler considers only the first 31
characters of the variable name.

17 | P a g e SCS 101 by TIRUS MUYA


Declaration of Variable

Declaration of a variable tells to the compiler to allocate required amount of


memory with specified variable name and allows only specified datatype values into
that memory location. In C programming language, the declaration can be performed
either before the function as global variables or inside any block or function. But it
must be at the begining of block or function.

Declaration Syntax:

datatype variableName;

Example

int number;

The above declaration tells to the compiler that allocate 2 bytes of memory with
the name number and allows only integer values into that memory location.

Constants in C

In C programming language, a constant is similar to the variable but constant holds


only one value during the program execution. That means, once a value is asssigned
to the constant, that value can't be changed during the program execution. Once
the value is assigned to the constant, it is fixed throughout the program. A constant
can be defined as follows...

A constant is a named memory location which holds only one value throughout
the program execution.

In C programmig language, constant can be of any datatype like integer, floating


point, character, string and double etc.,

Integer constants

An integer constant can be a decimal integer or octal integer or hexa decimal


integer. A decimal integer value is specified as direct integer value whereas octal
integer value is prefixed with 'o' and hexa decimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of
integer constant. Unsigned integer constant value is suffixed with 'u' and long integer
constant value is suffixed with 'l' whereas unsigned long integer constant value is
suffixed with 'ul'.

18 | P a g e SCS 101 by TIRUS MUYA


Examples

125 -----> Decimal Integer Constant


O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant

Floating Point constants

A floating point constant must contain both integer and decimal parts. Some times
it may also contain exponent part. When a floating point constant is represented in
exponent form, the value must be suffixed with 'e' or 'E'.

Example

The floating point value 3.14 is represented as 3E-14 in exponent form.

Character Constants

A character constant is a symbol enclosed in single quotation. A character constant


has a maximum length of one character.

Example

'A'
'2'
'+'

In C programming language, there are some predefined character constants called


escape sequences. Every escape sequence has its own special functionality and every
escape sequence is prefixed with '\' symbol. These escape sequences are used in
output function called 'printf()'.

String Constants

A string constant is a collection of characters, digits, special symbols and escape


sequences that are enclosed in double quotations. We define string constant in a
single line as follows

"This is btechsmartclass"We can define string constant using multiple lines as


follows..."This\is\mutclass. We can also define string constant by separating it with
white space as follows. "This" "is" "mutclass"All the above three defines the same
string constant.

In c programming language, constants can be created using two concepts...

1. Using 'const' keyword


2. Using '#define' preprocessor

19 | P a g e SCS 101 by TIRUS MUYA


Using 'const' keyword

We create a constant of any datatype using 'const' keyword. To create a constant,


we prefix the variable declaration with 'const' keyword. The general syntax for
creating constant using 'const' keyword is as follows...

const datatype constantName ;

OR

const datatype constantName = value ;

Example

const int x = 10 ;

Here, 'x' is a integer constant with fixed value 10.

Example Program

#include <stdio.h>
void main(){
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;

The above program gives an error because we are trying to change the constant
variable value (x = 100).

Using '#define' preprocessor

We can also create constants using '#define' preprocessor directive. When we create
constant using this preprocessor directive it must be defined at the beginning of the
program (because all the preprocessor directives must be written before the gloabal
declaration).
We use the following syntax to create constant using '#define' preprocessor
directive...

#define CONSTANTNAME value

20 | P a g e SCS 101 by TIRUS MUYA


Example

#define PI 3.14

Here, PI is a constant with value 3.14

Example Program

#include <stdio.h>
#define PI 3.14
void main(){
int r, area ;

printf("Please enter the radius of circle : ") ;


scanf("%d", &r) ;

area = PI * (r * r) ;

printf("Area of the circle = %d", area) ;


}

Output Functions in C

C programming language provides built-in functions to perform output operation.


The output opearations are used to display data on user screen (output screen) or
printer or any file. C programming language provides the following built-in output
functions...

1. printf()
2. putchar()
3. puts()
4. fprintf()

printf() function

The printf() function is used to print string or data values or combination of string
and data values on the output screen (User screen). The printf() function is built-in
function defined in a header file called "stdio.h". When we want to use printf()
function in our program we need to include the respective header file (stdio.h)
using #include statement. The printf() function has the following syntax...

Syntax:

printf("message to be display!!!");

21 | P a g e SCS 101 by TIRUS MUYA


Example Program

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

printf("Hello! Welcome to btechsmartclass!!!");

}
Output:
Hello! Welcome to btechsmartclass!!!

In the above example program, we used the printf() function to print a string on to
the output screen.

The printf() function is also used to display data values. When we want to display
data values we use format string of the data value to be display.

Syntax:

printf("format string",variableName);

Example Program

#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);

}
Output:
10 5.5

In the above example program, we used the printf() function to print data values of
variables i and x on to the output screen. Here i is a integer variable so we have
used format string %d and x is a float variable so we have used format string %f.

The printf() function can also used to display string along with data values.

Syntax:

printf("String format string",variableName);

22 | P a g e SCS 101 by TIRUS MUYA


Example Program

#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);

}
Output:
Integer value = 10, float value = 5.5

In the above program we are displaying string along with data values.

Every function in C programming language must have a return value. The printf()
function also have integer as return value. The printf() function returns an integer
value equalent to the total number of characters it has printed.

Example Program

#include <stdio.h>
void main(){
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);

}
Output:
btechsmartclass is 15 number of characters.

In the above program, first printf() function printing "btechsmartclass" which is of


15 characters. So it returns integer value 15 to variable "i". The value of "i" is printed
in the second printf() function.

Formatted printf() function

Generally, when we write multiple printf() statements the result is displayed in


single line because the printf() function displays the output in a single line. Consider
the following example program...

#include <stdio.h>
void main(){
printf("Welcome to ");
printf("btechsmartclass ");
printf("the perfect website for learning");

}
Output:

23 | P a g e SCS 101 by TIRUS MUYA


Welcome to btechsmartclass the perfect website for learning

In the above program, there are 3 printf() statements written in different lines but
the output is displayed in single line only.

To display the output in different lines or as we wish, we use some special characters
called escape sequences. Escape sequences are special characters with special
functionality used in printf() function to format the output according to the user
requirment. In C programming language, we have the following escape sequences...

Escape sequence Meaning


\n New line
\t Horizontal Tab
\v Vertical Tab
\a Beep sound
\b Backspace
\\ Backward slash
\? Question mark
\' Single quotation mark
\" Double quotation mark

Consider the following example program...

#include <stdio.h>
void main(){
printf("Welcome to\n");
printf("btechsmartclass\n");
printf("the perfect website for learning");

}
Output:
Welcome to btechsmartclass the perfect website for learning

putchar() function

The putchar() function is used to display single character on the output screen. The
putchar() functions prints the character which is passed as parameter to it and
returns the same character as return value. This function is used to print only single
charater. To print multiple characters we need to write multiple times or use a
looping statement. Consiider the following example program...

#include <stdio.h>
void main(){
char ch = 'A';
putchar(ch);

24 | P a g e SCS 101 by TIRUS MUYA


Output:
A

puts() function

The puts() function is used to display string on the output screen. The puts()
functions prints a string or sequence of characters till the newline. Consiider the
following example program...

#include <stdio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
puts(name);
}
Output:
Enter your favourite website: www.mut.ac.ke
www.btechsmartclass.com

fprintf() function

The fprintf() function is used with the concept of files. The fprintf() function is used
to print a line into the file. When you want to use fprintf() function the file must be
opened in writting mode.

Input Functions in C

C programming language provides built-in functions to perform input operations. The


input opearations are used to read user values (input) from keyboard. C programming
language provides the following built-in input functions...

1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()

scanf() function

The scanf() function is used to read multiple data values of different data types from
the keyboard. The scanf() function is built-in function defined in a header file called
"stdio.h". When we want to use scanf() function in our program, we need to include
the respective header file (stdio.h) using #include statement. The scanf() function
has the following syntax...

25 | P a g e SCS 101 by TIRUS MUYA


Syntax:

scanf("format strings",&variableNames);

Example Program

#include <stdio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);

}
Output:

Enter any integer value: 55


You have entered 55 number

In the above example program, we used the scanf() function to read an integer value
from the keyboard and store it into variable 'i'.

The scanf function also used to read multiple data values of different or same data
types. Consider the following example program...

#include <stdio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value :
");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);

}
Output:

Enter one integer followed by one float value : 20 30.5


integer = 20, float = 30.5

In the above example program, we used the scanf() function to read one integer
value and one float value from the keyboard. Here 'i' is an integer variable so we
have used format string %d, and 'x' is a float variable so we have used format string
%f.

The scanf() function returns an integer value equal to the total number of input
values read using scanf function.

26 | P a g e SCS 101 by TIRUS MUYA


Example Program

#include <stdio.h>
void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);

}
Output:

Enter two integers and one float : 10 20 55.5


Total inputs read : 3

getchar() function

The getchar() function is used to read a character from the keyboard and return it
to the program. This function is used to read only single character. To read multiple
characters we need to write multiple times or use a looping statement. Consider the
following example program...

#include <stdio.h>
void main(){
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c",ch);

}
Output:

Enter any character : A


You have entered : A

getch() function

The getch() function is similar to getchar function. The getch() function is used to
read a character from the keyboard and return it to the program. This function is
used to read only single character. To read multiple characters we need to write
multiple times or use a looping statement. Consider the following example
program...

#include <stdio.h>
void main(){
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);

27 | P a g e SCS 101 by TIRUS MUYA


}
Output:

Enter any character :


You have entered : A

gets() function

The gets() function is used to read a line of string and stores it into character array.
The gets() function reads a line of string or sequence of characters till a newline
symbol enters. Consider the following example program...

#include <stdio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}
Output:

Enter your favourite website: www.btechsmartclass.com


www.btechsmartclass.com

fscanf() function

The fscanf() function is used with the concept of files. The fscanf() function is used
to read data values from a file. When you want to use fscanf() function the file must
be opened in reading mode.

Operators in C

An operator is a symbol used to perform mathematical and logical operations in a


program. That means an operator is a special symbol that tells to the compiler to
perform mathematical or logical operations. C programming language supports rich
set of operators that are classified as follows...

1. Arithematic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

28 | P a g e SCS 101 by TIRUS MUYA


Arithematic Operators (+, -, *, /, %)

The arithematic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo. The following table provides information about arithematic
operators...

Operator Meaning Example


+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 5 * 10 = 50
/ Division 10 / 5 = 2
% Remaider of Division 5%2=1

⇒ The addition operator can be used with numerical data types and character data
type. When it is used with numerical values, it performs mathematical addition and
when it is used with character data type values, it performs concatination
(appending).

⇒ The remainder of division operator is used with integer data type only.

Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That
means, the relational operators are used to check the relationship between two
values. Every relational operator has two results TRUE or FALSE. In simple words,
the relational operators are used to define conditions in a program. The following
table provides information about relational operators...

Operator Meaning Example


Returns TRUE if first value is smaller than second value 10 < 5 is
<
otherwise returns FALSE FALSE
Returns TRUE if first value is larger than second value 10 > 5 is
>
otherwise returns FALSE TRUE
Returns TRUE if first value is smaller than or equal to 10 <= 5 is
<=
second value otherwise returns FALSE FALSE
Returns TRUE if first value is larger than or equal to 10 >= 5 is
>=
second value otherwise returns FALSE TRUE
Returns TRUE if both values are equal otherwise returns 10 == 5 is
==
FALSE FALSE

29 | P a g e SCS 101 by TIRUS MUYA


Returns TRUE if both values are not equal otherwise 10 != 5 is
!=
returns FALSE TRUE

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions
into one condition. The following table provides information about logical
operators...

Operator Meaning Example


Logical AND - Returns TRUE if all conditions are 10 < 5 && 12 > 10
&&
TRUE otherwise returns FALSE is FALSE
Logical OR - Returns FALSE if all conditions are 10 < 5 || 12 > 10 is
||
FALSE otherwise returns TRUE TRUE
Logical NOT - Returns TRUE if condition is !(10 < 5 && 12 >
!
FLASE and returns FALSE if it is TRUE 10) is TRUE

⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions
is FALSE then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions
is TRUE then complete condition becomes TRUE.

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called as unary operators because, both
needs only one operand. The increment operators adds one to the existing value of
the operand and the decrement operator subtracts one from the existing value of
the operand. The following table provides information about increment and
decrement operators...

Operator Meaning Example


int a = 5;
++ Increment - Adds one to existing value
a++; ⇒ a = 6
int a = 5;
-- Decrement - Subtracts one from existing value
a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or
after the operand (a++). If it is used infront of the operand, we call it as pre-
increment or pre-decrement and if it is used after the operand, we call it as post-
increment or post-decrement.

30 | P a g e SCS 101 by TIRUS MUYA


Pre-Increment or Pre-Decrement

In case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In case of pre-decrement, the value of the variable is
decreased by one before the expression evaluation. That means, when we use pre
increment or pre decrement, first the value of the variable is incremented or
decremented by one, then modified value is used in the expression evaluation.

#include <stdio.h>
void main(){
int i = 5,j;

j = ++i; // Pre-Increment

printf("i = %d, j = %d",i,j);

}
Output:

i = 6, j = 6

Post-Increment or Post-Decrement

In case of post-increment, the value of the variable is increased by one after the
expression evaluation. In case of post-decrement, the value of the variable is
decreased by one after the expression evaluation. That means, when we use post-
increment or post-decrement, first the expression is evaluated with existing value,
then the value of the variable is incremented or decremented by one.

Example

#include <stdio.h>
void main(){
int i = 5,j;

j = i++; // Post-Increment

printf("i = %d, j = %d",i,j);

}
Output:

i = 6, j = 5

Assignment Operators (=, +=, -=, *=, /=, %=)

The assignment operators are used to assign right hand side value (Rvalue) to the
left hand side variable (Lvalue). The assignment operator is used in different variants
along with arithematic operators. The following table describes all the assignment
operators in C programming language.

31 | P a g e SCS 101 by TIRUS MUYA


Operator Meaning Example
= Assign the right hand side value to left hand side variable A = 15
A += 10
Add both left and right hand side values and store the result
+= ⇒
into left hand side variable
A=A+10
Subtract right hand side value from left hand side variable A -= B
-=
value and store the result into left hand side variable ⇒ A=A-B
A *= B
Multiply right hand side value with left hand side variable
*= ⇒
value and store the result into left hand side variable
A=A*B
Divide left hand side variable value with right hand side A /= B
/=
variable value and store the result into left hand side variable ⇒ A=A/B
Divide left hand side variable value with right hand side A %= B
%= variable value and store the remainder into left hand side ⇒
variable A=A%B

Bitwise Operators (&, |, ^, ~, >>, <<)

The bitwise operators are used to perform bit level operations in c programming
language. When we use the bitwise operators, the operations are performed based
on the binary values. The following table describes all the bitwise operators in C
programming language.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100)

Operator Meaning Example


the result of Bitwise AND is 1 if all the bits are 1 A&B
&
otherwise it is 0 ⇒ 16 (10000)
the result of Bitwise OR is 0 if all the bits are 0 otherwise A|B
|
it is 1 ⇒ 29 (11101)
the result of Bitwise XOR is 0 if all the bits are same A^B
^
otherwise it is 1 ⇒ 13 (01101)
the result of Bitwise once complement is nagation of the ~A
~
bit (Flipping) ⇒ 6 (00110)
A<<2
the Bitwise left shift operator shifts all the bits to the left
<< ⇒ 100
by specified number of positions
(1100100)
the Bitwise right shift operator shifts all the bits to the A>>2
>>
right by specified number of positions ⇒ 6 (00110)

32 | P a g e SCS 101 by TIRUS MUYA


Conditional Operator (?:)

The conditional operator is also called as ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first we verify
a condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the
condition is FALSE the second option is performed. The conditional operator is used
with the following syntax...

Condition ? TRUE Part : FALSE Part ;

Example

A = (10<15) ? 100 : 200 ; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot etc.)

The following are the special operators in c programming language...

sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a
variable. This operator is used with the following syntax...

sizeof(variableName);

Example

sizeof(A); ⇒ result is 2 if A is an integer

Pointer operator (*)

This operator is used to define pointer variables in c programming language.

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the
expresions in function calls etc..

Dot operator (.)

This operator is used to access members of sructure or union.

33 | P a g e SCS 101 by TIRUS MUYA


Expressions in C

What is an expression?

In any programming language, if we want to perform any calculation or to frame any


condition etc., we use a set of symbols to perform the task. These set of symbols
makes an expression.
In C programming language, an expression is defined as follows...

An expression is a collection of operators and operands that represents a


specific value.

In the above definition, operator is a symbol which performs tasks like arithmetic
operations, logical operations and conditional operations etc.,
Operands are the values on which the operators perform the task. Here operand can
be a direct value or variable or address of memory location.

Expression Types in C

In C programming language, expressions are divided into THREE types. They are as
follows...

a) Infix Expression
b) Postfix Expression
c) Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression

The expression in which operator is used between operands is called as infix


expression.
The infix expression has the following general structure...

Operand1 Operator Operand2

Example

34 | P a g e SCS 101 by TIRUS MUYA


Postfix Expression

The expression in which operator is used after operands is called as postfix


expression.
The postfix expression has the following general structure...

Operand1 Operand2 Operator

Example

Prefix Expression

The expression in which operator is used before operands is called as prefix


expression.
The prefix expression has the following general structure...

Operator Operand1 Operand2

Example

Operator Precedence and Associativity in C

What is Operator Precedence?

Operator precedence is used to determine the order of operators evaluated in an


expression. In c programming language every operator has precedence (priority).
When there is more than one operator in an expression the operator with higher
precedence is evaluated first and the operator with least precedence is evaluated
last.

35 | P a g e SCS 101 by TIRUS MUYA


What is Operator Associativity?

Operator associativity is used to determine the order of operators with equal


precedence evaluated in an expression. In c programming language, when an
expression contains multiple operators with equal precedence, we use associativity
to determine the order of evaluation of those operators.

In c programming language the operator precedence and associativity is as shown in


the following table...

Precedence Operator Operator Meaning Associativity

() function call
[] array reference
1 Left to Right
-> structure member access
. structure member access

! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion

* multiplication
3 / division Left to Right
% remainder

+ addition
4 Left to Right
- subtraction

<< left shift


5 Left to Right
>> right shift

< less than


<= less than or equal to
6 Left to Right
> greater than
>= greater than or equal to

36 | P a g e SCS 101 by TIRUS MUYA


== equal to
7 Left to Right
!= not equal to

8 & bitwise AND Left to Right

9 ^ bitwise EXCLUSIVE OR Left to Right

10 | bitwise OR Left to Right

11 && logical AND Left to Right

12 || logical OR Left to Right

13 ?: conditional operator Left to Right

= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign additon
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

15 , separator Left to Right

In the above table, the operator precedence decrese from top to bottom and
increase from bottom to top.

Expression Evaluation in C

In C programming language, expression is evaluated based on the operator


precedence and associativity. When there are multiple operators in an expression,
they are evaluated according to their precedence and associativity. The operator
with higher precedence is evaluated first and the operator with least precedence is
evaluated last.

An expression is evaluated based on the precedence and associativity of the


operators in that expression.

37 | P a g e SCS 101 by TIRUS MUYA


To understand expression evaluation in c, let us consider the following simple
example expression...

10 + 4 * 3 / 2

In the above expression there are three operators +, * and /. Among these three
operators, both multiplication and division have same higher precedence and
addition has lower precedence. So, according to the operator precedence both
multiplication and division are evaluated first and then addition is evaluated. As
multiplication and division have same precedence they are evaluated based on the
associativity. Here, the associativity of multiplication and division is left to right.
So, multiplication is performed first, then division and finally addition. So, the above
expression is evaluated in the order of * / and +. It is evaluated as follows...

4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

Type Casting and Conversion in C

In a programming language, the expression contains data values of same datatype


or different datatypes. When the expression contains similar datatype values then
it is evaluated without any problem. But if the expression contains two or more
different datatype values then they must be converted to single datatype of
destination datatype. Here, destination is the location where the final result of that
expression is stored. For example,the multiplication of an integer data value with
float data value and storing the result into a float variable. In this case, the integer
value must be converted to float value so that the final result is a float datatype
value.
In c programming language, the data conversion is performed in two different
methods as follows...

1. Type Conversion
2. Type Casting

Type Conversion

The type conversion is the process of converting a data value from one datatype to
another datatype automatically by the compiler. Sometimes type conversion is also
called as implicit type conversion. The implicit type conversion is automatically
performed by the compiler.

For example, in c programming language, when we assign an integer value to a float


variable the integer value automically gets converted to float value by adding
decimal value 0. And when a float value is assigned to an integer variable the float

38 | P a g e SCS 101 by TIRUS MUYA


value automatically gets converted to integer value by removing the decimal value.
To understand more about type conversion observe the following...

int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable


x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

Example Program

#include <stdio.h>
void main(){
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;

i = x ;
printf("i value is %d\n",i);
x = i ;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);

}
Output:

i value is 90
x value is 90.000000
i value is 65

In the above program, we assign i = x, i.e., float variable value is assigned to integer
variable. Here, the compiler automatically converts the float value (90.99) into
integer value (90) by removing the decimal part of the float value (90.99) and then
it is assigned to variable i. Similarly when we assign x = i, the integer value (90) gets
converted to float value (90.000000) by adding zero as decimal part.

Type Casting

Type casting is also called as explicit type conversion. Compiler converts data from
one datatype to another datatype implicitly. When compiler converts implicitly,
there may be a data loss.In such case, we convert the data from one datatype to
another datatype using explicit type conversion. To perform this we use the unary
cast operator. To convert data from one type to another type we specify the target

39 | P a g e SCS 101 by TIRUS MUYA


datatype in paranthesis as a prefix to the data value that has to be converted. The
general syntax of type casting is as follows...

(TargetDatatype) DataValue

Example

int totalMarks = 450, maxMarks = 600 ;


float average ;

average = (float) totalMarks / maxMarks * 100 ;

In the above example code, both totalMarks and maxMarks are integer data values.
When we perform totalMarks / maxMarks the result is a float value, but the
destination (average) datatype is float. So we use type casting to convert totalMarks
and maxMarks into float datatype.

Example Program

#include <stdio.h>
void main(){
int a, b, c ;
float avg ;
printf("Enter any three integer values : ") ;
scanf("%d%d%d", &a, &b, &c) ;

avg = (a + b + c) / 3 ;
printf("avg before casting = %f\n",avg);

avg = (float)(a + b + c) / 3 ;
printf("avg after casting = %f\n",avg);
}
Output:

Enter any three integer values : 5 3 2


avg before casting = 3
avg after casting = 3.333333

if statement in C

What is Decision Making Statement?

In c programming language, the program execution flow is, line by line from top to
bottom. That means the c program is executed line by line from the main method.
But this type of execution flow may not be suitable for all the program solutions.
Sometimes, we make some decisions or we may skip the execution of one or more
lines of code. Consider a situation, where we write a program to check whether a
student has passed or failed in a particular subject. Here, we need to check whether

40 | P a g e SCS 101 by TIRUS MUYA


the marks are greater than the pass marks or not. If marks are greater, then we take
the decision that the student has passed otherwise failed. To solve such kind of
problems in c we use the statements called decision making statements.

Decision making statements are the statements that are used to verify a given
condition and decides whether a block of statements gets executed or not based
on the condition result.

In c programming language, there are two decision making statements they are as
follows...

1. if statement
2. switch statement

if statement in c

In c, if statement is used to make decisions based on a condition. The if statement


verifies the given condition and decides whether a block of statements are executed
or not based on the condition result. In c, if statement is classified into four types
as follows...

1. Simple if statement
2. if - else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)

Simple if statement

Simple if statement is used to verify the given condition and executes the block of
statements based on the condition result. The simple if statement evaluates
specified condition. If it is TRUE, it executes the next statement or block of
statements. If the condition is FALSE, it skips the execution of the next statement
or block of statements. The general syntax and execution flow of the simple if
statement is as follows...

41 | P a g e SCS 101 by TIRUS MUYA


Simple if statement is used when we have only one option that is executed or skipped
based on a condition.

Example Program | Test whether given number is divisible by 5.

#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:

Enter any integer number: 100


Given number is divisible by 5
statement does not belong to if!!!

Output 2:

Enter any integer number: 99


statement does not belong to if!!!

if - else statement

The if - else statement is used to verify the given condition and executes only one
out of the two blocks of statements based on the condition result. The if-else
statement evaluates the specified condition. If it is TRUE, it executes a block of
statements (True block). If the condition is FALSE, it executes another block of
statements (False block). The general syntax and execution flow of the if-else
statement is as follows...

42 | P a g e SCS 101 by TIRUS MUYA


The if-else statement is used when we have two options and only one option has to
be executed based on a condition result (TRUE or FALSE).

Example Program | Test whether given number is even or odd.

#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:

Enter any integer number: 100


Given number is EVEN

Output 2:

Enter any integer number: 99


Given number is ODD

Nested if statement

Writing a if statement inside another if statement is called nested if statement. The


general syntax of the nested if statement is as follows...

43 | P a g e SCS 101 by TIRUS MUYA


The nested if statement can be defined using any combination of simple if & if-else
statements.

Example Program | Test whether given number is even or odd if it is below


100.

#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:

Enter any integer number: 55


Given number is below 100
And it is ODD

Output 2:

Enter any integer number: 999


Given number is not below 100

if - else - if statement (if-else ladder)

Writing a if statement inside else of a if statement is called if - else - if statement.


The general syntax of the if-else-if statement is as follows...

44 | P a g e SCS 101 by TIRUS MUYA


The if-else-if statement can be defined using any combination of simple if & if-else
statements.

Example Program | Find the largest of three numbers.

#include <stdio.h>
#include<conio.h>
void main(){
int a, b, c ;
clrscr() ;

printf("Enter any three integer numbers: ") ;


scanf("%d%d%d", &a, &b, &c) ;

if( a>=b && a>=c)


printf("%d is the largest number", a) ;

else if (b>=a && b>=c)


printf("%d is the largest number", b) ;

else
printf("%d is the largest number", c) ;
}
Output 1:

Enter any three integer numbers: 55 60 20


60 is the largest number

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use conditional control statement like if statement, condition might be an


expression evaluated to a numerical value, a variable or a direct numerical value. If
the expression value or direct value is zero the conditon becomes FALSE
otherwise becomes TRUE

To understand more consider the following statements...

• if(10) - is TRUE
• if(x) - is FALSE if x value is zero otherwise TRUE
• if(a+b) - is FALSE if a+b value is zero otherwise TRUE
• if(a = 99) - is TRUE because a value is non-zero
• if(10, 5, 0) - is FALSE because it considers last value
• if(0) - is FALSE
• if(a=10, b=15, c=0) - is FALSE because last value is zero

Switch statement in C

45 | P a g e SCS 101 by TIRUS MUYA


Consider a situation in which we have more number of options out of which we need
to select only one option that is to be executed. Such kind of problems can be solved
using nested if statement. But as the number of options increases, the complexity
of the program also gets increased. This type of problems can be solved very easily
using switch statement. Using switch statement, one can select only one option
from more number of options very easily. In switch statement, we provide a value
that is to be compared with a value associated with each option. Whenever the given
value matches with the value associated with an option, the execution starts from
that option. In switch statement every option is defined as a case.

The switch statement has the following syntax and execution flow diagram...

The switch statement contains one or more number of cases and each case has a
value associated with it. At first switch statement compares the first case value with
the switchValue, if it gets matched the execution starts from the first case. If it
doesn't match the switch statement compares the second case value with the
switchValue and if it is matched the execution starts from the second case. This
process continues until it finds a match. If no case value matches with the
switchValue specified in the switch statement, then a special case called default is
executed.

When a case value matches with the switchValue, the execution starts from that
particular case. This execution flow continues with next case statements also. To
avoid this, we use "break" statement at the end of each case. That means
the break statement is used to terminate the switch statement. However it is
optional.

46 | P a g e SCS 101 by TIRUS MUYA


Example Program | Display pressed digit in words.

#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;

printf("Enter any digit: ") ;


scanf("%d", &n) ;

switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
Output 1:

Enter any digit: 5


FIVE

Output 2:

Enter any digit: 15


Not a Digit

47 | P a g e SCS 101 by TIRUS MUYA


MOST IMPORTANT POINTS TO BE REMEMBERED

When we use switch statement, we must follow the following...

• Both switch and case are keywords so they must be used only in lower case
letters.
• The data type of case value and the value specified in switch statement
must be same.
• switch and case values must be either integer or character but not float or
string.
• A switch statement can contain any number of cases.
• The keyword case and its value must be superated with a white space.
• The case values need not be defined in sequence, they can be in any order.
• The default case is optional and it can be defined anywhere inside the
switch statement.
• The switch value might be a direct value, a variable or an expression.

while Statement in C

Consider a situation in which we execute a single statement or block of statements


repeatedly for required number of times. Such kind of problems can be solved
using looping statements in C. For example, assume a situation where we print a
message for 100 times. If we want to perform that task without using looping
statements, we have to either write 100 printf statements or we have to write the
same message for 100 times in a single printf statement. Both are complex methods.
The same task can be performed very easily using looping statements.

The looping statements are used to execute a single statement or block of


statements repeatedly until the given condition is FALSE.

C language provides three looping statements...

• while statement
• do-while statement
• for statement

48 | P a g e SCS 101 by TIRUS MUYA


while Statement

The while statement is used to execute a single statement or block of statements


repeatedly as long as the given condition is TRUE. The while statement is also known
as Entry control looping statement. The while statement has the following syntax...

The while statement has the following execution flow diagram...

At first, the given condition is evaluated. If the condition is TRUE, the single
statement or block of statements gets executed. Once the execution gets completed
the condition is evaluated again. If it is TRUE, again the same statements gets
executed. The same process is repeated until the condition is evaluated to FALSE.
Whenever the condition is evaluated to FALSE, the execution control moves out of
the while block.

49 | P a g e SCS 101 by TIRUS MUYA


Example Program | Program to display even numbers upto 10.

#include <stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");

while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}

getch() ;
}
Output 1:

Even numbers upto 10


0 2 4 6 8 10

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use while statement, we must follow the following...

• while is a keyword so it must be used only in lower case letters.


• If the condition contains variable, it must be assigned a value before it is
used.
• The value of the variable used in condition must be modified according to
the requirement inside the while block.
• In while statement, the condition may be a direct integer value, a variable
or a condition.
• A while statement can be an empty statement.

50 | P a g e SCS 101 by TIRUS MUYA


do-while Statement in C

The do-while statement is used to execute a single statement or block of statements


repeatedly as long as given the condition is TRUE. The do-while statement is also
known as Exit control looping statement. The do-while statement has the following
syntax...

The do-while statement has the following execution flow diagram...

At first, the single statement or block of statements which are defined in do block
are executed. After execution of do block, the given condition gets evaluated. If the
condition is evaluated to TRUE, the single statement or block of statements of do
block are executed again. Once the execution gets completed again the condition is
evaluated. If it is TRUE, again the same statements are executed. The same process
is repeated until the condition is evaluated to FALSE. Whenever the condition is
evaluated to FALSE, the execution control moves out of the while block.

51 | P a g e SCS 101 by TIRUS MUYA


Example Program | Program to display even numbers upto 10.

#include <stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");

do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;

getch() ;
}
Output 1:

Even numbers upto 10


0 2 4 6 8 10

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use do-while statement, we must follow the following...

• Both do and while are keywords so they must be used only in lower case
letters.
• If the condition contains variable, it must be assigned a value before it is
used.
• The value of the variable used in condition must be modified according to
the requirement inside the do block.
• In do-while statement the condition may be, a direct integer value, a
variable or a condition.
• A do-while statement can be an empty statement.
• In do-while, the block of statements are executed atleast once.

52 | P a g e SCS 101 by TIRUS MUYA


for Statement in C

The for statement is used to execute a single statement or a block of statements


repeatedly as long as the given condition is TRUE. The for statement has the
following syntax and execution flow diagram...

At first, the for statement executes initialization followed by condition evaluation.


If the condition is evaluated to TRUE, the single statement or block of statements
of for statement are executed. Once the execution gets completed,
the modification statement is executed and again the condition is evaluated. If it is
TRUE, again the same statements are executed. The same process is repeated until
the condition is evaluated to FALSE. Whenever the condition is evaluated to FALSE,
the execution control moves out of the for block.

53 | P a g e SCS 101 by TIRUS MUYA


Example Program | Program to display even numbers upto 10.

#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");

for( n = 0 ; n <= 10 ; n++ )


{
if( n%2 == 0)
printf("%d\t", n) ;
}

getch() ;
}
Output 1:
Even numbers upto 10
0 2 4 6 8 10

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use for statement, we must follow the following...

• for is a keyword so it must be used only in lower case letters.


• Every for statement must be provided with initialization, condition and
modification (They can be empty but must be separated with ";")
Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; )
• In for statement, the condition may be a direct integer value, a variable or
a condition.
• The for statement can be an empty statement.

break, continue and goto in C

In c, there are control statements which does not need any condition to control the
program execution flow. These control statements are called as unconditional
control statements. C programming language provides the following unconditional
control statements...

• break
• continue
• goto

54 | P a g e SCS 101 by TIRUS MUYA


The above three statements does not need any condition to control the program
execution flow.

break statement
In C, the break statement is used to perform the following two things...

1. break statement is used to terminate switch case statement

2. break statement is also used to terminate looping statements like while,

do-while and for.

When a break statement is encountered inside the switch case statement, the
execution control moves out of the switch statement directly. For example consider
the following program...

Example Program | Program to perform all arithmetic operations using switch


statement.

#include <stdio.h>
#include<conio.h>
void main(){
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}

55 | P a g e SCS 101 by TIRUS MUYA


Output

Enter any two integer numbers: 50 30


Please enter any arithmetic operator: *
Multiplication = 1500

When the break statement is encountered inside the looping statement, the
execution control moves out of the looping statements. The break statement
execution is as shown in the following figure.

For example, consider the following example program...

Example Program for break statement.

#include <stdio.h>
#include<conio.h>
void main(){
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
Output

56 | P a g e SCS 101 by TIRUS MUYA


Enter Y / N : Y
Okay!!! Repeat again !!!
Enter Y / N : Y
Okay!!! Repeat again !!!
Enter Y / N : N
Okay !!! Breaking the loop !!!

continue statement

The continue statement is used to move the program execution control to the
beginning of looping statement. When continue statement is encountered in a
looping statement, the execution control skips the rest of the statements in the
looping block and directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while, do-while
and for.

When we use continue statement with while and do-while statements the
execution control directly jumps to the condition. When we use continue statement
with for statement the execution control directly jumps to the modification portion
(increment / decrement / any modification) of the for loop.
The continue statement execution is as shown in the following figure...

Example Program | Program to illustrate continue statement.

#include <stdio.h>
#include<conio.h>
void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{

57 | P a g e SCS 101 by TIRUS MUYA


printf("Entered number is EVEN!!! Try another
number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}

Output

Enter any integer numbers: 50


Entered number is EVEN!!! Try another number!!!
Enter any integer numbers: 100
Entered number is EVEN!!! Try another number!!!
Enter any integer numbers: 10
Entered number is EVEN!!! Try another number!!!
Enter any integer number: 15
You have entered ODD number!!! Bye!!!

goto statement

The goto statement is used to jump from one line to another line in the program.
Using goto statement we can jump from top to bottom or bottom to top. To jump
from one line to another line, the goto statement requires a lable. Lable is a name
given to the instruction or line in the program. When we use goto statement in the
program, the execution control directly jumps to the line with specified lable.

Example Program for goto statement.

#include <stdio.h>
#include<conio.h>
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}
Output

We are at first printf statement!!!


We are at last printf statement!!!

58 | P a g e SCS 101 by TIRUS MUYA


MOST IMPORTANT POINTS TO BE REMEMBERED

When we use break, continue and goto statements, we must follow the following...

• The break is a keyword so it must be used only in lower case letters.


• The break statement can not be used with if statement.
• The break statement can be used only in switch case and looping
statements.
• The break statement can be used with if statement, only if that if
statement is written inside the switch case or looping statements.
• The continue is a keyword so it must be used only in lower case letters.
• The continue statement is used only within looping statements.
• The continue statement can be used with if statement, only if that if
statement is written inside the looping statements.
• The goto is a keyword so it must be used only in lower case letters.
• The goto statement must requires a lable.
• The goto statement can be used with any statement like if, switch, while,
do-while and for etc,.

Designing Structured Programs in C

Structured programming is a programming technique in which a larger program is


divided into smaller subprograms to make it easy to understand, easy to implement
and makes the code reusable etc,. The structured programming enables code
reusability. Code reusability is a method of writing code once and using it many
times. Using structured programming technique, we write the code once and use it
many times. Structured programming also makes the program easy to understand,
improves the quality of the program, easy to implement and reduces time.

In C, the structured programming can be designed using functions concept. Using


functions concept, we can divide larger program into smaller subprograms and these
subprograms are implemented individually. Every subprogram or function in C is
executed individually.

59 | P a g e SCS 101 by TIRUS MUYA


Introduction to Functions in C

When we write a program to solve a larger problem, we divide that larger problem
into smaller sub problems and are solved individually to make the program easier.
In C, this concept is implemented using functions. Functions are used to divide a
larger program into smaller subprograms such that program becomes easy to
understand and easy to implement. A function is defined as follows...

Function is a subpart of program used to perform specific task and is executed


individually.

Every C program must contain atleast one function called main(). However a program
may also contain other functions. Every function in C has the following...

• Function Declaration (Function Prototype)


• Function Definition
• Function Call

Function Declaration

The function declaration tells the compiler about function name, datatype of the
return value and parameters. The function declaration is also called as function
prototype. The function declaration is performed before main function or inside
main function or inside any other function.

Function declaration syntax -

returnType functionName(parametersList);

In the above syntax, returnType specifies the datatype of the value which is sent as
a return value from the function definiton. The functionName is a user defined
name used to identify the function uniquely in the program. The parametersList is
the data values that are sent to the function definition.

Function Definition

The function definition provides the actual code of that function. The function
definition is also known as body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be
performed by a function are written in function definition. The actual instructions
of a function are written inside the braces "{ }". The function definition is performed
before main function or after main function.

Function definition syntax -

60 | P a g e SCS 101 by TIRUS MUYA


returnType functionName(parametersList)
{

Actual code...

Function Call

The function call tells the compiler when to execute the function definition. When
a function call is executed, the execution control jumps to the function definition
where the actual code gets executed and returns to the same functions call once
the execution completes. The function call is performed inside main function or
inside any other function or inside the function itself.

Function call syntax -

functionName(parameters);

Advantages of Functions

• Using funcions we can implement modular programming.


• Functions makes the program more readable and understandable.
• Using functions the program implementation becomes easy.
• Once a function is created it can be used many times (code re-usability).
• Using functions larger program can be divided into smaller modules.

Types of Functions in C

In C Programming Language, based on providing the function definition, functions


are divided into two types. Those are as follows...

• System Defined Functions


• User Defined Functions

System Defined Functions

The C Programming Language provides pre-defined functions to make programming


easy. These pre-defined functions are known as syatem defined functions. The
system defined function is defined as follows...

61 | P a g e SCS 101 by TIRUS MUYA


The function whose definition is defined by the system is called as system
defined function.

The system defined functions are also called as Library Functions or Standard
Functions or Pre-Defined Functions. The implementation of system defined
functions is already defined by the system.

In C, all the system defined functions are defined inside the header
files like stdio.h, conio.h, math.h, string.h etc., For example, the
funtions printf() and scanf() are defined in the header file called stdio.h.

Whenever we use system defined functions in the program, we must include the
respective header file using #include statement. For example, if we use a system
defined function sqrt() in the program, we must include the header file
called math.h because the function sqrt() is defined in math.h.

Points to be Remembered

• System defined functions are declared in header files


• System defined functions are implemented in .dll files. (DLL stands
for Dynamic Link Library).
• To use system defined functions the respective header file must be
included.

User Defined Functions

In C programming language, users can also create their own functions. The functions
that are created by users are called as user defined functions. The user defined
function is defined as follows...

The function whose definition is defined by the user is called as user defined
function.

That means the function that is implemented by user is called as user defined
function. For example, the function main is implemented by user so it is called as
user defined function.

In C every user defined function must be declared and implemented. Whenever we


make function call the function definition gets executed. For example, consider the
following program in which we create a fucntion called addition with two
paramenters and a return value.

62 | P a g e SCS 101 by TIRUS MUYA


#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int,int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

result = addition(num1, num2) ; // function call

printf("SUM = %d", result);


getch() ;
}
int addition(int a, int b) // function definition
{
return a+b ;
}

In the above example program, the function declaration statement "int


addition(int,int)" tells the compiler that there is a function with
name addition which takes two integer values as parameters and returns an integer
value. The function call statement takes the execution control to
the additon() definition along with values of num1 and num2. Then function
definition executes the code written inside it and comes back to the function
call along with return value.

In the concept of functions, the function call is known as "Calling Function" and the
function definition is known as "Called Function".

When we make a function call, the execution control jumps from calling function to
called function. After executing the called function, the execution control comes
back to calling function from called function. When the control jumps from calling
function to called function it may carry one or more data values called
"Paramenters" and while coming back it may carry a single value called "return
value". That means the data values transferred from calling function to called
function are called as Parameters and the data value transferred from called
funcion to calling function is called Return value.

Based on the data flow between the calling function and called function, the
functions are classified as follows...

a) Function without Parameters and without Return value

b) Function with Parameters and without Return value

c) Function without Parameters and with Return value

d) Function with Parameters and with Return value

63 | P a g e SCS 101 by TIRUS MUYA


Function without Parameters and without Return value

In this type of functions there is no data transfer between calling function and called
function. Simply the execution control jumps from calling function to called function
and executes called function, and finally comes back to the calling function. For
example, consider the following program...

#include <stdio.h>
#include<conio.h>
void main()
{
void addition() ; // function declaration
clrscr() ;

addition() ; // function call

getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}

Function with Parameters and without Return value

In this type of functions there is data transfer from calling function to called function
(parameters) but there is no data transfer from called function to calling function
(return value). The execution control jumps from calling function to called function
along with the parameters and executes called function, and finally comes back to
the calling function. For example, consider the following program...

#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}

64 | P a g e SCS 101 by TIRUS MUYA


Function without Parameters and with Return value

In this type of functions there is no data transfer from calling function to called
function (parameters) but there is data transfer from called function to calling
function (return value). The execution control jumps from calling function to called
function and executes called function, and finally comes back to the calling function
along with a return value. For example, consider the following program...

#include <stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;}

Function with Parameters and with Return value

In this type of functions there is data transfer from calling function to called function
(parameters) and also from called function to calling function (return value). The
execution control jumps from calling function to called function along with
parameters and executes called function, and finally comes back to the calling
function along with a return value. For example, consider the following program...

#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}

65 | P a g e SCS 101 by TIRUS MUYA


Points to be Remembered

• The parameters specified in calling function are said to be Actual


Parameters.
• The parameters declared in called function are said to be Formal
Parameters.
• The value of actual parameters is always copied into formal parameters.

Parameter Passing in C

When a function gets executed in the program, the execution control is transferred
from calling function to called function and executes function definition, and finally
comes back to the calling function. When the execution control is transferred from
calling function to called function it may carry one or more number of data values.
These data values are called as parameters.

Parameters are the data values that are passed from calling function to called
function.

In C, there are two types of parameters and they are as follows...

a) Actual Parameters
b) Formal Parameters

The actual parameters are the parameters that are speficified in calling function.
The formal parameters are the parameters that are declared at called function.
When a function gets executed, the copy of actual parameter values are copied into
formal parameters.

In C Programming Language, there are two methods to pass parameters from calling
function to called function and they are as follows...

a) Call by Value
b) Call by Reference

Call by Value

In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters and these formal parameters are used in called
function. The changes made on the formal parameters does not effect the values
of actual parameters. That means, after the execution control comes back to the

66 | P a g e SCS 101 by TIRUS MUYA


calling function, the actual parameter values remains same. For example consider
the following program...

#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(num1, num2) ; // calling function

printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);


getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}
Output:

Before swap: num1 = 10, num2 = 20


After swap: num1 = 10, num2 = 20

In the above example program, the variables num1 and num2 are called actual
parameters and the variables a and b are called formal parameters. The value
of num1 is copied into a and the value of num2 is copied into b. The changes made
on variables a and b does not effect the values of num1 and num2.

Call by Reference

In Call by Reference parameter passing method, the memory location address of


the actual parameters is copied to formal parameters. This address is used to access
the memory locations of the actual parameters in called function. In this method of
parameter passing, the formal parameters must be pointer variables.

That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters
(pointers). Whenever we use these formal parameters in called function, they
directly access the memory locations of actual parameters. So the changes made
on the formal parameters effects the values of actual parameters. For example
consider the following program...

67 | P a g e SCS 101 by TIRUS MUYA


#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:

Before swap: num1 = 10, num2 = 20


After swap: num1 = 20, num2 = 10

In the above example program, the addresses of variables num1 and num2 are
copied to pointer variables a and b. The changes made on the pointer
variables a and b in called function effects the values of actual
parameters num1 and num2 in calling function.

Standard Functions in C

The standard functions are built-in functions. In C programming language, the


standard functions are declared in header files and defined in .dll files. In simple
words, the standard functions can be defined as "the ready made functions defined
by the system to make coding more easy". The standard functions are also called
as library functions or pre-defined functions.

In C when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our
program, we must include stdio.hheader file using #include<stdio.h> statement.

C Programming Language provides the following header files with standard


functions.

68 | P a g e SCS 101 by TIRUS MUYA


Header Example
Purpose
File Functions

Provides functions to perform standard I/O


stdio.h printf(), scanf()
operations

Provides functions to perform console I/O


conio.h clrscr(), getch()
operations

Provides functions to perform mathematical


math.h sqrt(), pow()
operations

Provides functions to handle string data


string.h strlen(), strcpy()
values

Provides functions to perform general


stdlib.h calloc(), malloc()
functions

Provides functions to perform operations on time(),


time.h
time and date localtime()

Provides functions to perform - testing and isalpha(),


ctype.h
mapping of character data values islower()

Provides functions that are used in function setjump(),


setjmp.h
calls longjump()

Provides functions to handle signals during


signal.h signal(), raise()
program execution

Provides Macro that is used to verify


assert.h assert()
assumptions made by the program

Defines the location specific settings such


locale.h setlocale()
as date formats and currency symbols

Used to get the arguments in a function if


va_start(),
stdarg.h the arguments are not specified by the
va_end(), va_arg()
function

errno.h Provides macros to handle the system calls Error, errno

69 | P a g e SCS 101 by TIRUS MUYA


Provides constants related to floating point
float.h
data values

Defines the maximum and minimum values


limits.h of various variable types like char, int and
long

stddef.h Defines various variable types

circle(),
graphics.h Provides functions to draw graphics.
rectangle()

Scope of Variable in C

When we declare a variable in a program, it can not be accessed against the scope
rules. Variables can be accessed based on their scope. Scope of a variable decides
the portion of a program in which the variable can be accessed. Scope of the variable
is defined as follows...

Scope of a variable is the portion of the program where a defined variable can
be accessed.

The variable scope defines the visibility of variable in the program. Scope of a
variable depends on the position of variable declaration.

In C programming language, a variable can be declared in three different positions


and they are as follows...

a) Before the function definition (Global Declaration)


b) Inside the function or block (Local Declaration)
c) In the function definition parameters (Formal Parameters)

Before the function definition (Global Declaration)

Declaring a variable before the function definition (outside the function definition)
is called global declaration. The variable declared using global declaration is
called global variable. Tha global variable can be accessed by all the functions that
are defined after the global declaration. That means the global variable can be
accessed any where in the program after its declaration. The global variable scope
is said to be file scope.

70 | P a g e SCS 101 by TIRUS MUYA


#include <stdio.h>
#include<conio.h>
int num1, num2 ;
void main(){
void addition() ;
void subtraction() ;
void multiplication() ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}

Output:

num1 = 10, num2 = 20


addition = 30
subtraction = -10
multiplication = 200

In the above example program, the variables num1 and num2 are declared as global
variables. They are declared before the main() function. So, they can be accessed
by function main() and other functions that are defined after main(). In the above
example, the functions main(), addition(), subtraction() and multiplication() can
access the variables num1 and num2.

71 | P a g e SCS 101 by TIRUS MUYA


Inside the function or block (Local Declaration)

Declaring a variable inside the function or block is called local declaration. The
variable declared using local declaration is called local variable. The local variable
can be accessed only by the function or block in which it is declared. That means
the local variable can be accessed only inside the function or block in which it is
declared.

#include <stdio.h>
#include<conio.h>
void main(){
void addition() ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output:
ERROR

The above example program shows an error because, the variables num1 and num2
are declared inside the function main(). So, they can be used only inside main()
function and not in addition() function.

In the function definition parameters (Formal Parameters)

The variables declared in function definition as parameters have local variable


scope. These variables behave like local variables in the function. They can be
accessed inside the function but not outside the function.

#include <stdio.h>
#include<conio.h>
void main(){
void addition(int, int) ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;

72 | P a g e SCS 101 by TIRUS MUYA


addition(num1, num2) ;
getch() ;
}
void addition(int a, int b)
{
int sumResult ;
sumResult = a + b ;
printf("\naddition = %d", sumResult) ;
}
Output:
addition = 30

In the above example program, the variables a and b are declared in function
definition as parameters. So, they can be used only inside the addition() function.

Recursive Functions in C

In C programming language, function calling can be made from main() function,


other functions or from same function itself. The recursive function is definedd as
follows...

A function called by itself is called recursive function.

The recursive functions should be used very carefully because, when a function
called by itself it enters into infinite loop. And when a function enters into the
infinite loop, the function execution never gets completed. We should define the
condition to exit from the function call so that the recursive function gets
terminated.

When a function is called by itself, the first call remains under execution till the last
call gets invoked. Every time when a function call is invoked, the function returns
the execution control to the previous function call.

#include <stdio.h>
#include<conio.h>
int factorial( int ) ;
void main( )
{
int fact, n ;
printf(“Enter any positive integer: ”) ;
scanf(“%d”, &n) ;
fact = factorial( n ) ;
printf(“Factorial of %d is %d”, n, fact) ;
}
int factorial( int n )
{
int temp ;

73 | P a g e SCS 101 by TIRUS MUYA


if( n == o)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive
function call
return temp ;
}

Output:
Enter any positive integer: 3
Factorial of 3 is 6

In the above example program, the factorial() function call is initiated from main()
function with the value 3. Inside the factorial() function, the function calls
factorial(2), factorial(1) and factorial(0) are called recursively. In this program
execution process, the function call factorial(3) remains under execution till the
execution of function calls factorial(2), factorial(1) and factorial(0) gets completed.
Similarly the function call factorial(2) remains under execution till the execution of
function calls factorial(1) and factorial(0) gets completed. In the same way the
function call factorial(1) remains under execution till the execution of function call
factorial(0) gets completed. The complete execution process of the above program
is shown in the following figure...

74 | P a g e SCS 101 by TIRUS MUYA


type Qualifiers in C

In C programming language, type qualifiers are the keywords used to modify the
properties of variables. Using type qualifiers, we can change the properties of
variables. C programming language provides two type qualifiers and they are as
follows...

• const
• volatile

const type qualifier in C

The const type qualifier is used to create constant variables. When a variable is
created with const keyword, the value of that variable can't be changed once it is
defined. That means once a value is assigned to a constant variable, that value is
fixed and cannot be changed throughout the program.

The keyword const is used at the time of variable declaration. We use the following
syntax to create constant variable using constkeyword.

75 | P a g e SCS 101 by TIRUS MUYA


const datatype variableName ;

When a variable is created with const keyword it becomes a constant variable. The
value of the constant variable can't be changed once it is defined. The following
program generates error message because we try to change the value of constant
variable x.

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

int i = 9 ;
const int x = 10 ;
clrscr() ;

i = 15 ;
x = 100 ; // creates an error

printf("i = %d\nx = %d", i, x ) ;

Output:
Compiler error, we cannot modify const variable

→ For more details of const keyword and constant variables in C refer to C


Constants.

volatile type qualifier in C

The volatile type qualifier is used to create variables whose values can't be changed
in the program explicitly but can be changed by any external device or hardware.

For example, the variable which is used to store system clock is defined as volatile
variable. The value of this variable is not changed explicitly in the program but is
changed by the clock routine of the operating system.

Preprocessor Commands in C

In C programming language, preprocessor directive is a step performed before the


actual source code compilation. It is not the part of compilation. Preprocessor
directives in C programming language are used to define and replace tokens in the
text and also used to insert the contents of other files into the source file.

When we try to compile a program, preprocessor commands are executed first and
then the program gets compiled. Every preprocessor command begins with #

76 | P a g e SCS 101 by TIRUS MUYA


symbol. We can also create preprocessor commands with parameters.

Following are the preprocessor commands in C programming language...

#define

#define is used to create symbolic constants (known as macros) in C programming


language. This preprocessor command can also be used with parameterized macros.

#include <stdio.h>
#include<conio.h>

#define PI 3.14

#define SQR(x) x*x //Parameterized Macro

void main(){

double radius, area ;


clrscr() ;

printf("Enter the radius: ");


scanf("%ld",&radius);

area = PI * SQR(radius) ;

printf("area = %ld",area);

getch();
}

Output:

Enter the radius: 2


area = 12.56

#undef

#undef is used to destroy a macro that was already created using #define.

#ifdef

#ifdef returns TRUE if the macro is defined and returns FALSE if the macro is not
defined.

#ifndef

#ifndef returns TRUE if the specified macro is not defined otherwise returns FALSE.

77 | P a g e SCS 101 by TIRUS MUYA


#if

#if uses the value of specified macro for conditional compilation.

#else

#else is an alternative for #if.

#elif

#elif is a #else followed by #if in one statement.

#endif

#endif is used terminate preprocessor conditional macro.

#include

#include is used to insert specific header file into C program.

#error

#error is used to print error message on stderr.

#pragma

#pragma is used to issue a special command to the compiler.

In C programming language, there are some pre-defined macros and they are as
follows...

1. __ DATE __ : The current date as characters in "MMM DD YYYY" format.


2. __ TIME __ : The current time as characters in "HH : MM : SS" format.
3. __ FILE __ : This contains the current file name.
4. __ LINE __ : This contains the current line number.
5. __ STDC __ : Defines 1 when compiler compiles with ANSI Standards.

Arrays in C

When we work with large number of data values we need that many number of
different variables. As the number of variables increases, the complexity of the
program also increases and so the programmers get confused with the variable
names. There may be situations where we need to work with large number of similar
data values. To make this work more easy, C programming language provides a
concept called "Array".

An array is a special type of variable used to store multiple values of same data
type at a time.

78 | P a g e SCS 101 by TIRUS MUYA


An array can also be defined as follows...

An array is a collection of similar data items stored in continuous memory


locations with single name.

Declaration of an Array

In c programming language, when we want to create an array we must know the


datatype of values to be stored in that array and also the number of values to be
stored in that array.

We use the following general syntax to create an array...

datatype arrayName [ size ] ;

Syntax for creating an array with size and initial values

datatype arrayName [ size ] = {value1, value2, ...} ;

Syntax for creating an array without size and with initial values

datatype arrayName [ ] = {value1, value2, ...} ;

In the above syntax, the datatype specifies the type of values we store in that array
and size specifies the maximum number of values that can be stored in that array.

Example

int a [3] ;

Here, the compiler allocates 6 bytes of continuous memory locations with single
name 'a' and tells the compiler to store three different integer values (each in 2
bytes of memory) into that 6 bytes of memory. For the above declaration the
memory is organized as follows...

In the above memory allocation, all the three memory locations has a common name
'a'. So the accession of individual memory location is not possible directly. Hence
compiler not only allocates the memory but also assigns a numerical reference value

79 | P a g e SCS 101 by TIRUS MUYA


to every individual memory location of an array. This reference number is called as
"Index" or "subscript" or "indices". Index values for the above example is as follows...

Accessing Individual Elements of an Array

The individual elements of an array are identified using the combination of


'arrayName' and 'indexValue'. We use the following general syntax to access
individual elements of an array...

arrayName [ indexValue ] ;

For the above example the individual elements can be denoted as follows...

For example, if we want to assign a value to the second memory location of above
array 'a', we use the following statement...

a [1] = 100 ;

The result of above assignment statement is as follows...

Types of Arrays in C

80 | P a g e SCS 101 by TIRUS MUYA


In c programming language, arrays are classified into two types. They are as
follows...

1. Single Dimensional Array / One Dimensional Array


2. Multi Dimensional Array

Single Dimensional Array

In c programming language, single dimensional arrays are used to store list of values
of same datatype. In other words, single dimensional arrays are used to store a row
of values. In single dimensional array, data is stored in linear form. Single
dimensional arrays are also called as one-dimensional arrays, Linear Arrays or
simply 1-D Arrays.

Declaration of Single Dimensional Array

We use the following general syntax for declaring a single dimensional array...

datatype arrayName [ size ] ;

Example

int rollNumbers [60] ;

The above declaration of single dimensional array reserves 60 continuous memory


locations of 2 bytes each with the name rollNumbers and tells the compiler to allow
only integer values into those memory locations.

Initialization of Single Dimensional Array

We use the following general syntax for declaring and initializing a single
dimensional array with size and initial values.

datatype arrayName [ size ] = {value1, value2, ...} ;

Example

int marks [6] = { 89, 90, 76, 78, 98, 86 } ;

The above declaration of single dimensional array reserves 6 continuous memory


locations of 2 bytes each with the name marks and initializes with value 89 in first
memory location, 90 in second memory location, 76 in third memory location, 78 in
fourth memory location, 98 in fifth memory location and 86 in sixth memory
location.

81 | P a g e SCS 101 by TIRUS MUYA


We can also use the following general syntax to intialize a single dimensional array
without specifying size and with initial values...

datatype arrayName [ ] = {value1, value2, ...} ;

The array must be initialized if it is created without specifying any size. In this case,
the size of the array is decided based on the number of values initialized.

Example

int marks [] = { 89, 90, 76, 78, 98, 86 } ;

char studentName [] = "btechsmartclass" ;

In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler
stores one exttra character called \0 (NULL) at the end.

Accessing Elements of Single Dimensional Array

In c programming language, to access the elements of single dimensional array we


use array name followed by index value of the element that to be accessed. Here
the index value must be enclosed in square braces. Index value of an element in an
array is the reference number given to each element at the time of memory
allocation. The index value of single dimensional array starts with zero (0) for first
element and incremented by one for each element. The index value in an array is
also called as subscript or indices.

We use the following general syntax to access individual elements of single


dimensional array...

arrayName [ indexValue ]

Example

marks [2] = 99 ;

In the above statement, the third element of 'marks' array is assinged with
value '99'.

Multi Dimensional Array

An array of arrays is called as multi dimensional array. In simple words, an array


created with more than one dimension (size) is called as multi dimensional array.
Multi dimensional array can be of two dimensional array or three dimensional
array or four dimensional array or more...

82 | P a g e SCS 101 by TIRUS MUYA


Most popular and commonly used multi dimensional array is two dimensional array.
The 2-D arrays are used to store data in the form of table. We also use 2-D arrays to
create mathematical matrices.

Declaration of Two Dimensional Array

We use the following general syntax for declaring a two dimensional array...

datatype arrayName [ rowSize ] [ columnSize ] ;

Example

int matrix_A [2][3] ;

The above declaration of two dimensional array reserves 6 continuous memory


locations of 2 bytes each in the form of 2 rows and 3 columns.

Initialization of Two Dimensional Array

We use the following general syntax for declaring and initializing a two dimensional
array with specific number of rows and coloumns with initial values.

datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1,


r2c2,...}...} ;

Example

int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;

The above declaration of two dimensional array reserves 6 continuous memory


locations of 2 bytes each in the form of 2 rows and 3 coloumns. And the first row is
initialized with values 1, 2 & 3 and second row is initialized with values 4, 5 & 6.

We can also initialize as follows...

int matrix_A [2][3] = {


{1, 2, 3},
{4, 5, 6}
} ;

Accessing Individual Elements of Two Dimensional Array

In c programming language, to access elements of a two dimensional array we use


array name followed by row index value and column index value of the element that
to be accessed. Here the row and column index values must be enclosed in separate

83 | P a g e SCS 101 by TIRUS MUYA


square braces. In case of two dimensional array the compiler assigns separate index
values for rows and columns.

We use the following general syntax to access the individual elements of a two
dimensional array...

arrayName [ rowIndex ] [ columnIndex ]

Example

matrix_A [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1
of matrix_A array is assinged with value 10.

Applications of Arrays in C

In c programming language, arrays are used in wide range of applications. Few of


them are as follows...

a) Arrays are used to Store List of values

In c programming language, single dimensional arrays are used to store list of values
of same datatype. In other words, single dimensional arrays are used to store a row
of values. In single dimensional array data is stored in linear form.

b) Arrays are used to Perform Matrix Operations

We use two dimensional arrays to create matrix. We can perform various operations
on matrices using two dimensional arrays.

c) Arrays are used to implement Search Algorithms

We use single dimensional arrays to implement search algorihtms like ...

1. Linear Search
2. Binary Search

Arrays are used to implement Sorting Algorithms

We use single dimensional arrays to implement sorting algorihtms like ...

1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort, etc.,

84 | P a g e SCS 101 by TIRUS MUYA


Arrays are used to implement Datastructures

We use single dimensional arrays to implement datastructures like...

1. Stack Using Arrays


2. Queue Using Arrays

Arrays are also used to implement CPU Scheduling Algorithms

Pointers in C

In c programming language, we use normal variables to store user data values. When
we declare a variable, the compiler allocates required memory with specified name.
In c programming language, every variable has name, datatype, value, storage class,
and address. We use a special type of variable called pointer to store the address of
another variable with same datatype. Pointer is defined as follows...

Pointer is a special type of variable used to store the memory location address
of a variable.

In c programming language, we can create pointer variables of any datatype. Every


pointer stores the address of variable with same datatype only. That means, integer
pointer is used store the address of integer variable only.

Accessing the Address of Variables

In c programming language, we use the reference operator "&" to access the


address of variable. For example, to access the address of a variable "marks" we
use "&marks". We use the following printf statement to display memory location
address of variable "marks"...

printf("Address : %u", &marks) ;

In the above example statement %u is used to display address of marks variable.


Address of any memory location is unsigned integer value.

Declaring Pointers (Creating Pointers)

In c programming language, declaration of pointer variable is similar to the creation


of normal variable but the name is prefixed with *symbol. We use the following
syntax to declare a pointer variable...

datatype *pointerName ;

85 | P a g e SCS 101 by TIRUS MUYA


A variable declaration prefixed with * symbol becomes a pointer variable.

Example

int *ptr ;

In the above example declaration, the variable "ptr" is a pointer variable that can
be used to store any integer variable address.

Assigning Address to Pointer

To assign address to a pointer variable we use assignment operator with the


following syntax...

pointerVariableName = & variableName ;

For example, consider the following variables declaration...

int a, *ptr ;

In the above declaration, variable "a" is a normal integer variable and


variable "ptr" is an integer pointer variable. If we want to assign the address of
variable "a" to pointer variable "ptr" we use the following statement...

ptr = &a ;

In the above statement, the address of variable "a" is assigned to pointer


variable "prt". Here we say that pointer variable ptr is pointing to variable a.

Accessing Variable Value Using Pointer

Pointer variables are used to store the address of other variables. We can use this
address to access the value of the variable through its pointer. We use the
symbol "*" infront of pointer variable name to access the value of variable to which
the pointer is pointing. We use the following general syntax...

*pointerVariableName

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a = 10, *ptr ;
clrscr();

86 | P a g e SCS 101 by TIRUS MUYA


ptr = &a ;

printf("Address of variable a = %u\n", ptr) ;


printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
}

Output

Address of variable a = 65524


Value of variable a = 10
Address of variable ptr = 65526

In the above example program, variable a is a normal variable and variable ptr is a
pointer variable. Address of variable a is stored in pointer variable ptr. Here ptr is
used to access the address of variable a and *ptr is used to access the value of
variable a.

Memory Allocation of Pointer Variables

Every pointer variable is used to store the address of another variable. In computer
memory address of any memory location is an unsigned integer value. In c
programming language, unsigned integer requires 2 bytes of memory. So,
irrespective of pointer datatype every pointer variable is allocated with 2 bytes of
memory.

Pointers Arithmatic Operations in C

Pointer variables are used to store address of variables. Address of any variable is
an unsigned integer value i.e., it is a numerical value. So we can perform arithematic
operations on pointer values. But when we perform arithematic operations on
pointer variable, result depends on the amount of memory required by the variable
to which the pointer is pointing.

In c programming language, we can perform the following arithematic operations on


pointers...

1. Addition
2. Subtraction
3. Increment
4. Decrement
5. Comparison

Addition Operation on Pointer

In c programming language, the addition operation on pointer variables is calculated


using the following formula...

87 | P a g e SCS 101 by TIRUS MUYA


AddressAtPointer + ( NumberToBeAdd * BytesOfMemoryRequiredByDatatype )

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr = intPtr + 3 ; // intPtr = 1000 + ( 3 * 2 )


floatPtr = floatPtr + 2 ; // floatPtr = 2000 + ( 2 * 4 )
doublePtr = doublePtr + 5 ; // doublePtr = 3000 + ( 5 * 6
)

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

intPtr value : 1006


floatPtr value : 2008
doublePtr value : 3030

Subtraction Operation on Pointer

In c programming language, the subtraction operation on pointer variables is


calculated using the following formula...

AddressAtPointer - ( NumberToBeAdd * BytesOfMemoryRequiredByDatatype )

Example

#include<stdio.h>
#include<conio.h>

void main()
{

88 | P a g e SCS 101 by TIRUS MUYA


int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr = intPtr - 3 ; // intPtr = 1000 - ( 3 * 2 )


floatPtr = floatPtr - 2 ; // floatPtr = 2000 - ( 2 * 4 )
doublePtr = doublePtr - 5 ; // doublePtr = 3000 - ( 5 * 6
)

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

intPtr value : 994


floatPtr value : 1992
doublePtr value : 2970

Increment & Decrement Operation on Pointer

The increment operation on pointer variable is calculated as follows...

AddressAtPointer + NumberOfBytesRequiresByDatatype

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr++ ; // intPtr = 1000 + 2


floatPtr++ ; // floatPtr = 2000 + 4
doublePtr++ ; // doublePtr = 3000 + 6

89 | P a g e SCS 101 by TIRUS MUYA


printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

intPtr value : 1002


floatPtr value : 2004
doublePtr value : 3006

The decrement operation on pointer variable is calculated as follows...

AddressAtPointer - NumberOfBytesRequiresByDatatype

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr-- ; // intPtr = 1000 - 2


floatPtr-- ; // floatPtr = 2000 - 4
doublePtr-- ; // doublePtr = 3000 - 6

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

intPtr value : 998


floatPtr value : 1996
doublePtr value : 2994

Comparison of Pointers

90 | P a g e SCS 101 by TIRUS MUYA


The comparison operation is perform between the pointers of same datatype only.
In c programming language, we can use all comparison operators (relational
operators) with pointers.

We can't perform multiplication and division operations on pointers.

Pointers to Pointers in C

In c programming language, we have pointers to store the address of variables of


any datatype. A pointer variable can store the address of normal variable. C
programming language also provides pointer variable to store the address of another
pointer variable. This type of pointer variable is called as pointer to pointer variable.
Sometimes we also call it as double pointer. We use the following syntax for creating
pointer to pointer…

datatype **pointerName ;

Example

int **ptr ;

Here, ptr is an integer pointer variable that stores the address of another integer
pointer variable but does not stores the normal integer variable address.

Points to be Remembered

1. To store the address of normal variable we use single pointer variable


2. To store the address of single pointer variable we use double pointer
variable
3. To store the address of double pointer variable we use triple pointer
variable
4. Similarly the same for remaining pointer variables also…

Example Program

#include<stdio.h>
#include<conio.h>

void main()
{
int a ;
int *ptr1 ;
int **ptr2 ;
int ***ptr3 ;

clrscr() ;

ptr1 = &x ;

91 | P a g e SCS 101 by TIRUS MUYA


ptr2 = &ptr1 ;
ptr3 = &ptr2 ;

printf(“Address of ‘x’ = %u\n”, ptr1) ;


printf(“Address of ‘ptr1’ = %u\n”, ptr2) ;
printf(“Address of ‘ptr2’ = %u\n”, ptr3) ;

getch() ;
}

Pointers to void in C

In c programming language, pointer to void is the concept of defining a pointer


variable that is independent of datatype. In C programming language, void pointer
is a pointer variable used to store the address of variable of any datatype. That
means single void pointer can be used to store address of integer variable, float
variable, character variable, double variable or any structure variable. We use the
keyword "void" to create void pointer. We use the following syntax for creating
pointer to void…

void *pointerName ;

Example

void *ptr ;

Here, "ptr" is a void pointer variable which is used to store the address of any
datatype variable.

Points to be Remembered

1. void pointer stores the address of any datatype variable.

Example Program

#include<stdio.h>
#include<conio.h>

void main()
{
int a ;
float b ;
char c ;

void *ptr ;

clrscr() ;

92 | P a g e SCS 101 by TIRUS MUYA


ptr = &a ;
printf(“Address of integer variable ‘a’ = %u\n”, ptr) ;

ptr = &b ;
printf(“Address of float variable ‘b' = %u\n”, ptr) ;

ptr = &c ;
printf(“Address of character variable ‘c’ = %u\n”, ptr) ;

getch() ;
}

Pointers to Arrays in C

In c programming language, when we declare an array the compiler allocates


required amount of memory and also creates constant pointer with array name and
stores the base address of that pointer in it. The address of first element of an array
is called as base address of that array.

The array name itself acts as pointer to the first element of that array. Consider the
following example of array declaration...

int marks[6] ;

For the above declaration, the compiler allocates 12 bytes of memory and the
address of first memory location (i.e., marks[0]) is stored in a constant pointer
called marks. That means in the above example, marks is a pointer to marks[0].

Example Program

#include<stdio.h>
#include<conio.h>

void main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;

clrscr() ;

ptr = marks ;
printf(“Base Address of 'marks' array = %u\n”, ptr) ;

getch() ;
}

Points to be Remembered

1. An array name is a constant pointer.

93 | P a g e SCS 101 by TIRUS MUYA


2. We can use the array name to access the address and value of all the
elements of that array.
3. Since array name is a constant pointer we can't modify its value.

Consider the following example statements...


ptr = marks + 2 ;

Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.

printf("Address of 'marks[4]' = %u", marks+4) ;

The above printf statement displays the address of element "marks[4]".

printf("Value of 'marks[0]' = %d", *marks) ;


printf("Value of 'marks[3]' = %d", *(marks+3)) ;

In the above two statements, first printf statement prints the value 89 (i.e., value
of marks[0]) and the second printf statement prints the value 72 (i.e., value of
marks[3]).

marks++ ;

The above statement generates compilation error because the array name acts as
a constant pointer. So we can't change its value.

In the above example program, the array name marks can be used as follows...

marks is same as &marks[0]


marks + 1 is same as &marks[1]
marks + 2 is same as &marks[2]
marks + 3 is same as &marks[3]
marks + 4 is same as &marks[4]
marks + 5 is same as &marks[5]
*marks is same as marks[0]
*(marks + 1) is same as marks[1]
*(marks + 2) is same as marks[2]
*(marks + 3) is same as marks[3]
*(marks + 4) is same as marks[4]
*(marks + 5) is same as marks[5]

Pointers to Multi Dimensional Array

In case of multi dimensional array also the array name acts as a constant pointer to
the base address of that array. For example, we declare an array as follows...

int marks[3][3] ;

94 | P a g e SCS 101 by TIRUS MUYA


In the above example declaration, the array name marks acts as constant pointer to
the base address (address of marks[0][0]) of that array.
In the above example of two dimensional array, the element marks[1][2] is
accessed as *(*(marks + 1) + 2).

Pointers For Functions in C

In c programming language, there are two ways to pass parameters to functions.


They are as follows...

1. Call by Value
2. Call By Reference

We use pointer variables as formal parameters in call by reference parameter


passing method.
In case of call by reference parameter passing method, the address of actual
parameters is passed as arguments from the calling function to the called function.
To recieve this address, we use pointer variables as formal parameters.

Consider the following program for swapping two variable values...

Example - Swapping of two variable values using Call by Reference

#include<stdio.h>
#include<conio.h>

void swap(int *, int *) ;

void main()
{
int a = 10, b = 20 ;

clrscr() ;

printf(“Before swap : a = %d and b = %d\n", a, b) ;

swap(&a, &b) ;

printf(“After swap : a = %d and b = %d\n", a, b) ;

getch() ;
}
void swap(int *x, int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
}

95 | P a g e SCS 101 by TIRUS MUYA


Output

Before swap : a = 10 and b = 20


After swap : a = 20 and b = 10

In the above example program, we are passing the addresses of


variables a and b and these are recieved by the pointer variables x and y. In the
called function swap we use the pointer variables x and y to swap the values of
variables a and b.

96 | P a g e SCS 101 by TIRUS MUYA

You might also like