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

CIE 205 Notes

Uploaded by

soumitray45
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 views29 pages

CIE 205 Notes

Uploaded by

soumitray45
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
You are on page 1/ 29

Hajee Mohammad Danesh Science and Technology University

Programming in C
(Introductory theory)

Computer and its Components:


A computer is a device that accepts information (in the form of digitalized data) and manipulates it for some result
based on a program or sequence of instructions on how the data is to be processed.
Basic components of a computer can be classified in two categories as:
i. Hardware
ii. Software

Hardware: All the physical parts of a computer are called hardware. It may be said that the physical structure of
a computer is the combination of various hardware. They are tangible physical objects, i.e., visible and touchable.
Example: hard disk, motherboard, RAM, ROM, Processor etc.

Software: Software is the collection of some programs. It means all the profiles, operating units etc. It is that part
of a computer system which consists of encoded information or computer instructions, in contrast to the physical
hardware from which the system is built. A software is not visible, that is they have no physical existence.
Example: AutoCAD, Photoshop, office 2016, Bijoy etc.

Memory of Computer: RAM, ROM and HDD:


Programming language usually deals with computer memories. The memories can be classified into 3 categories
as
RAM:
➢ Random access memory
➢ Volatile type.
➢ Acts as temporary storage of data during the running of a program.
➢ Requires a flow of electricity to retain data
ROM:
➢ Read only memory.
➢ Non-volatile type.
➢ Reading access only, no regular writing access, need special technique for writing.
➢ Pre-written to hold the instructions. (Example: for booting-up the computer.)
➢ Can retain data without the flow of electricity
HDD:
➢ Hard Disc Drive, the storage device.
➢ User can read or write data into it whenever he wants.
➢ Reading and writing speed is less as compared to RAM.
➢ Can retain data after its power supply is cut.

Computer program: To process a particular set of data, the computer must be given an appropriate set of
instruction. A computer program is a collection of instructions that performs a specific task when executed by a
computer. These instructions are entered in a computer’s memory.

Types of program:
Computer programs are divided into two broad categories as
i) Source program
ii) Object program

Source Programe: The original high level language program before compilation is called source program or
source code. As computers cannot understand the statements of high-level language, the source code cannot be
executed by computer directly. It is converted into object code and then executed.

Md. Roknuzzaman, Department of Civil Engineering Page 1


Hajee Mohammad Danesh Science and Technology University

Object program:
A program in machine language is called objet program or object code or machine code. It is he resulting machine
language program after compilation of source program. Object program directly gives command to computer.

Importance of Computer Program in Civil Engineering:


Now-a-days, knowledge of computer programming is very essential. In the Civil engineering point of view its
importance is given below:
1) Mathematical, logical and structural problems may be solved by using computer program.
2) Computer program ensures greater accuracy of calculation.
3) Long calculations can be performed within a short time.
4) Various long and complex calculation of structural analysis can be performed easily and accurately using
computer program.
5) Computer programming is easy to learn, write and apply in various fields.
Thus programming is very important for a civil Engineer.

Programming Language:
A programming language is a formal computer language or constructed language designed to give instructions to a
machine, particularly a computer. Programming languages can be used to create programs to control the behavior
of a machine or to express algorithms.

Classification of Computer Languages:


Computer programming language can be classified into two major categories:
i. Low level language
ii. High level language

Low level language:


The languages which use only primitive operations of the computer are known as low language. In these
languages, programs are written by means of the memory and registers available on the computer. Programs
written in one low level language works for a particular machine and can’t be ported on any other machine with
different architecture. The low level languages are:
i. Machine language
ii. Assembly language

Machine Language:
In machine language program, the computation is based on binary numbers. All the instructions including
operations, registers, data and memory locations are given in there binary equivalent i.e., a combination of 0 and
1. In short, binary language is called machine language.
The machine directly understands this language by virtue of its circuitry design so these programs are directly
executable on the computer without any translations. This makes the program execution very fast. Machine
languages are also known as first generation languages.

Advantages:
1) Direct manipulation of memory and register.
2) Most efficient use of computer system resources like storage, registers, etc.
3) Program are directly executable
4) No need of translators.
5) Can manipulate the individual bits in a computer system with high execution speed.

Disadvantages:
1) Machine dependent language and therefore, programs are not portable from one computer to other.
2) Poor programmer productivity.
3) Requires a high level of programming skill which increases programmer training costs.
4) More error prone and difficult to debug because it is very difficult to remember.
5) Program size is comparatively very big and complex.

Md. Roknuzzaman, Department of Civil Engineering Page 2


Hajee Mohammad Danesh Science and Technology University

Assembly Language:
The language in which symbolic names (i.e. π, e etc.) are used to perform certain job is called assembly language.
It is also known as second generation languages. This language substitutes alphabetic or numeric symbols for the
binary codes of machine language and thus provides us with a facility to write reusable codes.
These language require a translator known as “Assembler” for translating the program code written in assembly
language to machine language. Because computer can interpret only the machine code instruction, once the
translation is completed the program can be executed.

Advantages:
1) Provides optimal use of computer resources like registers and memory because of direct use of these
resources within the programs.
2) Easier to use than machine language because there is no need to remember or calculate the binary
equivalents for certain items.
3) An assembler is useful for detecting programming errors.
4) Provides the facility of using reusable codes.

