Professional Documents
Culture Documents
ENGINEERING
ACADEMIC UNIT-2
Bachelor of Engineering (Computer Science &
Engineering)
Computer Programming
UCT-145
B.E. Computer Science & Engineering Program Educational Objectives
(PEO)
PEO-I: Graduates will evolve as effective professionals by solving real life problems using
computer science knowledge along with focus on team work, effective communication,
divergent thinking and problem-solving skills.
PEO-II: Graduates with their agility would readily adapt to changing environments by having
learnt new and upcoming technologies.
PEO-III: Graduates will be drenched in an educational foundation that fosters leadership roles,
professional ethics, excellence and active participation needed for a successful career.
PEO-IV: Graduates will be aligned towards use of modern teaching learning pedagogies.
PEO-V: Graduates will be infused with ability & zeal to pursue Masters/Research programs and
involve in developing newfangled ideas.
Hardware
Computer hardware refers to the physical parts or components of a computer such as the
monitor, mouse, keyboard, computer data storage, hard drive disk (HDD), system unit (graphic
cards, sound cards, memory, motherboard and chips), etc. all of which are physical objects that
can be touched.
Software
Software is a generic term for organized collections of computer data and instructions, often
broken into two major categories: system software that provides the basic non-task-specific
functions of the computer, and application software which is used by users to accomplish
specific tasks.
Characteristics of Computer
Speed, accuracy, diligence, storage capability and versatility are some of the key characteristics
of a computer. A brief overview of these characteristics:
• Speed: The computer can process data very fast, at the rate of millions of instructions per
second. Some calculations that would have taken hours and days to complete otherwise, can be
completed in a few seconds using the computer. For example, calculation and generation of
salary slips of thousands of employees of an organization, weather forecasting that requires
analysis of a large amount of data related to temperature, pressure and humidity of various
places, etc.
• Accuracy: Computer provides a high degree of accuracy. For example, the computer can
accurately give the result of division of any two numbers up to 10 decimal places.
• Diligence: When used for a longer period of time, the computer does not get tired or fatigued.
It can perform long and complex calculations with the same speed and accuracy from the start till
the end.
• Storage Capability: Large volumes of data and information can be stored in the computer and
also retrieved whenever required. A limited amount of data can be stored, temporarily, in the
primary memory. Secondary storage devices like floppy disk and compact disk can store a large
amount of data permanently.
• Versatility: Computer is versatile in nature. It can perform different types of tasks with the
same ease. At one moment you can use the computer to prepare a letter document and in the
next moment you may play music or print a document.
Violation of privacy
Public Safety
Impact on Labor Force
Health Risks
Impact on Environment
INPUT OUTPUT
DEVICES MEMORY DEVICES
STORAGE
DEVICES
Input Unit: Hardware used to enter data and instructions. E.g. Mouse, Keyboard, Microphone,
Scanner, Webcam.
Output Unit: Hardware that conveys information in human understandable form. E.g. Monitor,
Printer, Speaker/Headphone.
Processor: Also called as Central Processing Unit (CPU). CPU is known as the brain of the
computer. The electronic component that interprets and carries out the basic instructions that
operate the computer. Two major brands are Intel and AMD. E.g. Intel Core 2 Duo, AMD Turion
X2.
Control Unit: The process of input, output, processing and storage is performed under
the supervision of a unit called ‘control unit’.
Arithmetic Logic Unit: The operations performed by ALU are addition, subtraction,
multiplication, division, logic and comparison.
Storage Unit: Two types as given below:
Primary Memory: Consists of electronic components that store instructions waiting to
be executed and data needed by those instructions. Two main types are as given below:
Random Access Memory (RAM): Allows you to temporarily store commands
and data.
Read Only Memory (ROM): Memory that retains its contents even after the
computer is turned off.
Secondary Storage: Holds data, instructions and information for future use. Storage is
non-volatile which means its contents are not lost when the power is switched off. E.g.
Hard disk, Flash drive, CD-ROM, DVD-ROM.
Communication device: Hardware component that enables a computer to send and receive data,
instructions and information.
FLOWCHARTS
Advantage:
- It helps programmers to understand the logic of complicated and lengthy
problems very easily.
- Proper documentation and efficient coding.
- Proper debugging and maintenance.
- Communication and effective analysis.
Limitations:
- Drawing flowchart is time-consuming activity.
- Sometimes it becomes complex and clumsy to draw a flowchart.
- Alterations require complete redrawing.
- No well-defined standards
Table 1: Symbols used while drawing flowcharts
Algorithms
It is the blueprint of the solution of the problem. It is the finite set of precise instructions for performing a
computation or solving a problem.
Algorithm
Step1: Input the numbers as a and b
Step2: find the product a x b
Step3: Print the result
Flowchart
Start
Read a and b
Compute a x b
Print a X b
Stop
In the above example execution is done one after another and straight forward.
Such straight forward problems occur very rarely.
Sometimes we have to depend on decision making at certain stage in a normal flow of
execution. This is done by testing a condition and appropriate path of flow is selected.
Algorithm
Step 1: read the numbers as x ,y and z
Step 2: compare x and y
Step 3: if x > y then compare x with z and find the greater
Step 4: Otherwise compare y with z and find the greater
Flowchart
What is Programming?
How to program?
A computer is not intelligent. It cannot analyze a problem and come up with a solution. A human
(the programmer) must analyze the problem, develop the instructions for solving the problem,
and then have the computer carry out the instructions. What’s the advantage of using a computer
if it cannot solve problems? Once the solution is written for the computer, the computer can
repeat the solution very quickly and consistently, again and again. The computer frees people
from repetitive and boring tasks.
• An undisciplined developer will not be able to ship on time and will not write code that is
easy to maintain.
• A disciplined developer will not only enable the success of a project, but will raise the
level of productivity in others.
Good Programs and Bad Programs
• If program produces what is required, and is correct in its output, then is this a ‘good’
program.
• Program executes successfully for n number of test cases.
Characteristics of good program include:
• Run-time efficient
• User Friendly
• Self Documenting code (uses meaningful names for identifiers)
• Portable
• Reusable
• Robust (can handle unexpected conditions)
Characteristics of bad program:
• Messy, unreadable code
• Bugs, bugs everywhere
• Not well tested
• No documentation / comments
• Not well organised
• No indentation
• No robustness
Features of C language
The C language has following features
a) Simple: C language is easy to understand.
b) Mid-level programming language: It is used for low level programming in order to build
system application such as kernel and drivers etc. and also it support functionality of high
level language. For example UNIX OS.
c) Inbuilt library: C has rich set of inbuilt library function to ease the development task stored
in the form of header files.
d) Machine Independent: C program work on any machine with little or no change e.g.
windows and Linux etc.
e) Structured Programming: Using C language, one can divide bigger problem into smaller
problem.
f) Pointer: With the help of C language, one can directly control any device or memory with
the help of pointer concept.
g) Memory management: C language support memory management using various dynamic
memory allocation function such as calloc(), malloc() and realloc().
h) Recursion: C support recursive function so that same function calls itself. The main motive
behind it is that bigger problem is divided into smaller problem of the same type.
i) Extensible: C language support extensibility means one can write our own functions and
define header files.
Documentation section/Comments:
1. The documentation section basically provide information regarding each section with some
comments.
2. These comments are helpful to programmer so that he/she can build the code according to
requirement of the comments.
3. The comments basically provide rough idea who to do something for particular section and
programmer write code on the basis of comments.
4. It provide various information like aim of the particular module, when it is created and what
is the scheduled update if required.
The comments are of two types:
1) Single line comments: The single line comments start with two forward slashes //.
Whenever // slashes involve at the start of the line, the particular line is skipped by the
compiler.
2) Multli-line comment: It is always enclosed between /*………….*/. Any number of line
in between /*………….*/ will be skipped by the complier as it is comment section.
//Write to program to check prime no-it is single line comment and skipped by compiler
/* Code: Prime.c
Programmer:xyz */
Datatypes
Datatype: It basically determine what the type of value the data has and how much memory is
required to hold that data. Data type provide logical representation of the memory for particular
data and what kind of operation we can perform on the data.
There are four type of data types:
a) Fundamental datatype ( integer, floating point and void)
b) Derived datatype (array and function)
c) User defined data type(Union, Struct, Enum and typedef)
b) Explicit Type casting: When conversion is done by the programmer itself explicitly
Syntax: (datatype) expression.
For e.g:- printf(“%d”,(int)2.5), the answer will be 2.
Associativity: If two or more operator has same precedence then it is executed accordance to
associativity which is either left to right or right to left.
For example * and / have same precedence in same operator so it must be solved from left to
right. So in this expression c=7*4/2, it will be solved as c=(7*4)/2 so answer is 14.
Computer Programming
Topics to be covered:
Simple statements,
Decision making statements,
Looping statements,
Nesting of control structures,
break, continue and goto statement.
1. Introduction
In C programming the statement is the smallest standalone elementthat is written to instruct our
computer do some particular task.
An instruction or a statement is a part of code written in high level language that commands a
computer to perform some action.
The execution of statements starts from the first line of main() function.
All the lines written inside the main function are executed one by one sequentially.
The statements are of following types:
1. Simple statements
2. Control Statements
a. Decision making statements
b. Looping statements
c. Jumping statements
1.1 Simple C Statements
A C programming Statement is an instruction that perform a single task.
In C programing all statementsends with a semi-colon ‘;’.
This semicolon acts as a statement terminator or delimiter to identify the statements /
instructions of the C program.
Consider the Code below:
int a , b, c, sum;
sum = a+b;
These statements when compiled and executed are instructing a computer to add two numbers, stored in
variable ‘a’ and ‘b’, and store its value in a variable ‘sum’.
Declare four memory locations named ‘a’‘b’‘c’ and ‘sum’ whose data-type is integer.
It may be observed from the above example that the both statements are terminated by the delimiter ‘;’ to
tell compiler that it is the end of this instruction.
Every program is collection of instructions which together perform a desired task. So when these
instructions are combined they solve a real world problem.
It is required to find the sum of two numbers.
So all the statements which are instructing a computer to perform a task for us is call a simple C
statement.
It can be a declaration, an assignment, an initialization of variable or even printing a message on the
Screen using a function call of printf()
For example:
int a; This is a declaration statement
a = 10; This statement assigns the value 10 to variable / memory location named a
printf(“Hi this is a new message!!”);
Above Statement will print the Message Quoted inside the parenthesis (), on the screen
Onething is to be observed:
The following C Code is written in a single line and is a Complete C program!
#include<stdio.h> int main() { printf(“Hello this whole code is written in one line”); return 0;}
if (condition(s))
statement;
if (condition(s))
{
statement1;
statement2;
statement3;
…
} Figure 1 Simple IF Statement
The body of the “if” statement is executed only if the expression in parentheses at the top evaluates to true
(which in C means any value that is not 0).
The braces are not strictly required, and are used only to group one or more statements into a single
statement. If there is only one statement in the body, the braces can be omitted:
This style is recommended only for very simple bodies. Omitting the braces makes it harder to add more
statements later without errors.
if (dadEntersRoom)
{
/* Woah! */
MinimizeAllWindows();
StareAtDesktop();
}
An if statement may have an else clause, whose body is executed if the test is false (i.e. equal to 0)
if(condition)
{
statement1; /*if block*/
statement2;
statement3;
…
}
else
{
statement1; /*else*/
statement2;
statement3;
… Figure 2 If Else Statement
}
A common idiom is to have a chain of “if” and “else
if” branches that test several conditions:
if(temperature < 0)
{ puts("brrr");}
else if(temperature < 100)
{ puts("hooray");}
else { puts("ouch!"); }
/* print plural of cow, maybe using the obsolete dual number construction */
switch(numberOfCows)
{
case 1:
puts("cow");
break;
case 2:
puts("cowen");
break;
default:
puts("cows");
break;
}
1.3 Loops :
A portion of program that is executed repeatedly is called a loop.
The C programming language contains three different program statements for program looping. They are:
whileloop
forloop
do-while loop
The break statement immediately exits the innermmost enclosing loop or switch statement.
for(i = 0; i < n; i++) {
openDoorNumber(i);
if(TigerInRoom()) {
break;
}
}
The continue statement skips to the next iteration. Here is a program with a loop that iterates through all
the integers from -10 through 10, skipping 0:
#include <stdio.h>
/* print a table of inverses */
#define MAXN (10)
int main()
{
int n;
return 0;
}
OUTPUT
1.0/-10 = -0.100000
1.0/ -9 = -0.111111
1.0/ -8 = -0.125000
1.0/ -7 = -0.142857
1.0/ -6 = -0.166667
1.0/ -5 = -0.200000
1.0/ -4 = -0.250000
1.0/ -3 = -0.333333
1.0/ -2 = -0.500000
1.0/ -1 = -1.000000
1.0/ 1 = +1.000000
1.0/ 2 = +0.500000
1.0/ 3 = +0.333333
1.0/ 4 = +0.250000
1.0/ 5 = +0.200000
1.0/ 6 = +0.166667
1.0/ 7 = +0.142857
1.0/ 8 = +0.125000
1.0/ 9 = +0.111111
1.0/ 10 = +0.100000
Occasionally, one would like to break out of more than one nested loop. The way to do this is with a goto
statement.
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
doSomethingTimeConsumingWith(i, j);
if(checkWatch() == OUT_OF_TIME) {
goto giveUp;
}
}
}
giveUp:
puts("done");
The target for the goto is a label, which is just an identifier followed by a colon and a statement (the
empty statement ; is ok).
The goto statement can be used to jump anywhere within the same function body, but breaking out of
nested loops is widely considered to be its only genuinely acceptable use in normal code.
ARRAY
Array is a Homogenous group of logically related values stored under one variable having
identical data type that share common name and stored in contiguous memory locations. Eg.
int abc[20] can be represented as:
Fig 1: Declaration of int array variable Fig 2: Actual Memoy representation of One Dimensional array
Array elements may be of simple data type like int, float, char etc. or user defined data type
like structure, union etc.
Every array element can be accessed with the help of array name followed by unique index
which specify position of particular element in array.
TYPES OF ARRAYS
One-Dimensional Array:
Array having just one index is called one-dimensional. Eg. int A[5] = {1,2,3,4,5};. Here
A[0]=1 is first element also called base address of array A. and A[4]=5 is last element.
1-D array can be represented as single row or column.
When we are declaring an array it does not automatically do initialization of array element it
just produced continuous memory locations to array with each element having garbage value.
Valid and invalid 1D array declaration are:
int A[5] = {1,2,3,4,5}; //Valid Statement
int A[10] = {1,2,3}; //Valid Statement
int A[2] = {1,2,3,4,5}; //In-Valid Statement
int A[6] = {, 1,2,3,4,5}; //In-Valid Statement
Multi-Dimensional Array:
Most popular Multi- Dimensional Array used is Two-Dimensional Array.
Array can have more than one dimensions. Array having two dimensions called two-
dimensional array.
Multi-dimensional array represented of data is logical representation of data.
Most popular 2-D representation of data is tabular representation of data i.e. in rows and
column as shown in fig 3(a).
Declaration of two dimensional arrays is similar as that of one-dimensional array just a little
difference, I’ll show you shortly. Eg. int A[2][5] = {{1,2,3,4,5}, {5,4,3,2,1}};
One thing to keep in mind this is that 2-D data is also stored in continuous memory
locationas shown in figure 3(b).
Fig 3(a): Logical representation of 3x3 2D Fig 3(a): Physical representation of 4x2 2D Array
Array
Valid and invalid 1D array declaration are:
int A[2][2] = {1,2,3,4}; //Valid Statement
int A[][2] = {1,2,3,4}; //Valid Statement
int A[2][] = {1,2,3,4}; //In-Valid Statement
int A[][] = {1,2,3,4}; //In-Valid Statement
Pointers
Basics of Pointers
A Pointer is nothing but a variable that contains an address which is a location of another
variable in memory.
If one variable contains the address of another variable, the first variable is said to point to
the second variable.
#include<stdio.h>
int main()
{
int a=2;
int *i,**j;
i=&a;
j=&i;
printf("Value at pointer= %d\n",*i);
printf("Value at pointer to pointer= %d",**j);
printf("Value at pointer to pointer= %d",*j);
printf("Value at pointer to pointer= %d",&i);
return 0;
}
Output:
3. Pointer to Array
When an array is declared, compiler allocates sufficient amount of memory to contain all
the elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the
five elements will be stored as follows:
Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000. In short, arr has
two purpose - it is the name of an array and it acts as a pointer pointing towards the first
element in the array.arr is equal to &arr[0] //by default. Above example and Fig 6. Output
of program showing pointer & array and pointer to array
4. Array of Pointers
There may be a situation when we want to maintain an array, which can store pointers to
an int or char or any other data type available. Following is the declaration of an array of
pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a
pointer to an int value.
Example:
#include<stdio.h>
void main( ){
int *arr[4] ; /* array of integer pointers */
int i = 31, j = 5, k = 19, l = 71, m ;
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ ) {
printf ( "%d ", * ( arr[m] ) ) ;
}
}
Output:
int main(){
int *ptr;
int i;
ptr = fn_input();
printf("\nArray Elements are:\n");
for (i = 0; i< 5; i++)
printf("%d\t", *(ptr + i));
return 0;
}
Output:
Introduction
Regularly we face circumstances in programming where the information is dynamic in nature.
That is, the number of data items continues changing during execution of the program. Such
circumstances can be dealt with all the more effortlessly and effectively by utilizing what is
known as dynamic data structures in conjunction with dynamic management techniques.
MALLOC( )
It is used to allocate space in memory during the execution of the program.
It doesn’t initialize the memory allocated during execution. It carries garbage value.
It returns null pointer if it couldn’t able to able to allocate requested amount of memory.
The following syntax is used for malloc :
ptr = (cast-type *) malloc(byte-size);
Example:
or
if (ptr == NULL)
exit(-1);
else
CALLOC( )
It is used to allocate space in memory at run time for storing derived data types.
It allocates multiple blocks of storage.
It initializes the allocated memory to zero.
The following syntax is used for calloc:
n is number of blocks.
Example:
else
printf(“Memory allocated successfully.\n”);
REALLOC( )
It modifies the allocated memory size by previous discussed functions to new size.
If enough space doesn't exist in memory of current block to extend, new block is allotted
for the full size of reallocation, and copies the information to new block and after that
liberates the old block.
The reallocation can be done like:
ptr= realloc (ptr, newsize);
FREE( )
It releases the memory space when there is no longer need of data stored in it.
Also it frees the allocated memory created by malloc or calloc.
Use function like:
free (ptr);
ptr is a pointer to a memory block.