You are on page 1of 37

UNIVERSITY INSTITUTE OF

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.

B.E. Computer Science & Engineering Program Outcome (PO)

A Graduate of Computer Science and Engineering Program will demonstrate:


1. An ability to apply knowledge of science, mathematical foundations, algorithmic principles,
and computer science and engineering theorems in the modeling and design of computer-
based systems to real-world problems (fundamental engineering analysis skills).
2. An ability to design, analyze and perform experiments leading towards proficient
interpretation of results. (Information retrieval skills).
3. An ability to develop a computer-based system, process, component, or program to meet the
desired needs, within realistic constraints such as economic, environmental, social, political,
health and safety, manufacturability, and sustainability (creative skills).
4. An ability to participate effectively in multi-disciplinary teams (teamwork).
5. An ability to come forward with lateral & efficient solutions for computing & engineering
based problems (engineering problem solving).
6. An ability to challenge and solve professional, interpersonal, ethical, security & social issues
along with ability to perform responsibilities & duties (professional integrity, speaking /
writing skills, social awareness).
7. An educational ideology to assess the local & global impact of computing and engineering
solutions on individuals, organizations and society (engineering impact assessment skills,
continuing education awareness).
8. Honed skill set comprising of evolutionary tools and techniques applicable in computing &
engineering practice (practical engineering analysis skills).
9. Ability to harness design and development principles in the construction of verifying
complex hardware and software systems (Software hardware interface).
10. The knowledge by recognizing professional development by pursuing post graduate studies
or face competitive examinations that offer challenging and rewarding careers in
computing (successful career and immediate employment).
11. The ability to work in Professional environment and to communicate effectively with peers
(Communications skills).
12. To Recognize, Understand the real world problems and to deploy and execute engineering
solutions for sustainable eco system (Implementation and Deployment skills).

B.E. Computer Science & Engineering Program Specific Outcome (PSO)

A Graduate of Computer Science and Engineering Program will demonstrate:


1. To develop the good programming knowledge and analytical skills in students required to
be and to remain productive in the field of CSE as well as in diverse environments to
excel in higher education or to succeed in industry/technical profession.
2. To design and develop solutions for industry/society problems through their coding,
database and networking skills.
3. To learn the learning skills in order to adopt the ever changing advance technology in the
field of computer science and engineering.
Table of Contents
 Introduction to Computer and programming
 Fundamentals of C
 Decision Control structure in C
 Loop Control structure in C
 Array & String
 Functions
 Pointers
 Structure
 Dynamic memory allocation
Introduction to Computer and programming
Computer
A computer is an electronic machine that operates under the control of instructions stored in its
own memory which can accept data as input, process the data according to specified rules,
produce information as output. The computer has also the capability to store the information for
future use.

A computer consists of HARDWARE AND SOFTWARE.

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.

Limitations of using computer

 Violation of privacy
 Public Safety
 Impact on Labor Force
 Health Risks
 Impact on Environment

CENTRAL PROCESSING UNIT


CONTROL ARITHMETIC
UNIT LOGIC UNIT

INPUT OUTPUT
DEVICES MEMORY DEVICES

STORAGE
DEVICES

Fig: Block Diagram of Computer

Functions of various Components of Computer

 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

 A flowchart is a formalized graphical/ pictorial representation of a logic sequence, work


or manufacturing process, organization chart, or similar formalized structure.
 The purpose of a flow chart is to provide people with a common language or reference
point when dealing with a project or process. Flowcharts use simple geometric symbols
and arrows to define relationships.

 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

Symbol Name Symbol Description

Start or End Denotes the beginning or end of the program

Processing Denotes a process to be carried out

Input/Output Denotes an input/output operation

Conditional/Decision Denotes a decision to be made

Labeled Connectors Denotes connections in complex or multi-sheet flowchart


diagrams

Flow Line Denotes the direction of logic flow in the program

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 exhibits three key features that can be given as:


- Sequence
- Decision
- Repetition
 Properties of Algorithm:
- Correct
- Unambiguous
- Precise
- Efficient
- Finiteness
 Developing the Algorithm:
- Identify the inputs.
- Identify the processes.
- Identify the outputs.
- Identify modules.
Consider a problem of multiplying two numbers

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.

For example consider the following problem:

To find the highest of three numbers

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?

 Programming is the planning or scheduling the performance of a task or an event.


 Computer Programming is the process of specifying the data types and the operations for
a computer to apply to data in order to solve a problem.
 Programming Language provides a set of rules, symbols, and special words used to
construct a computer program.
 Computer program is the data type specifications and instructions for carrying out
operations that are used by a computer to solve a problem.

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.

Machines and Knowledge about problem solving

• Problem is defined as an obstacle which makes it difficult to achieve a desired goal,


objective or purpose.
• Problem Solving is the core of computer science
• Programmers must first understand
o how a human solves a problem,
o then understand how to translate this "algorithm" into something a computer can do,
o and finally how to "write" the specific syntax (required by a computer) to get the
job done.
• Machine language is a set of instructions executed directly by a computer's central
processing unit (CPU).
• Each instruction performs a very specific task, such as a load, a jump, or
an ALU operation on a unit of data in a CPU register or memory.
• Every program directly executed by a CPU is made up of a series of such instructions.

Steps involved in Program development

1. Analyze the problem


2. Identify the variables involved
3. Design the solution
4. Write the program
5. Enter it into a computer
6. Compile the program and correct errors
7. Correct the logical errors if any
8. Test the program with data
9. Document the program

Importance of Discipline in Programming

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

General structure of C program


The general structure of C program involves following sections:
a) Documentation section
b) Preprocessor directive section
c) Global variable declaration section
d) User defined function prototype declaration section
e) Main( ) section
f) Body of main function
g) User defined function definition section

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 */

Preprocessor directive section:


It is always start with #symbol. There are two preprocessor directive
a) #include
b) #define
Header files: Header files are files which are available in include folder. With the help of #
include we can add the content of header file from current folder into source code to make it as
extended source code. Header files basically involve definition of all those function which are
frequently used like printf() and scnaf() etc.
Examples of header files are stdio, conio, string, math, stdlib etc.
#define is used to assign fix value to name
For e.g. #define PI 3.14

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)

Constants and Variables


Constants: The entity which does not change its value during execution. There are different type
of constant like integer constant (5, -78), real constant (3.14, 2.23), character constant- single
character in single quotes (‘a’, ‘A’) and string constant-single or multiple character in double
quotes (“amit”,”ram”).
Variable: Variable are the storage space which is used to store value of a particular type. The
variable is identify using some name. Identifier must be used for any kind of datatype but we
have to follow some convention while writing identifiers. Some valid identifier are average, list_
and invalid identifier are 12in, $econd, third no.
Expression and Operators
An Expression is combination of variables, constants and operators that yield to give new value.
Operators: These are the symbols which instruct the programmer to perform certain operation
like arithmetic, relational or logical. There are various kind of operators which are as:
Binary operation: In this kind of operation, operation is performed on two operands using one
operator.
Unary operation: In this kind of operation, operation is performed on one operand using one
operator.
There are various kinds of operators which are as:
Binary operators
a) Arithmetic Operators (+,-,*, /, %)
b) Assignment Operators (Simple assignment =, compound assignment +=, - = etc.)
c) Relational Operators (>, <,>=, <=, ==, ! =)
d) Logical Operators(&&,| |)
e) Bitwise Operators( &, ~, | ,^)
Unary Operators
a) Increment and decrement (post a++, a--,pre ++a,--a)
Ternary operator
a) Conditional operator (? :)

Type Conversion in expression


In expression to be evaluated there may be variable of different types to solve such kind of
expression we need type casting. There are two type of type casting which is as follows
a) Implicit Type casting: When conversion is done automatically by the compiler, it is called
implicit type casting. In this data of lower type is automatically converted to higher type
during execution.
For e.g. float c;
In given statement, c=5.0/2, the answer will be 2.5 because 5.0 is higher type available in
expression, so it is accordingly.

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.

Precedence and Associativity?


In given expression, there may be multiple operators so in order to execute we have to follow
some order and direction from where to execute.
Precedence: The operators which are having higher priority as compared to other operator must
be executed first.
For example * operator has higher precedence as compared to +.
So in this expression c=5*3+2, answer will be 17 not 25,

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

Now how compiler will recognize the different parts of program?