Disadvantages:
1) Programs are not directly executable and need translation.
2) Language is machine dependent and, therefore, not portable from one machine to another.
3) Requires a high level of programming skills and knowledge of computer architecture of the particular
machine.

High level language:


The language of giving command to a computer which is written in human understanding from is called high level
language. These languages are procedure-oriented and are intended to be machine independent. These languages
require translators (compilers and interpreters) for execution. These are called third generation languages.
Example: BASIC, ADA, Pascal, C, C++, Java etc.

Advantages:
1) Machine independent.
2) Easier to learn than assembly language.
3) Less time is required to write programs.
4) Provides better documentation.
5) Easier to maintain.
6) Have an extensive vocabulary.

Disadvantages:
1) A long sequence statement is to be written for every program.
2) Additional memory space is required for storing compiler or interpreter.
3) Execution time is very high as the programs are not directly executable.

ASCII Encoding:
ASCII (American Standard Code for Information Interchange) is the most common format for text files in
computers and on the Internet. In an ASCII file, each alphabetic, numeric, or special character is represented with
a 7-bit binary number (a string of seven 0s or 1s). 128 possible characters are defined.

Compiler:
Compiler is a program that translates the high level language program to machine level language program. It
translates the entire program at a time into machine level language program. Translation of compiler is speedy as
compared to an interpreter and the compiled machine code works without the need of any associated file.

Interpreter:
Interpreter also translates the high level language program into machine level language program but it’s
translation is done line by line. It’s translation speed is relatively slow and the translated machine code does not
work without the associated interpreter.

Md. Roknuzzaman, Department of Civil Engineering Page 3


Hajee Mohammad Danesh Science and Technology University

Dealing with Error Using Compiler:


Compilers detect error in program and allow the programmer to make corrections. But during the time of writing a
program there may be several errors such as syntax error, logical error, declaring error and so on. Compilers only
show the syntax error, data type error, declaring error etc.
If there are errors in logic or in assigning values of various variables or like this, the compiler will not show any
error and the program will execute. This resulting program will not give the correct solution of problem.
Thus, programmers should be cautious while coding the logical part of the program keeping in mind that, no
errors in compilation of program gives no guaranty having no errors in program.

Algorithm:
Step by step instruction to do a certain job is called algorithm.

Flow chart:
The graphical representation of any algorithm is called flow chart. It is most helpful in planning, designing
structuring a program.

Bit:
Every piece of information stored with in the computer’s memory is encoded as some unique combination of 0
and 1. Each 0 and 1 is called a ‘Bit’. It is the smallest unit of computer’s memory.

Bytes:
Bytes is a group of 8 adjacent bits that represents characters such as letters, numbers or special symbols.
1 𝑘𝑖𝑙𝑜𝑏𝑦𝑡𝑒 = 1024 𝐵𝑦𝑡𝑒𝑠
1 𝑀𝑒𝑔𝑎𝑏𝑦𝑡𝑒 = 1024 𝐾𝑖𝑙𝑜 𝑏𝑦𝑡𝑒
1 𝐺𝑖𝑔𝑎𝑏𝑦𝑡𝑒 = 1024 𝑀𝑒𝑔𝑎 𝑏𝑦𝑡𝑒
1 𝑇𝑒𝑟𝑎𝑏𝑦𝑡𝑒 = 1024 𝐺𝑖𝑔𝑎 𝑏𝑦𝑡𝑒

“C” Language and “C” Program:


C is a high-level and general purpose programming language that is ideal for developing firmware or portable
applications. Originally intended for writing system software, C was developed at Bell Labs by Dennis Ritchie for
the Unix Operating System (OS) in the early 1970s. A program written in “C” language is often named as a “C”
program.

Structure of a “C” program:

Documentation selection
Link section
Definition section
Global declaration section

Main function ()
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2
................ user defined function.
…………..
Function n

Md. Roknuzzaman, Department of Civil Engineering Page 4


Hajee Mohammad Danesh Science and Technology University

Documentation section:
The documentation Section consists of a set of comment lines giving the name of the program, the author and
other details which the programmer would like to use later.
Example: /* Program for determining summation*/
Documentation refers to the details that describe a program. Documentation is important to understand, repair and
modify the source code.
Program documentation has two main aspects.
1) Selection of meaningful variable name
The variable names should be related to the data used. Confused variable names must be avoided.
As example,
Student = boys + girls;
is more meaningful than
s = b + g;
2) Use of comments
Appropriate comments should be used after statements, function etc. It will help to understand the code
later.
As example,
M = R1 * x – n; /*Equation for bending moment*/
The underlined portion is comment.

Link section:
The link section provides information to the compiler to link function from the system library.
Example: # include <stdio.h>

Definition section:
Definition section defines all the symbolic constants.
Example: #define PI 3.1416

Global declaration section:


There are some variables that are used in more than one function. Such variables are called global variables and
are declared in the global declaration section that is outside the main function.
Example: int a ;

Main function section:


Every C program must have a main function section consisting two pants,
i) Declaration part ii) Executable part
The declaration part declares all the variables used in executable part.
There must be at least one statement in the executable part which contains instructions to perform certain task..
The program execution begins with an opening brace and ends with a closing brace. All the statements in
declaration and executable part end with semi-colon.

