CIE 205 Notes
CIE 205 Notes
Programming in C
(Introductory theory)
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.
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.
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.
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.
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.
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.
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.
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 𝐺𝑖𝑔𝑎 𝑏𝑦𝑡𝑒
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
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
Library Function:
The pre-defined functions which are included with the compiler are called library functions.
Ex: clrscr() ; getch() etc.
#include <stdio.h>
int addNumbers(int a, int b); // UDF prototype
void main()
{
int n1,n2,sum;
printf("sum = %d",sum);
getch();
}
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
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
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:
Character Data Stores the Single Character 1 byte -128 to 127 (or a single character)
char
Type Value
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.
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
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)
Character constant:
A character contains a single character enclosed within a pair of single quotation marks.
Ex : ‘A’, ‘b’ etc.
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
Backslash Backslash
character Meaning character Meaning
\b Backspace \\ Backslash
\’ Single quote
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)
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;
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.
Special Operator:
C allows some special operators such as comma operator, sizeof operator, pointer operator etc. They are used for
special purposes.
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 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.
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);
General form:
if(test expression)
{
True block statement;
}
else
{
False block statement;
}
Statement-x
Flowchart:
Example:
if(code = = 1)
{
boy = boy + 1;
}
else
{
girl = girl + 1;
}
printf(“%f and %f”, boy, girl);
General form:
if(test expression1)
{
if(test expression2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
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;
Flow Chart:
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:
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();
}
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.
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();
}
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();
}
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:
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
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,
Here pointer is initialized using assignment operator in separate statement. A pointer can also be initialized in
combined form as
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.
/* 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();
}
#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 (); }
#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();
}
/* 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();
}