By checking and following the syntax!
So the first like is started with a # which is a pre-processor directive and will include the stdio.h file in our
program code. Next int main() {} will be parsed (reading code character by character to understand its
meaning is called parsing) so the curly brackets tell compiler that main function starts from here and ends
where the brackets ends. Every Statement written inside is set of instructions to be executed. And these
are SEPARATED by semi colon ‘ ; ’ allowing compiler to identify where the statement ends.

1.2 Control statements


The Control statements are the special statements provided to us by c language that allows us to control
the order of the execution of the statements.
All the statements written inside the main() function are executed one by one sequentially in the order in
which they are written.
By there are some scenarios where it is required by program to either skip a particular part of code, or
repeat a line of code again and again to solve our problem.
Consider a C program that asks a user to enter his age and check if the age entered is greater than and
equal to 18 computer should show the message “the person is eligible to vote”.
But if the age of user is less than 18 then it should print “you are not eligible to vote” so in this situation
our program should work differently under different condition.
To make this happen decision control statementsare used.
There are actually three types of control statements offered to us by C.
1. Branching / decision control statements
2. Looping / Repetition or iterative statements
3. Jumping break statements.

1.2 Decision control statements:


The decision control statements as mentioned in the above example are statements that allow conditional
execution of statements of the program.
They are
1. If
2. If-else
3. Nested if-else /Nested if
4. If – else ladder
5. Switch-case
The if statement if used to control the flow of execution of statements considering the conditions.
These are compound statements that test some condition and execute one or another block depending on
the outcome of the condition. The simplest is the “if” statement:
SYNTAX :

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

This can be inefficient if there are a lot of cases, since


the tests are applied sequentially. For tests of the
form <expression> == <small constant>,
the switch statement may provide a faster alternative.
Here's a typical switch statement:

Figure 3 IF else Ladder

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

This prints the string "cow" if there is one cow, "cowen" if


there are two cowen, and "cows" if there are any other number
of cows. The switch statement evaluates its argument and
jumps to the matching case label, or to the default label if none of the cases match. Cases must be constant
integer values.

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 while loop


Figure 4 Switch Case
A while loop tests if a condition is true, and if so, executes its
body. It then tests the condition is true again, and keeps
executing the body as long as it is.

The while loop is best suited to repeat a statement or a set of


statements as long as some condition is satisfied.

The general form of while loop is


initial expression;
while(conditional-expression)
{
statement;
increment/decrement;
}
The general form of for loop is
Figure 5 For Loop
for(initialization; condition;
increment/decrement)
{
statement;
}
Figure 6. Structure of For Loop

where the statement is single or compound statement.


The for loop is a form of SyntacticSugar that is used when a loop iterates over a sequence of
values stored in some variable (or variables). Its argument consists of three expressions: the first
initializes the variable and is called once when the statement is first reached. The second is the
test to see if the body of the loop should be executed; it has the same function as the test in a
while loop. The third sets the variable to its next value.
Do while loop
• The structure of do-while loop is similar to while loop.
• Figure 7 Nested LOOPS
• The difference is that in case of do-while loop the
expression is evaluated after the body of loop is
executed.
• In case of while loop the expression is evaluated before
executing body of loop.
• The general form of do-while statement is
do
{
statements;
} while(expression);
Figure 8 Flow Chart of do-While loop
Figure 9 while loop written as Do-while loop

A for loop can always be rewritten as a while loop.

for(i = 0; i < 10; i++) {


printf("%d\n", i);
}
/* is exactly the same as */
i = 0;
while(i < 10) {
printf("%d\n", i);
i++;
}
 C language provides us multiple statements through which the the control can be transferred
anywhere in the program.
 Jump statements cause an unconditional jump to another statement elsewhere in the code.
 They are used primarily to interrupt switch statements and loops.
 There are basically 3 Jumping statements:
1. Break
2. continue
3. goto

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;