Sub program Section:


The subprogram section contains all the user defined function that are called in the main function. The user
defined functions are generally paste immediately after the main function, although they may appear in anywhere
of the program.

Md. Roknuzzaman, Department of Civil Engineering Page 5


Hajee Mohammad Danesh Science and Technology University

Example of a program with different elements:

/*program to find the area of circle*/ /*Documentation section*/

#include "stdio.h" /*link section*/


#include "conio.h" /*link section*/

#define PI 3.14 /*definition section*/

float area; /*global declaration section*/

void main() /*Main function section*/


{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}

Library Function:
The pre-defined functions which are included with the compiler are called library functions.
Ex: clrscr() ; getch() etc.

User defined function:


Though there are various library functions to perform various job, but sometimes the programmer have to create
some functions to perform certain job or to make the program easy and less complex. These functions are called
user-defined function.
Ex: void playmusic ( ) ; void copy_msg ( ) etc.

Program example with UDF:

#include <stdio.h>
int addNumbers(int a, int b); // UDF prototype

void main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // UDF call

printf("sum = %d",sum);

getch();
}

int addNumbers(int a,int b) // UDF definition


{
int result;
result = a+b;
return result;
}
Md. Roknuzzaman, Department of Civil Engineering Page 6
Hajee Mohammad Danesh Science and Technology University

Difference of library function and user-defined functions:


1) Library functions are previously included with compiler, but user-defined functions are created by
programmer.
2) Same library may be used in various ANSI C compilers, but a user-defined function may be used in one
compiler only.
3) Library functions may be used in various programs, but one user-defined function may be called in one
program only.
4) A library function is reusable by many programmers to solve the same problem over and over whereas a
UDF is specific to programmer’s needs at a certain case.

Character set:
The characters that can be used to form words, numbers and expressions depend on the computer on which
program is run. The characters in C program are as follows.
i) Letter → A-Z, a-z
ii) Digit → 0-9
iii) Special characters → , . ; / \ _ - % # $ ^ ( ) etc.
iv) White Space → New line ( \n )
Horizontal tab ( \t )
Blank space
Formfeed
Carriage return
C – Token:
The smallest individual units in a C program are known as C- tokens.
C- Tokens are of six types.

C-token
Keyword Identifier Constant String Special Symbol/ Operator
Punctuator

Keyword:
There are some reserved words in C program which have standard, predefined meanings; these words are called
keyword. According to ANSI, there are 32 keywords in C.

C-Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Rules of Keyword:
1) All keywords have fixed meaning and it cannot be changed.
2) All key words must be written in lower case letter.
3) A keyword cannot be used for any other purpose (such as identifier).

Identifiers:
Identifiers are the names that are given to various program elements such as variables, functions, arrays etc.
Ex: int my_name; here my_name is an identifier

Md. Roknuzzaman, Department of Civil Engineering Page 7


Hajee Mohammad Danesh Science and Technology University

Rules for identifier:


1) 1st character must be a letter or an underscore.
2) Must consists of only letters, digits or under score.
3) Keywords cannot be used as identifier.
4) Must not contain any blank space.
5) “main” cannot be used as an identifier for a variable.

Unique nature of keywords:


A keyword cannot be used as any other token such as an identifier. The keywords are the reserved words in C
program, which have standard predefined meanings which cannot be changed. For instance, if a keyword is used
as an identifier, then the compiler do not take it as an identifier, because every keyword has specific meaning
which can’t be changed. The compiler therefore detects a misplaced keyword and shows error. So keywords
cannot be used as any other token.

Variable:
Variables are simply names or identifiers used to refer to some location in memory – a location that holds a value
with which we are working. It may help to think of variables as a placeholder for a value. You can think of a
variable as being equivalent to its assigned value. Unlike constant, variable changes its value during the execution
of the program.
Ex : a,b,c

Global and Local Variable:


Global variables are the variables that are used in more than one function. They are declared in the global
declaration section outside the main function. On the other hand the variables to be used in a particular function
are called local variable for that function. The local variables are declared inside the braces of the corresponding
function usually at its starting.

Data Type in C:
While declaring or defining a variable or a constant a programmer often needs to specify the type of data to be
stored in that variable or constant.
Some of the data types supported in C are:

Memory Range of Value


Data Type Description keyword
Space

Character Data Stores the Single Character 1 byte -128 to 127 (or a single character)
char
Type Value

Integer Data 2 byte -32768 to 32767


Stores the Integer Value int
Type

4 byte 3.4 × 10−38 𝑡𝑜 3.4 × 1038


Stores the Floating Point
Float Data Type float (Maximum 6 digits after decimal
Value
point)

8 byte 1.7 × 10−308 𝑡𝑜 1.7 × 10308


Double Data Stores the long range
double (Maximum 15 digits after decimal
Type Floating Value
point)

Md. Roknuzzaman, Department of Civil Engineering Page 8


Hajee Mohammad Danesh Science and Technology University

Data Type Modifiers:


There are some keywords in C that modify the bitwise memory allocation for data types. These are called
modifiers. They are:
signed, unsigned, long and short.

Data Type Data type with Modifier Range


char char -128 to 127
signed char -128 to 127
unsigned char 0 to 255
int int -32768 to 32767
signed int -32768 to 32767
short int -32768 to 32767
unsigned int 0 to 65535
long int -2147483648 to 2147483648
unsigned long int 0 to 4294967295
float No modifier 3.4 × 10−38 𝑡𝑜 3.4 × 1038
double double 1.7 × 10−308 𝑡𝑜 1.7 × 10308
short double
long double 1.7 × 10−308 𝑡𝑜 1.7 × 10308
3.4 × 10−4932 𝑡𝑜 3.4 × 104932

Significance of unsigned variable/constant:


In C program every data type has fixed range for containing data. This range can be changed using the modifiers.
The keyword ‘unsigned’ is a modifier that can be used for integer and character type data. When it is used before
the data type ‘int’ the corresponding variable/constant is called unsigned integer variable/constant. An unsigned
integer variable/constant has the same capacity of containing data as normal integer variable/constant but the
range starts from 0. The data range for normal integer type is -32,768 to 32,767. An integer constant cannot be less
than -32,768 and more than 32,767. But an unsigned integer constant has a data range of 0 to 65535. An unsigned
integer constant cannot be a negative value and can be up to 65535. So we can handle larger positive value of
constant by declaring it unsigned. This is the significance of declaring a constant unsigned.

Variable Declaration:
We must declare a variable before using it in an expression. Usually global variables are declared outside of the
main functions and local variables are declared at the beginning of corresponding function. Variable declaration
format is:
data_type variable_name[= value]
example: int SALARY=100000; char NAME= “Rahim”; etc.

Rules for variable declaration:


1) Data type must be specified.
2) They must begin with a letter, though space system permits underscore as a first character.
3) Uppercase and lowercase letters are significant.
4) No special character except ‘_’ and ‘$’ can be used in variable name.
5) First 31 characters of two variable names cannot be the same.
6) One variable name cannot be used more than once.
7) It should not be a keyword.
8) White space is not permitted.

Md. Roknuzzaman, Department of Civil Engineering Page 9


Hajee Mohammad Danesh Science and Technology University

Constant:
Constant may be defined as the fixed value that does not change during the execution of a c program. Constants
used in C program can be classified as:
1) Symbolic Constants
2) Numeric Constants
a. Integer constants
i. Decimal
ii. Octal
iii. Hexadecimal constants
b. Real or Floating point constants
3) Character constants
4) String constants
5) Backslash character constants

Symbolic constant
A symbolic constant is a name that substitutes for a sequence of characters. These characters may represent either
numeric constant or a character constant or a string constant. These constants are to be defined using #define and
unlike variables there is no need to specify data type.
Ex - #define PI 3.14 , here PI is symbolic constant

Rules for symbolic constant


1) Symbolic name should have the same form as variable name, but in general practice, it is written in
uppercase latters.
2) Pound sign “#” must be the 1st character in the line.
3) No blank space is permitted between the pound sign # and the word “define”.
4) A blank space is required between the pound sign define “#define” and the symbolic name and the
constant.
5) The # define statement must not end with a semi-colon.
6) The #define statement may appear in anywhere in the program but before it is referenced.

Rules for Numeric Constant


1) Comma and blank space cannot be included within the constant.
2) The constant can be presented by a minus sign, if required.

Integer Constant:
An integer constant is an integer valued number. Thus it consists of sequence of digits. Integer constant may be
written in three number types:
1) Decimal (0~9); base=10
2) Octal (0~7); base=8 (it must start with 0)
3) Hexadecimal(o~9,a~f); base=16(must start with 0x)

Floating point constant :


Floating point constant is decimal number that contains either a decimal point or an exponent or both.
Ex : 3.14 , 6E5

Character constant:
A character contains a single character enclosed within a pair of single quotation marks.
Ex : ‘A’, ‘b’ etc.

Md. Roknuzzaman, Department of Civil Engineering Page 10


Hajee Mohammad Danesh Science and Technology University

String constant:
A string constant consists of any number of consecutive characters encloses within a double quotation mark .The
characters may be letters, digits, special symbols or blank spaces.
Ex ; “2001”, “Hellow, there” etc

Constants, data type and examples:

Constant type data type Example

Integer constants int const int ID_NO=44;


unsigned int const unsigned long int VALUE=4294967294;
long int
unsigned long int

Floating point constants float const int FRACTION=44.453;


double const long double FRACTION=132e789;
long double

Octal constant int const int VALUE=013;

Hexadecimal constant int const int VALUE=0x90;

character constants char const char NAME= ‘P’;

string constants char const char NAME= “PENCIL”;

Backslash Character Constant:


There are some characters having special meaning in C language when they are preceded by backslash symbol.
They facilitates the use of special function.
Given below is the list of special characters and their purpose.

Backslash Backslash
character Meaning character Meaning

\b Backspace \\ Backslash

\f Form feed \v Vertical tab

\n New line \a Alert or bell

\r Carriage return \? Question mark

\t Horizontal tab \N Octal constant (N is an octal constant)

\” Double quote \XN Hexadecimal constant (N – hex.dcml cnst)

\’ Single quote

Md. Roknuzzaman, Department of Civil Engineering Page 11


Hajee Mohammad Danesh Science and Technology University