for(n = -MAXN; n <= MAXN; n++) {


if(n == 0) continue;
printf("1.0/%3d = %+f\n", n, 1.0/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.

Fig 1: Representation of normal variable & pointer variable


 A pointer provides an indirect method of accessing the value of data item.
 If pointer variable is not pointing to any variable, then it is called NULL pointer.
 Two operators are used for representing a pointer variable (i.e. * and &).
 * Operator is used to access the value of variable to which pointer variable is
pointing.
 & Operator is used to represent the address of variable to which pointer variable is
pointing.
 Or pointer is always initialized to NULL. i.e. int *p=NULL.
 Value of pointer variable is always whole number i.e. Address.
 Pointer can be declared as.
int*p /*Pointer to an integer variable*/
double*p /*Pointer to a doublevariable */
char*p /*Pointer to a character variable*/
float*p /*pointer to a float variable*/
Benefits of pointer:
 Pointers are used in situations when passing actual values is difficult or not desired in
functions.
 To return more than one value from a function.
 They increase the execution speed.
 The pointer are more efficient in handling the data types .
 Pointers reduce the length and complexity of a program.
 The use of a pointer array to character string results in saving of data.
 To allocate memory and access it( Dynamic memory Allocation).
 Implementing linked lists, trees graphs and many other data structure.

Operations with pointers:


 Incrementing and decrementing a pointer variable. eg.
int *p, a[5]; // A integer type pointer p& array a declared.
a[]={4,2,5,7,6}; //Arrayaassigned values.
p=a; //Address of 1st element of arrayais assigned to pointerp.
p++; //pointerppoints to 2nd value i.e. 2.
*p++ // pointerppoints to 3rd value i.e. 5.
 Adding or subtracting an integer to pointer variable. eg.
*p = *p+3; // valve 3 will be added to pointerpat 4thlocation i.e. 7+3 = 10.
*p =*p-2; // valve 2 will be subtracted to pointerpat 4thlocation i.e. 10-2 = 8.
 Two pointers can be compared with each other using comparison operator.
while(p++ != a[4]) // Condition will check the address of p with array a[5] address
printf(“%d\n”, *p); // Value of p will be printed
1. Pointer to Pointer
Declaring Pointer to Pointer is similar to declaring pointer in C. The difference is we
have to place an additional ‘*’ before the name of pointer.
Fig 3. Example of pointer to array (pr = array) and pointer to pointer (pr=&ppr)

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

Fig 4. Output of program showing pointer to pointer

2. Pointer and array


Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable takes different addresses as value whereas, in
case of array it is fixed.
In C programming, name of the array always points to address of the first element of an
array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
#include<stdio.h>
void main()
{
int a[5]={1,2,3,4,5};
int i;
int *p;
p=a;
for(i=0;i<5;i++)
{
printf("The value is : %d \n",*p);
printf("%d\n",a[i]);
printf("%d\n",i[a]);
printf("%d\n",a+i);
printf("%d\n",*(a+i));
printf("%d\n",*a);
p++;
}
}
Output:
Fig 5. Output of program showing pointer & array and pointer to array

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:

Fig 6. Output of program showing pointer to array

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:

Fig 7. Output of program showing array of pointers

5. Function returning a Pointer


C allows us to return a pointer from a function. To do so, you have to declare a function
like this:
int * myfunction( )
{
------------;
------------;
}
Example:
#include <stdio.h>
int* fn_input(){
static int a[5];
int i;
for (i = 0; i< 5; i++) {
printf("Enter the value for array a[%d]:", i);
scanf("%d", &a[i]);
}
return a;
}

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:

Fig 8. Output of program showing function returning pointers


Dynamic Memory Allocation

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.

Dynamic Memory Allocation


 The process of allocating memory at run time is known as dynamic memory allocation.
 It is unique feature of C Programming Language as this allows us to create data types and
structures of any size and length which suits our program.
 There are four library routines known as “memory management functions” that can be
utilized for allocating and freeing memory during program execution.
 The functions are shown in table 1.

Table 1: Memory Allocation Functions


Function Task
Malloc Allocates a block of memory and returns a pointer to the first byte of the
allocated space.
Calloc Allocates multiple blocks of storage.
Realloc Modifies the memory size that is already allocated
Free Releases storage space previously allocated.

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

ptr is pointer of type cast.

Example:

ptr = (int *) malloc (sizeof (int) );

or

int *ptr = (int *) malloc(sizeof (int));

if (ptr == NULL)

printf(“Could not allocate memory \n”);

exit(-1);

else

printf(“Memory allocated successfully.\n”);

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:

ptr = (cast-type *) calloc (n, byte-size);

n is number of blocks.

Example:

ptr = (int *) calloc(10, sizeof (int) );


or
int *ptr = (int *) calloc(10, sizeof (int));
if (ptr == NULL)
{
printf(“Could not allocate memory \n”);
exit(-1);
}

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.

You might also like