Operators, Operands and Expression:


An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation. They are
in program to manipulate data and variable.
The data items that operators act upon are called operands.
The combination of operators and operands is called an expression.
Example: SUM=a+b; is an expression. Here = and + are operators and SUM, a and b are operands.

Classification of Operators:
1) Arithmetic operator
2) Relational operator
3) Logical operator
4) Assignment operator Increment & decrement operator
5) Conditional operator
6) Bitwise operator
7) Special operator

Arithmetic operator:
There are various mathematical operation used in C program as adding, subtracting, multiplying, dividing etc.
These operations are performed using arithmetic operators.
Example:
Operator Meaning C Expression
+ Adding a + b;
- Subtracting a - b;
* Multiplying a * b;
/ Division a / b;
% Modulo Division a % b;

Relational Operator:
A relational operator is used in decision making statements and to decide the course of action of running program.
It is used to compare two operands.
Example:-
Operator Meaning C Expression
< Is less than a < b;
> Is greater than a > b;
<= Is less than or equal to a <= b;
>= is greater than or equal to a >= b;
== is equal to a = = b;
!= is not equal to a != b;

Logical Operator:
It is an operator which combines two or more relational expressions. It is used to make logical expressions. It is
used when we want to test more than one condition and make decision.
Example:
Operator Meaning C Expression
&& logical AND a >b && a < c;
|| logical OR a > b || a < c;
! logical NOT !(a==3)

Md. Roknuzzaman, Department of Civil Engineering Page 12


Hajee Mohammad Danesh Science and Technology University

Assignment Operator:
Assignment Operators are used to assign the result of an expression to a variable.
Example:
Operator Meaning C Expression
= Assignment a = 10;
+= add and assign a +=10;
-= subtract and assign a -= 10;
*= multiply and assign a *=10;
/= divide and assign a /= 10;
%= take modulus and assign a %= 10;

Increment and Decrement Operator:


C language allows two special types of operators that are not found in other languages. These are increment and
decrement operator.
The increment operator ++ adds one to operand and the decrement operator – – subtracts one from operand.
Example:
Operator Meaning C Expression
++ add one a++
–– subtract a– –

Conditional Operator:
A conditional Operator is a ternary operator pair that is used to make conditional expressions. This operator is
“?:”. This operator is used in the form,
exp1 ? exp2 : exp3
where, exp1, exp2, exp3 are expressions.
The exp1 is first evaluated. If it is true, then exp2 is evaluated and becomes the value of expression. If exp1 is
false, then exp3 is evaluated and its value becomes the value of expression.

Bitwise Operator:
C language has the capability to support some special operators known as bitwise operators which are used to
manipulate data at bit level. They are used to test the bit or shifting them right or left.

Bitwise Operator Meaning


& bitwise AND
| bitwise OR
<< shift left
>> shift right
^ bitwise exclusive OR

Special Operator:
C allows some special operators such as comma operator, sizeof operator, pointer operator etc. They are used for
special purposes.

Md. Roknuzzaman, Department of Civil Engineering Page 13


Hajee Mohammad Danesh Science and Technology University

Control Statement:
It is seen that a C program is a set of statements which are executed sequentially in the order in which they appear.
This happens where no option is employed. But, in practice we have to take decisions according to the situation
and requirement. Thus some decision making statements are required which are generally called control
statements.

Types of Control Statement:


The commonly used control statements can be classified as follows
1) Selection statements
a. if
b. switch
2) Iteration statements
a. for
b. while
c. do…while
3) Jump Statement
a. break
b. continue
c. goto
d. return
4) Label statement
a. case
b. default
5) Expression Statement

Decision making with if statement:


The if statement is a powerful decision making statement and is used to control the flow of execution of
statements. It is basically a two way control statement and is used in conjunction with an expression. It takes the
following form:
if (test expression)
It allows the computer to evaluate the expression first and then depending on the value of expression being true or
false, the control is transferred to a particular statement.
Thus the point of the program has two paths, one for the true condition and another for false condition.

Types of if statement:
There are four types of if statements in C program
1) simple if statement
2) if…………else statement
3) Nested if………..else statement
4) else if ladder.

Md. Roknuzzaman, Department of Civil Engineering Page 14


Hajee Mohammad Danesh Science and Technology University

Simple if statement:
In simple if statement, there is only one statement block which is executed only if the test expression is true. If the
test expression is false, the program skips the statement block and the control is transferred subsequently to the
statement-x.

General form:
if(test expression)
{
Statement block;
}
statement –x;

Flow-chart:

Example:
if(colour = = RED)
{
Score = score + bonus;
}
printf(“%f”, score);

The if………………….else statement:


In the if………..else statement, there are two block statements, false block and true block. If the test expression is
true then the true block is executed, otherwise, the false block is executed. In either case only one block is
executed. In the both cases, the control is transferred subsequently to the statement-x.

General form:
if(test expression)
{
True block statement;
}
else
{
False block statement;
}
Statement-x

Md. Roknuzzaman, Department of Civil Engineering Page 15


Hajee Mohammad Danesh Science and Technology University

Flowchart:

Example:
if(code = = 1)
{
boy = boy + 1;
}
else
{
girl = girl + 1;
}
printf(“%f and %f”, boy, girl);

Nested if…….else statement:


When a series of decisions are involved, more than one if………else statements are to be used. When these
statements are used in nested form it is called nested if………else statement.

General form:
if(test expression1)
{
if(test expression2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

Md. Roknuzzaman, Department of Civil Engineering Page 16


Hajee Mohammad Danesh Science and Technology University

Flow Chart:

Example:
A bonus of 2% of the balance held on 31 December is given to everyone, irrespective of their balance and 5% is
given to female account holders, if their balance is more than 5000 taka and 3% if their balance is less than 5000
taka.
if(account == Female)
{
if(balance > 5000);
{
bonus = balance * 0.05;
}
else
{
bonus = balance * 0.03;
}
}
else
{
bonus = balance * 0.02;
}
balance = bonus + balance;

Md. Roknuzzaman, Department of Civil Engineering Page 17


Hajee Mohammad Danesh Science and Technology University

The else if ladder:


The else if ladder statement is used to test a set of conditions in sequence. It is used to make long decision making
statements, involving a lot of options. else if ladder is used when a large number of conditions are employed in the
program. In case of long programs use of else if ladder instead of simple if statement makes the compilation
easier. When the data interval is not homogeneous, else if ladder is used instead of switch statement.
An if condition is tested only when all previous if conditions in else-if ladder is false. If any of the conditional
expression evaluates to true, then it will execute the corresponding statement block and exit whole if-else ladder
being transferred to statement-x.
General form:

Flow Chart:

Md. Roknuzzaman, Department of Civil Engineering Page 18


Hajee Mohammad Danesh Science and Technology University

Switch statement:
Switch statement is another important control statement. It is used to find the appropriate statement from various
alternative statements. In large programs, sometimes the use of else if statement is very lengthy, while the use of
switch is easier. switch statement works more rapidly reducing the time of compilation.
When the switch statement is executed, the value of the expression is successively compared against the case
values. If a case is found whose values matches with the value of expression, then be statement blocks followed
by that case are executed. The break statement at the end of each block indicates the end of a particular case and
causes an exit from the switch statement. Then the control is transferred to the statement-x.
The default is an optional case. If the value of expression does not match with any of the case values, the default
block statement is executed. This is how a switch statement is executed.

General form:
switch (expression)
{
case value_1 ;
block-1;
break;
case value_2;
block-2;
break;
------
------
case value_n;
block n;
break;
default:
default block ;
break;
}
statement-x;

Flow Chart:

Md. Roknuzzaman, Department of Civil Engineering Page 19


Hajee Mohammad Danesh Science and Technology University

Example:
/*A program of our grading system */

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

void main()
{
int mark, m;
char* S;
clrscr();
printf("Enter your marks : ");
scanf("%d", & mark);
m = mark / 5 ;
switch (m)
{
case 20:
case 19:
case 18:
case 17:
case 16:
S = "A+" ;
break ;
case 15 :
S = "A";
break;
case 14 :
S = "A-";
break;
case 13 :
S = "B+";
break;
case 12 :
S = "B";
break;
case 11 :
S = "B-";
break;
case 10 :
S = "C+";
break;
case 9 :
S = "C";
break;
case 8 :
S = "D";
break;
default:
S = "F";
break;
}
printf("Your grade is %S" S);
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 20


Hajee Mohammad Danesh Science and Technology University

The for Loop:


The for loop provides unexpected flexibility and power C coding.
The general form of the for statement is:

for (initialization; condition; increment) statement ;

The for loop allows many variations, but its most common form works like this:
➢ The initialization is an assignment statement that is used to set the loop control variable.
➢ The condition is a relational expression that determines when the loop exits.
➢ The increment defines how the loop control variable changes each time the loop is repeated.
The programmer must separate these three major sections by semicolons.
The for loop continues to execute as long as the condition is true. Once the condition becomes false, program
execution resumes on the statement following the for loop.
In the following program, a for loop is used to print the numbers 1 through 100 on the screen:

#include <stdio.h>

void main()
{
int x;
for(x=1; x <= 100; x++)
printf("%d ", x);
getch();
}

In this loop, x is initially set to 1 and then compared with 100. Since x is less than 100, printf( ) is called and the
loop repeats. This repetition causes x to be increased by 1 and again tested to see if it is still less than or equal to
100. If it is, printf( ) is called again. This process repeats until x is greater than 100, at which point the loop
terminates. In this example, x is the loop control variable, which is changed and checked each time the loop
repeats.

The while Loop:


The second important loop available in C is the while loop. It is an entry controlled loop statement and tests the
condition before execution. Thus the body of loop may not be executed at all. Its general form is

while(condition) statement;

Here statement is either an empty statement or a single statement or a block of statements. The condition may be
any expression, and true is any nonzero value. The loop repeats while the condition is true. When the condition
becomes false, program control passes to the line of code immediately following the loop.

Example:

#include <stdio.h>

void main()
{
int i = 10;

while ( i > 0 )
{
printf("Hello %d\n", i );
i = i -1;
}
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 21


Hajee Mohammad Danesh Science and Technology University

The do-while Loop:


Unlike for and while loops, which test the loop condition at the top of the loop, the do-while loop checks its
condition at the bottom of the loop. It is an exit controlled loop statement. This means that a do-while loop always
executes at least once. Perhaps the most common use of the do-while loop is in a menu selection function when
the user enters a valid response, it is returned as the value of the function. Invalid responses cause a re-prompt.
The general form of the do-while loop is

do
{
statement;
}
while(condition);

Example:

#include <stdio.h>

void main()
{
int i = 10;

do{
printf("Hello %d\n", i );
i = i -1;
}
while ( i > 0 );
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 22


Hajee Mohammad Danesh Science and Technology University

Array:
An array can be defined as a collection of variables of the same type that are referred to through a common name.
It is simply a collection of same type data. In its simplest form, it is used to represent a list of numbers, names etc.
The most common array is the string, which is simply an array of characters terminated by a null.

Types of Array:

Types General Form Example


Single type var_name[size]; double balance[100];
dimension (A 100 element double type variable; like
balance[1], balance[2]….etc.)
Two type var_name[size1][size2]; int d[10][20];
dimension (Matrix element with 10 rows and 20 columns,
like d[1][1], d[1][2]… etc.)
Multi type name[Size1][Size2][Size3] . . int m[4][3][6][5];
dimension .[SizeN];

Need of array variables:


We know that an array variable can contain a group of data i.e. it can contain more than one data. In such
programs, where a large number of same type data is to be compared the declaration of a large number of
variables is laborious. This can be eliminated using array variables.

Common example uses of array variables:


1) Testing scores of a class of students.
2) Listing temperatures recorded every hour.
3) Making table of daily rainfall data etc.

Advantages of using Array:


1) Use of array can eliminate the use of a lot of variables.
2) 2-d arrays can be used in programs to handle matrices.
3) Use of array is very useful in the programs, where it is needed to compare among a lot of data.
Diadvantages of using Array:
1) Different types of data cannot be handled with a single array.
2) The array size must be defined before declaring it. We cannot use data more than the pre-defined array
size.

Pointer:
Pointer is defined as a derived data type in C program which contains memory address as its value. As a pointer
contains memory addresses and the memory addresses indicates the location of data in computer’s memory, the
pointers are usually used to access and manipulate data in the computer’s memory.

Importance of pointer:
The correct understanding and use of pointers is crucial to successful C programming. There are several reasons
for this like:
➢ Pointers provide the means by which functions can modify their calling arguments.
➢ Pointers support dynamic allocation.
➢ Pointers can improve the efficiency of certain routines.
➢ Pointers provide support for dynamic data structures, such as binary trees and linked lists.
Pointers are one of the strongest but also one of the most dangerous features in C. For example, a pointer
containing an invalid value can cause your program to crash. Perhaps worse, it is easy to use pointers incorrectly,
causing bugs that are very difficult to find.

Initialization of pointer:
We know pointers contain the memory addresses of other variables. The process of assigning the memory address
of a variable to a pointer is called initialization of pointer. If a pointer is not initialized, it will contain random

Md. Roknuzzaman, Department of Civil Engineering Page 23


Hajee Mohammad Danesh Science and Technology University

memory address but the compiler will not show any error. As a result uninitialized pointer will result a wrong
output. Therefore, initialization is very important for pointers.
A pointer can be initialized in the general form,

data_type variable, *pointer_variable; /*Declaration*/


pointer_variable = &variable; /*Initialization*/

Here pointer is initialized using assignment operator in separate statement. A pointer can also be initialized in
combined form as

data_type *pointer_variable = & variable;

For example:
int R, *B;
B = &R;
or,
int *B = &R;

In this example R is a variable and B is a pointer. Here the memory address of R is stored in pointer B.

Program debugging:
Program debugging is the process of detecting and removing errors from source code of a C program. The output
of a program after compilation of each and every line can be viewed individually with program debugging. Also
the change in a variable in each line of program can be inspected by debugging it. The incorrect result can also be
backtracked by debugging. Doing so, errors can be eliminated using debugging.

Md. Roknuzzaman, Department of Civil Engineering Page 24


Hajee Mohammad Danesh Science and Technology University

Some common mistakes in coding:


1) int, shear [4][4], moment [4*4]; int shear[4][4], moment[4][4];
2) for (j=1, j >=10; j++); for (j=1; j <=10; j++)
3) Printf(“value is %f”,&VALUE); printf(“value is %f”,VALUE);
4) #define Y=2.5; #define Y 2.5
5) y = sqrt(100) y = sqrt(100);
6) scanf(“%c%d%f”,city,price,year); scanf(“%c%d%f”,&city, &price, &year);
7) float values[10,15]; float values[10][15];

Some example programs:


/*A program to find largest value from three Or, Alternately,
numbers of integer values.*/
#include <stdio.h>
#include <stdio.h> #include <conio.h>
#include <conio.h> void main()
{
void main() int a,b,c,A;
{ clrscr();
int a,b,c,A; printf("Enter the three values:");
clrscr(); scanf("%d%d%d",&a,&b,&c);
printf("Enter the three values:"); if(a>=b && a>=c)
scanf("%d%d%d",&a,&b,&c); A=a;
if(b>=a && b>=c)
if(a>b) A=b;
{ if(c>=a && c>=b)
if(a>c) A=c;
printf("%d",a); printf("Largest is %d",A);
else getch();
printf("%d",c); }
}
else /* A program to read four values a, b, c, d and
{ evaluate the ratio of a+b to c-d, and print the
if(c>b) result if c-d is not equal to zero. */
printf("%d",c);
else #include <stdio.h>
printf("%d",b); #include <conio.h>
}
void main()
{
float a, b, c, d, ratio;
clrscr();
printf("Enter a, b, c, and d :");
scanf("%f%%f%f%f", &a, &b, &c, &d);
ratio = (a+b)/(c-d);
if ((c-d)!=0)
{
printf("%f", ratio);
}
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 25


Hajee Mohammad Danesh Science and Technology University

/* 4 different quizes are given to a class of CIE 205 of 60 students. A program to calculate the average of the
best 3 quiz marks.*/

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

void main()
{
float a,b,c,d,A;
clrscr();
printf("Enter 4 Quiz marks separating by spaces:");
scanf("%f%f%f%f",&a, &b, &c, &d);
if(a<=b && a<=c && a<=d)
A=(b+c+d)/3;
if(b<=a && b<=c && b<=d)
A=(a+c+d)/3;
if(c<=a && c<=b && c<=d)
A=(a+b+d)/3;
if(d<=a && d<=b && d<=c)
A=(a+b+c)/3;
printf("The average mark is %f",A);
getch();
}

/* 4 different quizes are given to a class of CIE 205 of 60 students. A program to calculate the average of the
best 3 quiz marks for all the students at once.*/

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

void main()
{
int r;
float a,b,c,d,A;
clrscr();
for(r=1;r<=60;r++)
{
printf("Enter 4 Quiz marks of %d separating by spaces:",r);
scanf("%f%f%f%f",&a, &b, &c, &d);
if(a<=b && a<=c && a<=d)
A=(b+c+d)/3;
if(b<=a && b<=c && b<=d)
A=(a+c+d)/3;
if(c<=a && c<=b && c<=d)
A=(a+b+d)/3;
if(d<=a && d<=b && d<=c)
A=(a+b+c)/3;
printf("The average marks of student %d is %f \n",r,A);
}
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 26


Hajee Mohammad Danesh Science and Technology University
𝟏 𝟑 𝟓
/* A program to calculate + + + ……… upto 100 numbers. */
𝑳𝟏 𝑳𝟑 𝑳𝟓

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

void main()
{
double L, n, sum;
clrscr();
printf(“Enter the value of L:\n”);
scanf(“%lf”, &L);
for(n = 1; n<=100; n += 1)
{
sum = sum+(2*n – 1)/pow(L,(2*n – 1));
}
printf(“The sum is %lf”, sum);
getch();
}

𝟏 𝟏 𝟏 𝟏
/* A program to calculate + + + ………+ */
𝟐! 𝟒! 𝟔! 𝟑𝟎!

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

double FACT(double n)
{
if(n == 1)
returen 1;
else
return n*FACT(n-1);
}

void main ()
{
double r, sum;
clrscr();
sum = 0;
for(r = 2; r <= 30; r += 2)
{
sum = sum + (1/fact(r));
}
printf(“The summation is %lf”, sum);
getch (); }

Md. Roknuzzaman, Department of Civil Engineering Page 27


Hajee Mohammad Danesh Science and Technology University

/* A program for reading and printing a matrix of order 4x4. */

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

void main()
{
int i, j, C[4][4];
clrscr();
printf("Enter your 4x4 matrix row by row: \n");
for ( i = 1; i < = 4; i++)
{
for (j=1; j<=4; j++)
printf("Enter the value of element %d %d: \n",i,j);
scanf("%d", &C[i][j]);
}
printf (" \n you have entered : \n");
for ( i = 1; i < = 4; i++)
{
for (j=1; j<=4; j++)
{
printf("%d"\t, C[i][j]);
}
printf ("\n\n\n\n\n\n\n");
}
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 28


Hajee Mohammad Danesh Science and Technology University

/* A program for multiplication of two matrices of order 2x3 and 3x4 respectively. */

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

void main()
{
int A[2][3], B[3][4], C[2][4], i, j, k, sum;
clrscr();
printf(“Enter the first matrix (Matrix A) of order 2x3:\n”);
for(i=1; i<=2; i++)
{
for(j=1; j<=3; j++)
{
printf(“Enter the value A %d %d:\n”,i,j);
scanf(“%d”,&A[i][j]);
}
}
printf(“Now enter the 2nd matrix (Matrix B) of order 3x4:\n”);
for(i=1; i<=3; i++)
{
for(j=1; j<=4; j++)
{
printf(“Enter the value B %d %d:\n”,i,j);
scanf(“%d”,&B[i][j]);
}
}
for(i=1; i<=2; i++)
{
for(j=1; j<=4; j++)
{
sum=0;
for(k=1; k<=3; k++)
{
sum=sum+A[i][k]*B[k][j];
C[i][j]=sum;
}
}
}
printf(“The result matrix by multiplying A and B is:\n\n”);
for( i = 1; i < = 2; i++)
{
for (j=1; j<=4; j++)
{
printf("%d\t”, C[i][j]);
}
printf ("\n\n\n\n\n\n\n");
}
getch();
}

Md. Roknuzzaman, Department of Civil Engineering Page 29

You might also like