0% found this document useful (0 votes)
69 views151 pages

PSCP Material

This document provides an introduction to computers for engineering students. It discusses computer systems and components including hardware and software. It describes different computing environments such as personal, time-sharing, client-server and distributed computing. It also discusses different types of computer languages from machine language to high-level languages like C. An example C program is provided to print "Hello to CSE!". The goal is to teach students basic concepts about computers as per the JNTUA R13 CSE syllabus.

Uploaded by

S Sri
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)
69 views151 pages

PSCP Material

This document provides an introduction to computers for engineering students. It discusses computer systems and components including hardware and software. It describes different computing environments such as personal, time-sharing, client-server and distributed computing. It also discusses different types of computer languages from machine language to high-level languages like C. An example C program is provided to print "Hello to CSE!". The goal is to teach students basic concepts about computers as per the JNTUA R13 CSE syllabus.

Uploaded by

S Sri
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/ 151

Specially Prepared for Engineering Students

As per
R13 CSE
Syllabus

By
H. Ateeq Ahmed, M.Tech.,
Assistant Professor of CSE,
Kurnool.

As per JNTUA R13 CSE Syllabus


ACKNOWLEDGEMENT

First I thank Almighty God for giving me the knowledge to learn and teach
various students.

It’s my privilege to thanks my parents as without their right guidance and


support, this book will be a dream for me.

Finally, I thank my colleagues and friends for helping me during tough


period of time.

“Interest & Focus are two KEYWORDS of a perfect programmer”

“The goal of this book is to find the next C Programmer in YOU in

a magical way…”

H. Ateeq Ahmed, M.Tech.,

Mobile no: 9948378994,

E-mail ID: [email protected].


Syllabus & Contents

Topics Page No.


UNIT-I
Introduction to Computers:
Computer Systems, Computing Environment, Computer Languages,
Creating and Running Programs, System Developments.
Introduction to the C Language: Introduction, C programs,
Identifiers, Types, Variables, Constants, Input and Output,
1 - 21
Programming Examples.
Introduction to Computer Problem Solving: Introduction , The
Problem-Solving Aspect, Top-down Design, Bottom – up Approach,
Flowcharts, Implementation of Algorithms, Program Verification, The
Efficiency of Algorithms, The Analysis of
Algorithms.
UNIT-II
Structure of C program: Expressions, Precedence and Associatively,
Evaluating Expressions, Type Conversion, Statements, Sample
Programs.
Selections and Making Decisions: Logical Data and Operators, Two
way Selection, Multiway Selection.
Repetition: Concept of Loop, Pretest and Posttest Loops,
22 - 52
Initialization and Updation, Event and Counter Controller Loop,
Loops in C, Looping Applications.
Fundamental Algorithms: Exchanging the values between two
variables, Counting, Summation of a set numbers, Factorial
Computation, Sine Function Computation, Generation of the
Fibonacci Sequence, Reversing the digits of a integer, Basic
conversions, Character to Number Conversion
UNIT-III
Factoring Methods: Finding Square root of a Number, The Smallest
Deviser of an Integer, The GCD of two Integers, Generating Prime
Numbers, Computing Prime Factor of an Integer, Computing the
prime factors of an Integer, Generation of Pseudo Random Number,
Raising the number to Large Power, Computing the nth Fibonacci.
Functions: Introduction, User Defined Functions, Inter Function
Communication, Standard Functions, Scope, Programming Examples. 53 – 99
Array Techniques: Array Order Reversal, Array Counting, Finding
the Maximum Number Set, Removal Duplicates from an Ordered
Array, Partitioning an Array, Finding kth smallest Element, Longest
Monotone Subsequence.
Arrays: Introduction, Two Dimensional Arrays, Multi Dimensional
Arrays, Inter Function Communication, Array Applications, Exchange
Sort, Binary Search, Linear Search.
UNIT-IV
Strings: String Concepts, C Strings, Sting Input/Output Functions,
Arrays of Strings, String Manipulation Functions, String/Data
Conversion.
100 – 123
Enumerated, Structure, and Union Types: The Type Definition,
Enumerated Types, Structure, Unions, Programming Applications.
Bitwise Operators: Exact Size Integer Types, Logical Bitwise
Operators, Shift Operators, Mask.
UNIT-V
Pointers: Introduction, Pointers for Inter Function Communication,
Pointers to Pointers, Compatibility, Lvalue and Rvalue.
Pointer Applications: Array and Pointers, Pointer Arithmetic and
124 – 147
Arrays, Passing an Array to a Function, Memory Allocation
Functions, Array of Pointers, Programming Applications.
Binary Input/output: Text Versus Binary Streams, Standard Library
Functions for Files, Converting File Type.
Linked List: Single Linked List, Insertion and Deletion
Department of CSE 1

UNIT- I
INTRODUCTION TO COMPUTERS
Computer Systems
Today computer systems are found everywhere.
Computers have become almost as common as televisions.
But what is a computer?

Definition:
“A computer is an electronic machine which converts raw data into meaningful information.”
“A computer is an electronic machine which accepts the input, processes the input and
produces the output.”

A computer is a system made of two major components: hardware and software.

Hardware components of a computer

Software

“Software is a collection of programs that allows a user to work on a computer.”

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 2

Types of software

Relationship between system and application software

Computing Environments
 Computing Environment is a collection of computers / machines, software, and
networks that support the processing and exchange of electronic information meant to
support various types of computing solutions.
 In the early days of computers, there was only one environment, the mainframe
computer hidden in a central computing department.
 With the advent of minicomputers and personal computers, the environment changed
with computers on virtually every desktop.
In this section we describe several different environments.
 Personal Computing Environment
 Time-Sharing Environment
 Client/Server Environment
 Distributed Computing

Let us now discuss each of them briefly.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 3

(a) Personal Computing Environment


A personal computing environment seems to be an environment for your computing that
intends to make computing more comfortable for the person by placing many conveniences
such as a desk, cup holder and other things.

(b) Time-Sharing Environment

In computing, time-sharing is the sharing of a computing resource among many users by


means of multiprogramming and multi-tasking.

By allowing a large number of users to interact concurrently with a single computer, time-
sharing dramatically lowered the cost of providing computing capability, made it possible for
individuals and organizations to use a computer without owning one, and promoted the
interactive use of computers and the development of new interactive applications.

(c) Client/Server Environment

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 4

Relating to a computer system in which a central server supports a number of networked


workstations

(d) Distributed Computing


Distributed computing is a field of computer science that studies distributed systems.
A distributed system is a software system in which components located on networked
computers communicate and coordinate their actions by passing messages.
The components interact with each other in order to achieve a common goal.

Computer Languages
To write a program for a computer, we must use a computer language.
Over the years computer languages have evolved from machine language to natural
languages.

 Machine Languages
 Symbolic Languages
 High-Level Languages
(i) Machine Languages
The only language understood by computer hardware is machine language.
Example

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 5

(ii) Symbolic Languages


Symbolic language uses symbols, or mnemonics, to represent the various machine language
instructions.
Example

(iii) High Level Languages


A programming language such as C, FORTRAN, or Pascal that enables a programmer to
write programs that are more or less independent of a particular type of computer. Such
languages are considered high-level because they are closer to human languages and further
from machine languages. In contrast, assembly languages are considered low-level because
they are very close to machine languages.

The main advantage of high-level languages over low-level languages is that they are easier
to read, write, and maintain. Ultimately, programs written in a high-level language must be
translated into machine language by a compiler or interpreter.

The first high-level programming languages were designed in the 1950s.


Now there are dozens of different languages, including Ada, Algol, BASIC, COBOL, C,
C++, FORTRAN, LISP, Pascal, and Prolog.

Example C program
#include<stdio.h>
#include<conio.h>

void main()
{
printf(“Hello to CSE!”);
getch();
}

Expected Output
Hello to CSE!

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 6

Creating and Running Programs


In this section, we explain the procedure for turning a program written in C into machine
language.

The process is presented in a straight forward, linear fashion, but you should recognize that
these steps are repeated many times during development to correct errors and make
improvements to the code.

System Development
In this section, we discuss how we go about developing a program. This critical process
determines the overall quality and success of our program. If we carefully design each
program using good structured development techniques, our programs will be efficient, error-
free, and easy to maintain.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 7

INTRODUCTION TO THE C LANGUAGE


 C is a structured programming language.
 It was developed by M. Dennis Ritchie in 1972 at Bell Laboratories.
 It is considered a high-level language because it allows the programmer to concentrate
on the problem at hand and not worry about the machine that the program will be
using.
 While many languages claim to be machine independent, C is one of the closest to
achieving that goal.
 That is another reason why it is used by software developers whose applications have
to run on many different hardware platforms.

C Programs
It's time to write your first C program! This section will take you through all the basic parts of
a C program so that you will be able to write it.

Structure of a C program

Our First C Program

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

void main()
{
clrscr(); // clears any previous output
printf(“Hello World!”); // displays the message on the output device - monitor
getch();
}

Expected Output

Hello World!

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 8

Identifiers
 One feature present in all computer languages is the identifier.
 Identifiers allow us to name data and other objects in the program.
 Each identified object in the computer is stored at a unique address.
 If we didn‟t have identifiers that we could use to symbolically represent data
locations, we would have to know and use object‟s addresses.
 Instead, we simply give data identifiers and let the compiler keep track of where they
are physically located.
Example
int x;
x is known as identifier.
Rules for Identifiers
 An identifier must start with a letter or underscore: it may not have a space or a
hyphen.
 An identifier must not be a keyword.
 It can consist of letters, digits or underscore.
 Identifier names are case sensitive.
 The maximum length of identifier must be less than or equal to 31 characters.

Valid & Invalid Names of Identifiers

Data types
A data type is used to indicate the type of value stored in a variable.
A data type indicates the following
 Type of value stored in a variable
 Memory allocated for data value
 Type of operations that can be performed on the variable.
Data types are classified in to the following categories.
1. Integer data types
2. Floating point data types
3. Characters
1. Integer data types
It is used to store whole numbers.
The size of the integer depends on the word length of a machine i.e. it can be either 16 or 32
bits.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 9

Signed Integers:
Signed integers are those integers which uses 15 bits for storing the magnitude of a number
and 1 bit for storing its sign.
The left most bit i.e. 16th bit is used for storing the sign.
1-> Negative number
0-> Positive number
Example:
signed int x=10;
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
Magnitude
Sign
0-> Positive number
Unsigned Integers
Unsigned integers uses all 16 bits to store the magnitude.
Data type Size (bytes) Range
int 2 or 4 -32768 to 32767 or
-21474836648 to 21474836648
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -21474836648 to 21474836648
unsigned long int 4 0 to 4294967295
signed long int 4 -21474836648 to 21474836648

2. Floating point data types:


These are used to store real numbers i.e. decimal point numbers or numbers with fractional
values.
Data type Size (bytes) Range
float 4 -3.4e-38 to 3.4e+38
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e-4932 to 1.1e+4932

3. Character data type:


This data type is used to store characters.
Each character has an equivalent ASCII value.
The format specifier used with character data type is %c.

Data type Size (bytes) Range


char or signed char 1 -128 to 127
unsigned char 1 0 to 255

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 10

Variables
“A variable is the name given to memory location to store data value in it.”
Unlike constant, the value of a variable can be changed.
A variable name must be chosen in such a way that it improves the readability of a program.
Syntax
Data_type var_name=var_value;

Example
int x=10;
The above variable „x‟ contains value 10 and it is of integer data type.

Constants
Constants are data values that cannot be changed during the execution of a program.
Like variables, constants have a type.
In this section, we discuss Boolean, character, integer, real, complex, and string constants.

Character constants
A character constant is enclosed in single quotes.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 11

Integer constants

Real constants

Complex constants

The two components of a complex constant must be of the same precision, that is, if the real
part is type double, then the imaginary part must also be type double.

Input and Output


Input/Output functions are classified into the following two types.
(1) Formatted I/O functions
(2) Unformatted I/O functions.
Let us now discuss each of them briefly.

(1) Formatted I/O functions


The following are the two types of formatted I/O functions
(a) printf()
(b) scanf()
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 12

(a) printf()
This function is used to print result on the monitor.

Syntax
printf(“control string”,arg1,arg2,….,argn);
Examples
printf(“%d”,a);
printf(“%d%c”,num,ch);

( b) scanf()
This function is used to read values for variables from keyboard.

Syntax
scanf(“control string”,address_list);
where control string specifies the type of values that have to read from the keyboard.
Examples
scanf(“%d”,&a);
scanf(“%d%f”,&a,&b);
scanf(“%d%f%c”,&a,&b,&c);

2. Unformatted I/O functions


The following are the various types of unformatted I/O functions.
(a) getchar()
This function returns a single character entered from keyboard.
Syntax
var=getchar();

(b) putchar()
This function displays a single character on an output device.
Syntax
puts(var);

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 13

(c) gets()
This function is used to read an input string.
Syntax
gets(var);

(d) puts()
This function is used to display a string on the monitor.
Syntax
puts(var);

Programming Examples
1. Write a C program to calculate the area of circle.
/*To display area of a circle*/

#include<stdio.h>
#define PI 3.1416
void main()
{
float r,area;
clrscr();
printf("Enter the radius:");
scanf("%f",&r);
area=PI*r*r;
printf("\nArea of circle=%f",area);
getch();
}

Expected Output
Enter the radius:5
Area of circle=78.540001

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 14

INTRODUCTION TO COMPUTER PROBLEM SOLVING

Introduction

Programs and Algorithms

Requirements for Solving Problems by Computer

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 15

The Problem Solving Aspect

1. Problem definition phase

the problem definition phase.

2. Similarities among problems

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 16

General Problem Solving Strategies

Top-down Design

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 17

Breaking a problem into sub problems

Construction of Loops

The following are the three steps in the construction of loops.

(1) Establishing the initial conditions


(2) Finding the iterative construct
(3) Termination of loops.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 18

Flowcharts
A Flowchart is a diagrammatic representation of an Algorithm.
 It is built using different types of boxes and symbols.
 The operation to be performed is written in the box.
 All symbols are interconnected by arrows to indicate the flow of information and
processing.
The following are the standard symbols used in drawing flowcharts.

Example

Draw a Flowchart to determine whether the number is even or odd.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 19

Implementation of Algorithms

Use of procedures to emphasize modularity

Choice of variable names

Documentation of programs

Debugging Programs

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 20

Program Verification

The following steps are used in order to perform program verification.

 Computer model for program execution


 Input and Output assertions
 Implications and Symbolic executions
 Verification of straight line program segments
 Verification of program segments with branches
 Verification of program segments with loops
 Verification of program segments that employ arrays
 Proof of termination

The Efficiency of Algorithms

The following points must be considered

 Redundant computations
 Referencing array elements
 Inefficiency due to late termination
 Early detection of desired output conditions

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 21

The Analysis of Algorithms

*******

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 22
UNIT-II
STRUCTURE OF A C PROGRAM
Expressions
An expression consist of a single entity such as constant, a variable or a combination of such
entities joined together using one or more operators.

Example
c=a+b*d;
The above expression states the following
 It consists of four operands namely a,b,c,d
 It also consists of three operators =,+,*
 The result of the expression is assigned to a variable c.

Types of Expressions
 Postfix
 Prefix
 Unary
 Binary
 Ternary

Postfix

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 23
Prefix

If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated.
If ++ is before the operand, as in ++a, the increment takes place before the expression is
evaluated.

Unary

Binary

Precedence and Associativity


 Precedence is used to determine the order in which different operators in a complex
expression are evaluated.
 Associativity is used to determine the order in which operators with the same precedence
are evaluated in a complex expression.
 Each operator in ‗C‘ has a precedence associated with it.
 This precedence is used to determine how each expression containing more than one
operator is evaluated.
 The operator at the higher level of precedence is evaluated first and the operators of the
same precedence are evaluated either from left to right or from right to left depending up
on the level.
The following are the two distinct levels of Arithmetic operators.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 24
(i) High priority arithmetic operators are *,/,% and
(ii) Low priority arithmetic operators are +, -

Example-1
x=a-b/3+c*2-1

Now let a=9, b=12, c=3 then

x=9-12/3+3*2-1
The above expression is evaluated as follows.
x=9-4+3*2-1
x=9-4+6-1
x=15-4-1
x=15-5
x=10

If parenthesis is used then expression within the parenthesis is evaluated first.


Example-2
x=9-12/6*(2-1)
x=9-12/6*1
x=9-2*1
x=9-2
x=7
 When an expression contains two operators of equal priority then the tie between them is
settled using the assoociativity of operators.
 Associativity are of two types
Left to Right
Right to Left
 Left to Right associativity means that the left operand must not be involved in any other
sub expression.
 Similarly, Right to Left associativity means that the right operand should not involved in
any sub expressions.

Evaluating Expressions
When an expression consists of different types of variables, compiler follows rules of type
conversions.

RULE:
If the operands are of different types, the lower type is automatically converted to higher type
and the result will be of higher type.
The result of expression is then converted to the type of variable present at the left hand side pf
the assignment operator.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 25
Example
int i;
float f;
double d;

int j=i*d+f/i;
int j=double type+float type
int j=double type.
Finally, the result is converted to integer type as j is an integer variable.

Type Conversion
Type conversion is classified in to two types.
(i) Implicit Type Conversion
(ii) Explicit Type Conversion (Casting)

(i) Implicit type conversion


―It is a process of converting data type of smaller size into higher size‖.
It is done automatically by the compiler.
Rules of Implicit Type Conversion:
(i) The two types must be compatible
(ii) The destination type must be larger than the source type.
Example
long int i;
int c=10;
i=c;
This process is also called as widening.

(ii) Explicit type conversion (Casting)


―It is a process of converting data type of larger size into smaller size‖.
In this process some value may get truncated.
Syntax
(type-cast)operand;
Example
int a=3,b=4;
float res;
res= (float)a/b;

Statements
 A statement causes an action to be performed by the program.
 It translates directly into one or more executable computer instructions.
 You may have noticed that we have used a semicolon at the end of the statements in our
programs.
 Most statements need a semicolon at the end; some do not.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 26
The Role of the Semicolon (;)
Every declaration in C is terminated by using semicolon.
Most statements in C are terminated by using semicolon.

Return Statement
A return statement terminates a function.
Example
return expression;
Compound statement

The compound statement does not need a semicolon.

Sample Programs
1. Write a C program to display quotient and remainder.
//To display quotient and remainder
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2;
float quot,rem;
clrscr();
printf("Enter two numbers:");
scanf("%d%d",&n1,&n2);

quot=(float)n1/n2; // (float) indicates casting


printf("\nQuotient=%f",quot);

rem=n1%n2;
printf("\nRemainder=%f",rem);
getch();
}

Expected Output
Enter two numbers:25
4
Quotient=6.250000
Remainder=1.000000

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 27
SELECTIONS AND MAKING DECISIONS

Logical Data
A piece of data is called logical if it conveys the idea of true or false.
In real life, logical data (true or false) are created in answer to a question that needs a yes–no
answer.
In computer science, we do not use yes or no, we use true or false.

Logical operators truth table

Comparative operator complements

Operators
Operators are C tokens which can join together individual constants, variables, array elements
etc.

C operators are classified into the following categories.

 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and Decrement operators
 Conditional operators
 Bitwise operators
 Special operators

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 28
Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division

Relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Assignment operators
It is used to assign the result of an expression to a variable.
It is denoted as ‗=‘.

Increment and Decrement operators


Operator Meaning
a++ Post increment
++a Pre increment
a-- Post decremment
--a Pre decrement
Conditional operator
It is also known as ternary operator.
Syntax
exp1?exp2:exp3;
The value of exp1 is evaluated first, If it is true, value of exp2 is evaluated otherwise exp3 is
evaluated.
Bitwise operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR(XOR)
~ One‘s Complement
<< Shift left
>> Shift right

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 29
Special operators
(i) Comma operator(,)
It is used to separate the variables
Eg:
int a,b,c;

(ii) sizeof operator


It return the no. of bytes the operand occupies.
Eg: sizeof(operand)

Two way selection


The decision is described to the computer as a conditional statement that can be answered either
true or false.
If the answer is true, one or more action statements are executed. If the answer is false, then a
different action or set of actions is executed.

The following are the two way selection statements


(i) Simple if
(ii) if else
(iii) Nested if

(i) Simple if
Syntax
if(condition)
statement1;

(ii) if else
Syntax
if(condition)
statement1;
else
statement2;

If the condition is TRUE then statement1 is executed otherwise statement2 is will be executed.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 30
Example Program
#include<stdio.h>
#include<conio.h>

void main()
{
int age;
clrscr();
printf(―Enter the age:‖);
scanf(―%d‖,&age);
if(age>=18)
printf(―\nEligible for Voting.‖);
else
printf(―\nNot eligible.‖);
getch();
}

(iii) Nested if statement


Syntax
if(condition-1)
{
if(condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}

If the condition in the outer if statement is TRUE then control will enter into inner if statement
otherwise else part will be executed.

Multiway Selection
In addition to two-way selection, most programming languages provide another selection
concept known as multiway selection.
Multiway selection chooses among several alternatives.
C has two different ways to implement multiway selection: the switch statement and else-if
construct.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 31

The following are the two types of Multiway selction statements


(i) else if ladder
(ii) Switch
(i) else if ladder
Syntax

if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
.
.
.
else
statement-n;

(ii) switch
A switch statement is used to select from more than one choice in program.
Syntax
switch(expression)
{
case value1:
statement-1;
break;

case value-2;
statement-2;
break;
.
.
.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 32

default:
statement-n;
}

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

void main()
{
int num;
clrscr();
printf("Enter day no:");
scanf("%d",&num);

switch(num)
{
case 0:
printf("\nZERO");
break;

case 1:
printf("\nONE");
break;

case 2:
printf("\nTWO");
break;

default:
printf("\nInvalid Number.");
}
getch();
}

REPETITION
Concept of a Loop
The real power of computers is in their ability to repeat an operation or a series of operations
many times.
This repetition, called looping, is one of the basic structured programming concepts.
Each loop must have an expression that determines if the loop is done.
If it is not done, the loop repeats one more time; if it is done, the loop terminates.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 33

Pretest and Post-test Loops


We need to test for the end of a loop, but where should we check it—before or after each
iteration?
We can have either a pre-or a post-test terminating condition.
(a) Pretest Loop
 In a pretest loop , the condition is checked at the beginning of each iteration.
 In each iteration, the control expression is tested first. If it is true, the loop continues;
otherwise, the loop is terminated.

(b) Post-test Loop


 In a post-test loop, the condition is checked at the end of each iteration.
 In each iteration, the loop action(s) are executed. Then the control expression is tested. If
it is true, a new iteration is started; otherwise, the loop terminates.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 34
Comparison

Initialization and Updation


In addition to the loop control expression, two other processes, initialization and updating, are
associated with almost all loops.

Event and Counter Controller Loops


All the possible expressions that can be used in a loop limit test can be summarized into two
general categories:
(i) Event-controlled loops
(ii) Counter-controlled loops.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 35
(i) Event-controlled loops

(ii) Counter-controlled loops

Loops in C
C has three loop statements: the while, the for, and the do…while.
The first two are pretest loops, and the third is a post-test loop.
We can use all of them for event-controlled and counter-controlled loops.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 36
(i) The while loop

Syntax
while(condition)
{
statements;
}

(ii) The for loop

Syntax
for(initialization;condition;iteration)
{
statements;
}

A for loop is used when a loop is to be executed a known number of times.


We can do the same thing with a while loop, but the for loop is easier to read and more natural
for counting loops.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 37
Comparing for and while loops

(iii) The do while loop


A do while loop executes the body atleast once even though the condition is false.

Syntax
do
{
statements;
}
while(condition);

Comparing while and do while loops

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 38
Looping Applications
Program-1 using while loop
void main()
{
int i=1;
clrscr();
while(i<=5)
{
printf(―\n%d‖,i);
i++;
}
getch();
}

Program-2 using for loop


void main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
printf(―\n%d‖,i);
}
getch();
}

Program-3 using do while loop


void main()
{
int i=1;
clrscr();
do
{
printf(―\n%d‖,i);
i++;
} while(i<=5);
getch();
}

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 39
FUNDAMENTAL ALGORITHMS

Exchanging the values of two variables

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 40

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 41

Counting

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 42

Thus

Finally

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 43
Summation of a set of Numbers

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 44

Factorial Computation

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 45

Sine Function Computation

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 46

Generation of the Fibonacci sequence

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 47

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 48
Reversing the digits of an Integer

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 49

Base Conversion

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 50

We have

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 51

Character to Number conversion

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 52

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 53
UNIT-III
FACTORING METHODS

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 54

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 55

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 56

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 57

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 58

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 59

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 60

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 61

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 62

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 63

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 64

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 65

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 66

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 67

Array Techniques

Introduction

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 68

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 69

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 70

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 71

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 72

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 73

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 74

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 75

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 76

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 77

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 78

FUNCTIONS
In C, the idea of top–down design is done using functions. A C program is made of one
or more functions, one and only one of which must be named main.
The execution of the program always starts with main, but it can call other functions to
do some part of the job.

Definition:
“A function is a self-contained block of statements that perform some specific task for the
program.”

Functions are used to provide modularity to the software. By using functions, you can divide
complex tasks into small manageable tasks. The use of functions can also help avoid duplication
of work. For example, if you have written the function for calculating the square root, you can
use that function in multiple programs

Functions are classified into two categories.


(1) Built in functions or Standard library functions
(2) User defined functions.

Standard Library Functions


 C provides a rich collection of standard functions whose definitions have been written
and are ready to be used in our programs.
 As the name suggests, library functions are nothing but commonly required functions
grouped together and stored in a Library.
 This library of functions is present on the disk and is written for us by people who write
compilers for us.
 Almost always a compiler comes with a library of standard functions.
Examples:
printf(), scanf() etc.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 79
1. stdio.h: I/O functions:
1. getchar() returns the next character typed on the keyboard.
2. putchar() outputs a single character to the screen.
3. printf() as previously described
4. scanf() as previously described

2. string.h: String functions


1. strcat() concatenates a copy of str2 to str1
2. strcmp() compares two strings
3. strcpy() copys contents of str2 to str1

3. ctype.h: Character functions


1. isdigit() returns non-0 if arg is digit 0 to 9
2. isalpha() returns non-0 if arg is a letter of the alphabet
3. isalnum() returns non-0 if arg is a letter or digit
4. islower() returns non-0 if arg is lowercase letter
5. isupper() returns non-0 if arg is uppercase letter

4. math.h: Mathematics functions


1. acos() returns arc cosine of arg
2. asin() returns arc sine of arg
3. atan() returns arc tangent of arg
4. cos() returns cosine of arg
5. exp() returns natural logarithim e
6. fabs() returns absolute value of num
7. sqrt() returns square root of num

5. time.h: Time and Date functions


1. time() returns current calender time of system
2. difftime() returns difference in secs between two times
3. clock() returns number of system clock cycles since program execution

6. stdlib.h:Miscellaneous functions
1. malloc() provides dynamic memory allocation, covered in future sections
2. rand() as already described previously
3. srand() used to set the starting point for rand()

Example Program
Write a C progam to display the square root of a number.
#include<stdio.h>
#include<conio.h>
#include<math.h>

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 80
void main()
{
float n,res;
clrscr();
printf("Enter the number:");
scanf("%f",&n);
res=sqrt(n);
printf("\nSquare root=%f",res);
getch();
}

Expected Output
Enter the number:25
Square root=5.000000

User Defined Functions


 User defined functions are those functions that are used by the user according to the
requirement of the program.
 Like every other object in C, functions must be both declared and defined.
 The function declaration gives the whole picture of the function that needs to be defined
later. The function definition contains the code for a function.
 A function name is used three times: for declaration, in a call, and for definition.

Syntax:
return-type function-name(parameter-list)
{
local variables;
statements;
}

Advantages of functions

 A function provides modularity and readability to the software.


 To define the function, you have to define the function name, the return data type and the
formal parameters.
 It is recommended to declare a function prototype before using a function.
 If the function does not return any value, then you have to set the return data type as void.
 A call to a function should be compatible with the function definition.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 81
Example Program
//Using userdefined function

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

void message(); // function prototype or function declaration

void message() // function definition


{
printf("\nI am fine!");
}

void main()
{
clrscr();
printf("\nHow r u?");
message(); // calling message()
getch();
}

Expected Output:
How r u?
I am fine!

Explanation
 Here, main( ) itself is a function and through it we are calling the function message( ).
 What do we mean when we say that main( ) „calls‟ the function message( )?
 We mean that the control passes to the function message( ).
 The activity of main( ) is temporarily suspended; it falls asleep while the message( )
function wakes up and goes to work.
 When the message( ) function completes the execution of statements, the control returns
to main( ), which comes to life again and begins executing its code at the exact point
where it left off.
 Thus, main( ) becomes the „calling‟ function, whereas message( ) becomes the „called‟
function.

Types of Functions:
Depending up on the arguments and return values, functions
are classified in to the following four types.
(a) Functions with no arguments and no return values
(b) Functions with arguments and no return values
(c) Function with no arguments and return values
(d) Function with arguments and return values.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 82
(a) Functions with no arguments and no return values
#include<stdio.h>
#include<conio.h>

void sum(); //function prototype

void sum() // function definition


{
int a,b,c;
a=10;
b=20;
c=a+b;
printf("\nSum=%d",c);
}

void main()
{
clrscr();
sum();
getch();
}

(b) Functions with arguments and no return values


void sum(int a,int b); //function prototype

void sum(int a,int b) // function definition


{
int res;
res=a+b;
printf("\nSum=%d",res);
}

void main()
{
int a,b;
clrscr();
a=10;
b=20;
sum(a,b);
getch();
}

(c) Function with no arguments and return values


int sum(); //function prototype

int sum() // function definition


{
int a,b,c;
a=10;
b=20;
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 83
c=a+b;
return(c);
}

void main()
{
int res;
clrscr();
res=sum();
printf("\nSum=%d",res);
getch();
}

(d) Function with arguments and return values


int sum(int a,int b); //function prototype

int sum(int a,int b) // function definition


{
int c;
c=a+b;
return(c);
}

void main()
{
int x,y,res;
clrscr();
x=10;
y=15;
res=sum(x,y);
printf("\nSum=%d",res);
getch();
}

Formal and Actual Parameters


 Formal parameters are variables that are declared in the header of the function definition.
 Actual parameters are the expressions in the calling statement.
 Formal and actual parameters must match exactly in type, order, and number.
 Their names, however, do not need to match.

Inter Function Communication


There are two ways in which we can pass the parameters to
the function.
(1) Call by value
(2) Call by reference

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 84
Let us discuss each of them briefly.
(a) Call by value:
“The technique of passing the value of the variable as parameter to the
function is known as “Call by value”.
By now we are well familiar with how to call functions. But, if you observe carefully, whenever
we called a function and passed something to it we have always passed the „values‟ of variables
to the called function. Such function calls are called „calls by value‟. By this what we mean is, on
calling a function we are passing values of variables to it.

Example Program:
//call by value

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

void swap(int x,int y);

void swap(int x,int y) //x & y are formal parameters


{
int z;
z=x;
x=y;
y=z;
printf("\nSwapped values are %d %d",x,y);
}

void main()
{
int a=10,b=20;
clrscr();
printf("\nValues before swap are %d %d",a,b);

swap(a,b); //a & b are actual parameters

printf("\nValues after swap are %d %d",a,b);


getch();
}

Expected Output
Values before swap are 10 20
Swapped values are 20 10
Values after swap are 10 20

(2) Call by reference:


The technique of passing the address of the variable as a parameter to the
function is known as a “Call by reference”.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 85
We have also learnt that variables are stored somewhere in memory. So instead of passing the value
of a variable, we pass its location (also called address) of the variable to a function. Hence this
technique is Call by reference.

Example Program:
//call by reference
#include<stdio.h>
#include<conio.h>

void swap(int *x,int *y);


void swap(int *x,int *y) //x & y are formal parameters
{
int *z;
*z=*x;
*x=*y;
*y=*z;
printf("\nSwapped values are %d %d",*x,*y);
}
void main()
{
int a=10,b=20;
clrscr();
printf("\nValues before swap are %d %d",a,b);
swap(&a,&b); //a & b are actual parameters
printf("\nValues after swap are %d %d",a,b);
getch();
}
Expected Output
Values before swap are 10 20
Swapped values are 20 10
Values after swap are 20 10

Scope
“Scope is defined as the area of the program in which the variable is visible or accessible.”
 Scope determines the region of the program in which a defined object is visible.
 Any object defined in the global area of a program is visible from its definition until the
end of the program.
 Variables defined within a block have local scope.

Consider the following function which contains the local


variable „i‟ as follows.
void fun()
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 86
{
int i=10; // „i‟ is a local variable
printf(“i=%d”,i);
}

Arrays
“An array is collection of similar elements that are stored in sequential memory locations.”
An ordinary variable can hold only one value at a time where as an array can store multiple
values of same type.

Example
Consider an array named “scores” that contains 9 elements from index 0 to 8.

Consider the following program

main( )
{
int x ;
x=5;
x = 10 ;
printf ( "\nx = %d", x ) ;
}

No doubt, this program will print the value of x as 10. Why so? Because when a value 10 is
assigned to x, the earlier value of x, i.e. 5, is lost. Thus, ordinary variables (the ones which we
have used so far) are capable of holding only one value at a time (as in the above example).
However, there are situations in which we would want to store more than one value at a time in a
single variable.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 87
Syntax

Array Declaration

Data-type array-name[Size];

Examples

int a[5];
a

a[0] a[1] a[2] a[3] a[4]

65516 65518 65520 65522 65524

 Here, int specifies the type of the variable, just as it does with ordinary variables and „a‟
specifies the name of the variable.
 The [5] however is new. The number 5 tells how many elements of the type int will be in
our array. This number is often called the „dimension‟ of the array.
 The bracket ( [ ] ) tells the compiler that we are dealing with an array.
 a[0] refers to the first element in the array whereas the whole number 65516 is its address
in memory.

Array Initialization
 So far we have used arrays that did not have any values in them to begin with.
 We managed to store values in them during program execution.
 Let us now see how to initialize an array while declaring it.

Example

int a[5] ={ 2, 4, 6,10, 12 };


or
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 88
int a[]={ 2, 4, 6,10, 12 };
a
a[0] a[1] a[2] a[3] a[4]
2 4 6 8 10
65516 65518 65520 65522 65524

Array elements are referred to using subscript; the lowest subscript is always 0 and the highest
subscript is (size –1). If you refer to an array element by using an out-of-range subscript, you
will get an error. You can refer to any element as a[0], a[1], a[2], etc

Thus, an array is a collection of similar elements. These similar elements could be all ints, or all
floats, or all chars, etc. Usually, the array of characters is called a „string‟, whereas an array of
ints or floats is called simply an array. Remember that all elements of any given array must be
of the same type. i.e. we cannot have an array of 10 numbers, of which 5 are ints and 5 are
floats.

More Array Initialization Methods

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

void main()
{
int a[5]={2,4,6,8,10};
clrscr();
printf("\nFirst element=%d",a[0]);
printf("\nFifth element=%d",a[4]);
getch();
}

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 89
Expected Output
First element=2
Fifth element=10

Using for loop for Sequential Access


As array elements are stored in adjacent memory locations, we can use for loop to store as well
to access them sequentially.

Example Program
//To store and display elements of the array using for loop
#include<stdio.h>
#include<conio.h>

void main()
{
int a[3],i;
clrscr();
printf("\nEnter the elements in the array:");
for(i=0;i<3;i++)
scanf("%d",&a[i]);
printf("\nArray elements are");
for(i=0;i<3;i++)
printf("\n%d",a[i]);
getch();
}

Expected output
Enter the elements in the array:
1
2
3

Array elements are


1
2
3

Using Array Elements as arguments to a function


 Array elements can be passed to a function by calling the function by value, or by
reference.
 In the call by value we pass values of array elements to the function, whereas in the call
by reference we pass addresses of array elements to the function.

(a) Passing a single element of the array to a function


//Program to pass an Array element as argument

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

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 90

void fun(int x);

void main()
{
int a[3],i;
clrscr();
printf("\nEnter any three numbers:");
for(i=0;i<3;i++)
{
scanf("%d",&a[i]);
}
fun(a[0]); // passing a single element of an array
getch();
}

void fun(int x)
{
printf("\nElement=%d",x);
}

Expected Output
Enter any three numbers:
10
20
30
Element=10

(b) Passing all elements of the array to a function


//Program to pass all elements of the array

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

void fun(int x);

void main()
{
int a[3],i;
clrscr();
printf("\nEnter any three numbers:");
for(i=0;i<3;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<3;i++)
fun(a[i]); // passing all elements of the array to a function
getch();
}
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 91

void fun(int x) // formal parameter x is an ordinary variable


{
printf("\n%d",x);
}

Expected Output
Enter any three numbers:
10
20
30

10
20
30

(c) Passing an entire array as argument to the function

//Program to pass an entire array as argument

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

void fun(int b[]);

void main()
{
int a[3],i;
clrscr();
printf("\nEnter any three numbers:");
for(i=0;i<3;i++)
scanf("%d",&a[i]);

fun(a); // passing array „a‟ to the function “fun()”

getch();
}

void fun(int b[]) // formal parameter b[] is an array variable


{
int i;
for(i=0;i<3;i++)
printf("\n%d",b[i]);
}

Expected Output
Enter any three numbers:
10
20
30
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 92

10
20
30

Multidimensional Arrays
Arrays with two or more dimensions are often referred as “Multidimensional arrays.”

Two dimensional arrays:


Two dimensional arrays are often expressed and analyzed as
matrix of rows and columns.

Declaration & Initialization:


Syntax:
Data-type array-name[row-size][column-size]={ {row1 elements},{row2 elements},…};

Number of elements in array= (row-size * column size)

Example
int a[3][2]={{2,4}, {6,8}, {10,12}};

Column Index

Row Index

First element of the array is referred as a[0][0]


Sixth element is referred as a[2][1].

Total number of elements in the above array is 6 i.e. (3*2=6).


The array arrangement shown in matrix form is only conceptually true.
This is because memory doesn‟t contain rows and columns.
In memory whether it is a one-dimensional or a two-dimensional array the array elements are
stored in one continuous chain.
The arrangement of array elements of a two-dimensional array in memory is shown below:

Memory Representation:

a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[0][1]


2 4 6 8 10 12
65516 65518 65520 65522 65524 65526

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 93
Example Program
#include<stdio.h>
#include<conio.h>

void main()
{
int a[3][2]={{2,4},{6,8},{10,12}},i,j;
clrscr();
printf("The array elements are");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n%d",a[i][j]);
}
}
getch();
}

Expected Output:
The array elements are
2
4
6
8
10
12

Array Applications
In this section we study two array applications: frequency arrays with their graphical
representations and random number permutations.

Frequency Array

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 94
Frequency Histogram

Histogram Program Design

Exchange Sort
 Bubble sort or Exchange sort, sometimes incorrectly referred to as sinking sort, is a
simple sorting algorithm that works by repeatedly stepping through the list to be sorted,
comparing each pair of adjacent items and swapping them if they are in the wrong order.
 In this method, the first element is compared with the second element, second is
compared with the third and so on.
 The pass through the list is repeated until no swaps are needed, which indicates that the
list is sorted.
 The algorithm gets its name from the way larger elements "bubble" to the top of the list.

Example

Consider the following list of numbers in an array

2 6 4 8 5

Iteration-1
2 6 4 8 5

2 6 4 8 5

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 95
2 4 6 8 5

2 4 6 8 5

2 4 6 5 8

2 4 6 5 8

Iteration-2
2 4 6 5 8

2 4 6 5 8

2 4 6 5 8

2 4 5 6 8

2 4 5 6 8

Iteration-3

2 4 5 6 8

2 4 5 6 8

2 4 5 6 8

2 4 5 6 8

Iteration-4

2 4 5 6 8

2 4 5 6 8

2 4 5 6 8

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 96
2 4 5 6 8

Thus the sorted elements are 2 4 5 6 8

Searching
“Searching is a process of finding the exact location of an element in a list.”

There are two ways in which the element can be searched.


(a) Linear Search
(b) Binary Search

(a) Linear Search


 A Linear search method compares the element to be searched with all the elements in the
array until the match is found or the last element in the array has been reached.
 It can be used for arrays that contain small number of elements.
 Linear search can be applied for unsorted array.
 It may take more time to search an element.

Example

Write a C program to search an element in the array by passing an array as argument to


the function.

//Program to search an element in the array using functions

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

void search(int b[],int n,int x); // function prototype

void main()
{
int a[10],i,n,x;
clrscr();
printf("\nEnter n:");
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 97
scanf("%d",&n);

printf("\nEnter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("\nEnter the element to be searched-");


scanf("%d",&x);

search(a,n,x); // passing an array named „a‟ as argument


getch();
}

void search(int b[],int n,int x)


{
int i,flag;
for(i=0;i<n;i++)

if(b[i]==x)
{
flag=1;
break;
}

if(flag==1)
printf("\nElement found!");
else
printf("\nElement not found!");
}

Expected Output
Enter n:3
Enter 3 elements:
10
25
50
Enter the element to be searched-25
Element found!

(b) Binary Search


In binary search method, the key element is searched in the following way.
(1) The array is sorted.
(2) Locate the middle element of the array.
(3) Compare the value at that location with the search key.
(4) If they are equal - done!
(5) Otherwise, decide which half of the array contains the search key.
(6) Repeat the search on that half of the array and ignore the other half.
(7) The search continues until the key is matched or no elements remain to be searched.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 98
Example

Pass-1

Pass-2

Pass-3

Pass-4

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 99
Advantages of Binary Search
 Searching and array of 1024 elements will take at most 10 passes to find a match or
determine that the element does not exist in the array.
512, 256, 128, 64, 32, 16, 8, 4, 2, 1
 An array of one billion elements takes a maximum of 30 comparisons.
 The bigger the array the better a binary search is as compared to a linear search

*******

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 100
UNIT-IV
STRINGS
String Concepts
In general, a string is a series of characters treated as a unit. Computer science has long
recognized the importance of strings, but it has not adapted a standard for their implementation.
We find, therefore, that a string created in Pascal differs from a string created in C.

String Taxonomy

Length Controlled Strings:

Delimited Strings:

C Strings
A string is defined as an array of characters.
C uses variable-length, delimited strings.
In C, Strings are terminated by the special character ‘\0’; this is called a null character or
null terminator.
When you declare the string, you should ensure that you should have sufficient room for the null
character.
The null terminator has ASCII value 0.
A string literal is enclosed in double quotes.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 101

Defining Strings

Memory for strings must be allocated before the string can be used.

String Initialization Methods

char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;

 Each character in the array occupies one byte of memory and the last character is always
„\0‟. What character is this? It looks like two characters, but it is actually only one
character, with the \ indicating that what follows it is something special. „\0‟ is called null
character.
 Note that „\0‟ and „0‟ are not same. ASCII value of „\0‟ is 0, whereas ASCII value of „0‟
is 48.
 Note that the elements of the character array are stored in contiguous memory locations.
 The below figure shows the way a character array is stored in memory.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 102

A string can also be initialized in the following way

char name[ ] = "HAESLER" ;


In the above declaration „\0‟ is not necessary. C inserts the
null character automatically.

Example Program

void main( )
{
char name[ ] = "CSE" ;
printf ( "%s", name ) ;
}

The %s used in printf( ) is a format specification for printing out a string.

Expected Output
CSE

String Input/Output Functions


C provides two basic ways to read and write strings. First, we can read and write strings with the
formatted input/output functions, scanf/fscanf and printf/fprintf.
Second, we can use a special set of string-only functions, get string (gets/fgets) and put string
(puts/fputs).

1. Formatted String Input/Output functions


Example Program

void main()
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "\nHello %s!", name ) ;
}

Expected Output
Enter your name:Ateeq
Hello Ateeq!

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 103
 Note that the declaration char name[25] sets aside 25 bytes under the array name[ ],
whereas the scanf( ) function fills in the characters typed at keyboard into this array until
the enter key is hit.
 Once enter is hit, scanf( ) places a „\0‟ in the array.
 Naturally, we should pass the base address of the array to the scanf( ) function.
 scanf( ) is not capable of receiving multi-word strings.
 Therefore names such as „Computer Science‟ would be unacceptable.
 The way to get around this limitation is by using the function gets( ).

The usage of functions gets( ) and its counterpart puts( ) is shown below.

2. String Input/Output functions


Example Program
//puts and gets

void main()
{
char name[25] ;
clrscr();
printf ( "Enter your full name: " ) ;
gets ( name ) ; // accepts the string
puts ( name ) ; // displays the string
getch();
}

Expected Output
Enter your full name: H. Ateeq Ahmed
H. Ateeq Ahmed
 puts( ) can display only one string at a time (hence the use of two puts( ) in the program
above). Also, on displaying a string, unlike printf( ), puts( ) places the cursor on the next
line.
 Though gets( ) is capable of receiving only one string at a time, the plus point with gets( )
is that it can receive a multi-word string.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 104
String Manipulation Functions
Because a string is not a standard type, we cannot use it directly with most C operators.
Fortunately, C provides a set of functions to manipulates strings.

Out of the above list we shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ),
since these are the most commonly used functions. This will also illustrate how the library
functions in general handle strings. Let us study these functions one by one.

strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the
following program.

Example Program
//to calculate length of string
#include<stdio.h>
#include<conio.h>
void main()
{
char str[]="Computer";
int l;
clrscr();
l=strlen(str);
printf("\nLength=%d",l);
getch();
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 105
}

Expected Output
Length=8

strcpy( )
This function copies the contents of one string into another. The base addresses of the source and
target strings should be supplied to this function.

strcat( )
This function concatenates the source string at the end of the target string. For example,
“Computer” and “Science” on concatenation would result into a string “ComputerScience”.

Example Program
//strcpy & strcat

#include<stdio.h>
#include<conio.h>
void main()
{
char *str;
char *str1="Computer",*str2=" Science";
clrscr();
strcpy(str,str1);
strcat(str,str2);
printf("\n%s",str); // or puts(str);
getch();
}

Expected Output
Computer Science

strcmp( )
This is a function which compares two strings to find out whether they are same or different.
The two strings are compared character by character until there is a mismatch or end of one of
the strings is reached, whichever occurs first.
If the two strings are identical, strcmp( ) returns a value zero.
If they‟re not, it returns the numeric difference between the ASCII values of the first non-
matching pairs of characters.

Example Program
//strcmp
#include<stdio.h>
#include<conio.h>
void main()
{
char *str1,*str2;
int res;
clrscr();
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 106
printf("\nEnter string1:");
gets(str1);
printf("\nEnter string2:");
gets(str2);
res=strcmp(str1,str2);
if(res==0)
printf("\nStrings are equal");
else
printf("\nStrings are not equal");
getch();
}

Expected Output
Enter string1:Computer

Enter string2:Computer

Strings are equal

String/Data Conversion
 The functions printf and scanf are such powerful string manipulators that sometimes we
would like to directly control the strings on which they work.
 Two other similar functions that are also a part of stdio library are sprintf and sscanf.
Let us now see their working with the following programs.

sprintf()
This function substitutes values for placeholders just as printf does, but instead of printing the
result, sprintf stores it in the character array accessed by its initial argument.

Example Program
//use of sprintf
void main()
{
int day=15,mon=8,year=2012;
char str[50];
clrscr();
sprintf(str,"%d/%d/%d",day,mon,year); //result is stored in string "str"
printf("\n%s",str);
getch();
}

Expected Output
15/8/2012
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 107
sscanf()
The sscanf function works exactly like scanf except that instead of taking the data values for its
output parameters from the standard input device, it takes data from the string that is its first
argument.

Example Program
//use of sscanf
void main()
{
int rno;
char name[20];
float per;
clrscr();
sscanf("25 Ateeq 71","%d%s%f",&rno,&name,&per);
printf("\nRoll no=%d",rno);
printf("\nName=%s",name);
printf("\nPercentage=%.2f",per);
getch();
}

Expected Output
Roll no=25
Name=Ateeq
Percentage=71.00

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 108
ENUMERATED, STRUCTURE, AND UNION TYPES

The Type Definition (typedef)


“Typedef provides the facility of providing alternative names for the basic data types in C such
as int, pointers and structures”.
A program that carries out so many tasks would be very big in size. In such a program if we start
using the normal integer data type to represent variables that hold different entities we would
soon lose track of what that integer value actually represents. This can be overcome by using
typdef.

Example Programs
(1)
//using typdef with simple data types
void main()
{
typedef int integer; // using integer instead of int
integer a;
a=10;
clrscr();
printf("\na=%d",a);
getch();
}

(2)
//Using typedef with pointers
void main()
{
int a=10;
typedef int* integer;
integer ptr; // ptr is a pointer to int
clrscr();
ptr=&a;
printf("\nAddress of a is %u",ptr);
printf("\nValue of a is %d",*ptr);
getch();
}

(3)
//using typedef with structure
struct student
{
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 109
int rno;
char name[15];
};
void main()
{
typedef struct student profile;
profile s={25,"Ahmed"};
clrscr();
printf("\nRollno=%d \nName=%s",s.rno,s.name);
getch();
}

Enumerated Data Type


 The Enumerated data type helps the programmer to create his/her own data type and
define what values the variables of these data types can hold.
 Thus the use of Enumerated data type improves the readability of the program.
 The keyword “enum” is used for declaring enumerated data types.

Example

enum days
{
sun, mon, tue, wed, thu, fri, sat // no semicolon(;) after identifiers
};
enum days d1,d2; // d1, d2 are variables of data type “days”

The above statement creates a user defined data type.


 The keyword enum is followed a tag name “days”.
 The identifies sun, mon etc are called enumerators.
 Their values are constant unsigned integers and start from 0.
 By default, the identifier sun refers to 0, mon refers to 1 and so on.

Example Program 1

void main()
{
enum branch // branch is enumerated data type
{
cse,ece,eee // cse,ece,eee are values of variables b1,b2,b3
};
enum branch b1,b2,b3;
clrscr();
b1=cse; // internally cse means „0‟
b2=ece; // internally ece means „1‟
b3=eee; // internally eee means „2‟
printf("\nCSE=%d",b1);
printf("\nECE=%d",b2);
printf("\nEEE=%d",b3);

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 110
getch();
}

Expected Output
CSE=0
ECE=1
EEE=2

Example Program 2
void main()
{
enum branch // branch is enumerated data type
{
cse=5,ece=4,eee=2 // cse,ece,eee are values of variables b1,b2,b3
};
enum branch b1,b2,b3;
clrscr();
b1=cse; // internally cse means „5‟
b2=ece; // internally ece means „4‟
b3=eee; // internally eee means „2‟
printf("\nCSE=%d",b1);
printf("\nECE=%d",b2);
printf("\nEEE=%d",b3);

getch();
}

Expected Output
CSE=5
ECE=4
EEE=2

Structure
We have seen earlier how ordinary variables can hold one piece of information and how arrays
can hold a number of pieces of information of the same data type. These two data types can
handle a great variety of situations. But quite often we deal with entities that are collection of
dissimilar data types.

For example, suppose you want to store data about a book.


You might want to store its name (a string), its price (a float) and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can follow two approaches:

(a) Construct individual arrays, one for storing names, another for storing prices and still another
for storing number of pages.

(b) Use a structure variable.

In the first approach, the program becomes more difficult to handle as the number of items
relating to the book go on increasing. For example, we would be required to use a number of

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 111
arrays, if we also decide to store name of the publisher, date of purchase of book, etc. To solve
this problem, C provides a special data type—the structure.

Structure
A structure contains a number of data types grouped together.
These data types may or may not be of the same type.
Unlike arrays which can store elements of same data type, a structure can hold data of different
data types.

Declaring a Structure
The general form of a structure declaration statement is given below:

Syntax
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};

Example
struct book
{
char name ;
float price ;
int pages ;
};

The above statement defines a new data type called struct book. Each variable of this data type
will consist of a character variable called name, a float variable called price and an integer
variable called pages.

Once the new structure data type has been defined one or more variables can be declared to be of
that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as,

struct book b1, b2, b3 ;

This statement sets aside space in memory. It makes available space to hold all the elements in
the structure—in this case, 7 bytes—one for name, four for price and two for pages. These bytes
are always in adjacent memory locations.

If we so desire, we can combine the declaration of the structure type and the structure variables
in one statement.
For example,

struct book
{
char name ;
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 112
float price ;
int pages ;
};
struct book b1, b2, b3 ;

(or)

struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

Important points about structure declaration

 The closing brace in the structure type declaration must be followed by a semicolon.

 It is important to understand that a structure type declaration does not tell the compiler to
reserve any space in memory. All a structure declaration does is, it defines the „form‟ of
the structure.

 Usually structure type declaration appears at the top of the source code file, before any
variables or functions are defined. In very large programs they are usually put in a
separate header file, and the file is included (using the preprocessor directive #include) in
whichever program we want to use this structure type.

Initialization of structures
Like primary variables and arrays, structure variables can also be initialized where they are
declared. The format used is quite similar to that used to initiate arrays.

struct book
{
char name[10] ;
float price ;
int pages ;
};
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

Accessing Structure Elements


Having declared the structure type and the structure variables, let us see how the elements of the
structure can be accessed.
In arrays we can access individual elements of an array using a subscript.
Structures use a different scheme. They use a dot (.) operator.
So to refer to pages of the structure defined in our sample program we have to use,
b1.pages

Similarly, to refer to price we would use,


Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 113
b1.price

Note that before the dot there must always be a structure variable and after the dot there must
always be a structure element.

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

void main()
{

struct book
{
char name[20];
float price;
int pages;
};
struct book b1={"C Language",275.75,450}; // Initialization of structure variable
clrscr();

printf("\nBook Name=%s",b1.name);
printf("\nPrice=%.2f",b1.price);
printf("\nPages=%d",b1.pages);

getch();
}
Expected Output
Book Name=C Language
Price=275.5
Pages=450

How Structure Elements are Stored


Whatever be the elements of a structure, they are always stored in contiguous memory locations.
The following program would illustrate this:

main()
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
printf ( "\nAddress of price = %u", &b1.price ) ;
printf ( "\nAddress of pages = %u", &b1.pages ) ;
getch();
}
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 114

Memory Representation
Actually the structure elements are stored in memory as shown below

Expected Output
Address of name = 65518
Address of price = 65519
Address of pages = 65523

Example Program
void main()
{
struct book
{
char name[20];
float price;
int page;
}b1;
clrscr();

printf("\nEnter the name, price, pages of book\n");


scanf("%s%f%d",&b1.name,&b1.price,&b1.page);

printf("\nBook Name=%s",b1.name);
printf("\nPrice=%.2f",b1.price);
printf("\nPages=%d",b1.page);

getch();
}

Expected Output
Enter the name, price, pages of book
PCDS
275.50
370

Book Name=PCDS
Price=275.50
Pages=370

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 115
Structure within Structure
One structure can be nested within another structure. Using this facility complex data types can
be created.

Example Program
//Structure within Structure
void main()
{
struct student // outer structure
{
char name[20];
int rno;

struct address // inner structure


{
char city[20];
char state[20];
}a;
}s;
clrscr();
printf("Enter Student name, Roll no,City,State\n");
scanf("%s%d%s%s",&s.name,&s.rno,&s.a.city,&s.a.state);

printf("\nName:%s \nRoll no:%d",s.name,s.rno);


printf("\nCity:%s \nState:%s",s.a.city,s.a.state);
getch();
}

Expected Output
Enter Student name, Roll no,City,State
Saqib
25
Kurnool
AP

Name:Saqib
Roll no:25
City:Kurnool
State:AP

UNION
 Like structure, a union can hold data belonging to different data types but it hold only one
object at a time.
 In the structure each member has its own memory locations whereas, members of unions
have same memory locations.
 The union requires bytes that are equal to the number of bytes required for the largest
member.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 116
 For example, if the union contains char, integer and float then the number of bytes
reserved in the memory is 4 bytes (i.e. the size of float).
 Unlike structure members which can be initialized all at the same time, only one union
member should be initialized at a time.

Syntax
The syntax of union is similar to the structure which is shown below
union <union_ name>
{
union element 1 ;
union element 2 ;
union element 3 ;
......
......
};
Let us now observe the difference between union and structure by using the
following program.

Example Program
//To show the difference between structure & union

struct student1 // structure


{
int rno;
char grade;
};

union student2 //union


{
int rno;
char grade;
};

void main()
{
struct student1 s={25,'A'}; // initialization of structure members at a time
union student2 u;
clrscr();

printf("\nRollno=%d",s.rno);
printf("\nGrade=%c",s.grade);

u.rno=30; // initialization of union member 1


printf("\nRollno=%d",u.rno);
u.grade='B'; // initialization of union member 2
printf("\nGrade=%c",u.grade);

printf("\nSize of Structure=%d bytes",sizeof(s)); // displaying size of structure


printf("\nSize of Union=%d bytes",sizeof(u)); // displaying size of union
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 117
getch();
}

Expected Output
Rollno=25
Grade=A
Rollno=50
Grade=B
Size of Structure=3 Bytes
Size of Union=2 Bytes

In the above, the size of structure is sum of the sizes of all its
members i.e. int & char which is (2+1)=3 bytes whereas the size of union is the size of the
member which belongs to largest data type i.e. int which is of 2 bytes.

Programming Application
In this section, we develop a program that simulates the operation of an elevator. The elevator
serves floors from zero (the basement) to the top floor. The elevator is very old and is not fully
automatic. When people enter the elevator, they enter their desired floor number.

Elevator Structure

Elevator Structure Chart

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 118
BITWISE OPERATORS
 Bitwise operators are special types of operators that are used in programming the
processor.
 In processor, mathematical operations like: addition, subtraction, addition a nd
division are done using the bitwise operators which makes processing faster and
saves power.
 Bitwise operators are used to manipulate one or more bits from integral operands like
char, int, short, long.
C language supports the following bitwise operators.

Operators Meaning

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
~ One‟s complement
<< Shift left
>> Shift right

The above operators can be grouped in to the following two major categories.
(1) Logical bitwise operators
(2) Shift operators.

Let us discuss each of them briefly.

(1) LOGICAL BITWISE OPERATORS

Bitwise AND (&):


The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of
bit is 0 or both bits are 0, the output will be 0.
It is a binary operator(works on two operands) and indicated in C programming by
& symbol. Let us suppose the bitwise AND operation of two integers 12 and 25.

2 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 119
As, every bitwise operator works on each bit of data.
The corresponding bits of two inputs are check and if both bits are 1 then only the
output will be 1.
In this case, both bits are 1 at only one position i.e, fourth position from the right,
hence the output bit of that position is 1 and all other bits are 0.

Example Program
#include <stdio.h>
void main()
{
int a=12,b=25;
printf("Output=%d",a&b);
getch();
}

Expected Output
Output=8

Bitwise OR ( | ):
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1.
In C Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

Example Program
#include <stdio.h>
void main()
{
int a=12,b=25;
printf("Output=%d",a|b);
getch();
}

Expected Output
Output=29

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 120

Bitwise XOR(exclusive OR)


The output of bitwise XOR operator is 1 if the corresponding bits of two operators are
opposite(i.e., To get corresponding output bit 1; if corresponding bit of first operand is 0
then, corresponding bit of second operand should be 1 and vice-versa.).
It is denoted by ^.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
________
00010101 = 21 (In decimal)

Example Program
#include <stdio.h>
void main()
{
int a=12,b=25;
printf("Output=%d",a^b);
getch();
}

Expected Output
Output=21

One’s Complement (~)


Bitwise compliment operator is an unary operator (works on one operand only).
It changes the corresponding bit of the operand to opposite bit i.e. 0 to 1 and 1 to 0.
It is denoted by ~.

35=00100011 (In Binary)

Bitwise One‟s complement operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 121

(2) SHIFT OPERATORS


There are two shift operators in C programming: Right shift operator and Left shift
operator .

Right Shift Operator (>>)


Right shift operator moves the all bits towards the right by certain number of bits which
can be specified.
It is denoted by >>.

Example
int a=8>>1;

Let‟s take the binary representation of 8 assuming int is 1 byte for simplicity.

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 1 0 0 0

Now shifting the bits towards right for 1 time, will give the following result

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0

Left Shift Operator (>>)


The left shift operator will shift the bits towards left for the given number of times.

Example
int a=2<<1;

Let‟s take the binary representation of 2 assuming int is 1 byte for simplicity.

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 0 1 0

Now shifting the bits towards left for 1 time, will give the following result

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 122
For any positive number, right shift is equal to integer division of that number by (shift
bit plus one) and for any integer left shift is equal to the multiplication of that number by
(shift bit plus one).

Example Program
#include <stdio.h>
void main()
{
int num=212,i;
for (i=0;i<=2;i++)
printf("Right shift by %d: %d\n",i,num>>i);
printf("\n");
for (i=0;i<=2;i++)
printf("Left shift by %d: %d\n",i,num<<i);
getch();
}

Expected Output
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848

Mask
Mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

 Bitwise ANDing in order to extract a subset of the bits in the value


 Bitwise ORing in order to set a subset of the bits in the value
 Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:


Mask: 00001111b
Value: 01010101b
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the
last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask: 00001111b
Value: 01010101b
Result: 00000101b

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 123
Masking bits to 1
To turn certain bits on, the bitwise OR operation can be used, following the principle that Y OR
1 = 1 and Y OR 0 = Y. Therefore, to make sure a bit is on, OR can be used with a 1. To leave a
bit unchanged, OR is used with a 0.
Example: turning on the 4th bit

10011101 10010101
OR 00001000 00001000
= 10011101 10011101

Masking bits to 0
There is no way to change a bit from on to off using the OR operation. Instead, bitwise AND is
used. When a value is ANDed with a 1, the result is simply the original value, as in: Y AND 1 =
Y. However, ANDing a value with 0 is guaranteed to return a 0, so it is possible to turn a bit off
by ANDing it with 0: Y AND 0 = 0. To leave the other bits alone, ANDing them with a 1 can be
done.
Example: Turning off the 4th bit

10011101 10010101
AND 11110111 11110111
= 10010101 10010101

Toggling bit values


So far the article has covered how to turn bits on and turn bits off, but not both at once.
Sometimes it does not really matter what the value is, but it must be made the opposite of what it
currently is. This can be achieved using the XOR (exclusive or) operation. XOR returns 1 if and
only if an odd number of bits are 1. Therefore, if two corresponding bits are 1, the result will be
a 0, but if only one of them is 1, the result will be 1. Therefore inversion of the values of bits is
done by XORing them with a 1. If the original bit was 1, it returns 1 XOR 1 = 0. If the original
bit was 0 it returns 0 XOR 1 = 1. Also note that XOR masking is bit-safe, meaning that it will not
affect unmasked bits because Y XOR 0 = Y, just like an OR.
Example: Toggling bit values

10011101 10010101
XOR 00001111 11111111
= 10010010 01101010

*******
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 124
UNIT-V
POINTERS
Introduction
As we know that, each variable has two attributes: address and value. A variable can take any
value specified by its data type.
For example, if the variable i is of the integer type, it can take any value permitted in the range
specified by the integer data type.
A pointer to an integer is a variable that can store the address of that integer.

Consider the declaration,

int i = 3 ;

This declaration tells the C compiler to:


(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.

We may represent i‟s location in memory by the following memory map.

We can print this address number through the following program:


main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ; // “address of” operator
printf ( "\nValue of i = %d", i ) ;
printf(“\nValue of i=%d”,*(&i)); // “value at address” operator
}

Expected Output
Address of i = 65524
Value of i = 3
Value of i=3

Look at the first printf( ) statement carefully. „&‟ used in this statement is C‟s „address of‟
operator. The expression &i returns the address of the variable i, which in this case happens to be
65524. Since 65524 represents an address, there is no question of a sign being associated with it.
Hence it is printed out using %u, which is a format specifier for printing an unsigned integer.
We have been using the „&‟ operator all the time in the scanf( ) statement.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 125
The other pointer operator available in C is „*‟, called „value at address‟ operator. It gives the
value stored at a particular address. The „value at address‟ operator is also called „indirection‟
operator.

Pointer
“A Pointer is a variable that can store the address of another variable”.
Syntax
Data-type *variable;

Example
int *i;
In the above declaration, „*‟ indicates that „i‟ is a pointer variable.

Example Program
//Program to show the use of pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,*ptr;
clrscr();
ptr=&a; // address of a is stored in ptr
printf("\nAddress of a is %u",ptr); // displaying the address of a
printf("\nValue of a is %d",*ptr); // displaying the value of a
getch();
}

Memory Representation

a ptr

10 65524

Address 65524 65522

The expression &a gives the address of the variable a. This address can be collected in a
variable, by saying,
ptr = &a ;
But remember that ptr is not an ordinary variable like any other integer variable. It is a variable
that contains the address of other variable (a in this case). Since ptr is a variable the compiler
must provide it space in the memory.

Expected Output
Address of a is 65524
Value of a is 10

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 126

Pointers for Inter Function Communication


The technique of passing the address of the variable as a parameter to the
function is known as a “Call by reference”.
We have also learnt that variables are stored somewhere in memory. So instead of passing the value
of a variable, we pass its location (also called address) of the variable to a function. Hence this
technique is Call by reference.
Example Program
//call by reference
#include<stdio.h>
#include<conio.h>

void swap(int *x,int *y);


void swap(int *x,int *y) //x & y are formal parameters
{
int *z;
*z=*x;
*x=*y;
*y=*z;
printf("\nSwapped values are %d %d",*x,*y);
}
void main()
{
int a=10,b=20;
clrscr();
printf("\nValues before swap are %d %d",a,b);
swap(&a,&b); //a & b are actual parameters
printf("\nValues after swap are %d %d",a,b);
getch();
}
Expected Output
Values before swap are 10 20
Swapped values are 20 10
Values after swap are 20 10

Pointers to Pointers
“A pointer to pointer is a variable that can store the address of another pointer variable.”

Example Program
//pointer to pointer
void main()
{
int a=10,*ptr1,*ptr2;
clrscr();
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 127
ptr1=&a;
printf("\nAddress of a is %u",ptr1);
printf("\nValue of a is %d",*ptr1);
ptr2=&ptr1; // a ponter ptr2 storing the address of another pointer ptr1
printf("\nAddress of ptr1 is %u",ptr2);
printf("\nValue of ptr1 is %u",*ptr2);
getch();
}

Memory Representation

a ptr1 ptr2

10 65524 65522
Address 65524 65522 65520

Expected Output
Address of a is 65524
Value of a is 10
Address of ptr1 is 65522
Value of ptr1 is 65524

Compatibility
It is important to recognize that pointers have a type associated with them. They are not just
pointer types, but rather are pointers to a specific type, such as character. Each pointer therefore
takes on the attributes of the type to which it refers in addition to its own attributes.

Void Pointers
 A void pointer is used for working with raw memory or for passing a pointer to an
unspecified type.
 A void pointer is a C convention for “a raw address.” The compiler has no idea what type
of object a void Pointer “really points to.”
 If you write int *ip; ip points to an int. If you write void *p; p doesn‟t point to any data
type.

Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=10;
float f=2.5;
char c='A';
void *ptr; // ptr is declared as void
clrscr();
ptr=&i;
printf("\nValue of i is %d",*(int*)ptr);
ptr=&f;
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 128
printf("\nValue of f is %f",*(float*)ptr);
ptr=&c;
printf("\nValue of c is %c",*(char*)ptr);
getch();
}

Expected Output
Value of i is 10
Value of f is 2.5
Value of c is A

Lvalue and Rvalue


In C, an expression is either an lvalue or an rvalue. As you know, every expression has a value.
But the value in an expression (after evaluation) can be used in two different ways.

Lvalue Expressions

Rvalue Expressions

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 129
POINTER APPLICATIONS

Array and Pointers


Pointers and arrays have the following important properties.

(a) Array elements are always stored in contiguous memory locations.


(b) A pointer when incremented always points to an immediately next location of its type.

Suppose we have an array num[ ] = { 24, 34, 12, 44, 56, 17 }. The following figure shows how
this array is located in memory.

This method of accessing array elements by using subscripted variables is already known to us.
Now let us see how we can access the above array elements by using pointers.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 130
//Program to show the use of pointers with arrays

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 131
Obviously, a question arises as to which of the above two methods should be used ?
Accessing array elements by pointers is always faster than accessing them by subscripts.

Example Program
//Program to show the use of pointers with arrays
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,*ptr;
clrscr();
printf("\nEnter the elements in the array:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
ptr=&a[0];
for(i=0;i<5;i++)
{
printf("\n%d",*ptr);
ptr++;
}
getch();
}

Pointer Arithmetic and Arrays


Like normal variables, pointers can also be used to perform various arithmetic operations like
addition, subtraction etc.
//Program to show the use Arithmetic operations on pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*res,*ptr1,*ptr2;
clrscr();
printf("\nEnter any two numbers:");
scanf("%d%d",&a,&b);
ptr1=&a;
ptr2=&b;

*res=*ptr1+*ptr2; // addition
printf("\nSum=%d",*res);

*res=*ptr1-*ptr2; // subtraction
printf("\nDifference=%d",*res);

*res=*ptr1**ptr2; // multiplication
printf("\nProduct=%d",*res);

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 132
*res=*ptr1/(*ptr2); // division
printf("\nDivision=%d",*res);

*res=*ptr1%*ptr2; // mod
printf("\nRemainder=%d",*res);
getch();
}
Expected Output
Enter any two numbers:
20
10

Sum=30
Difference=10
Product=200
Division=2
Remainder=0

Passing an Array to a Function


Refer UNIT-II Topic - Using Array Elements as arguments to a function – (Page-37-40)

Memory Allocation Functions


C has the facility of dynamic memory allocations. Using this, you can allocate the memory for
your storage. The allocation is done at runtime. When your work is over, you can deallocate the
memory.
The allocation of memory is done using three functions: malloc, relloc, and calloc. The
functions return the pointers to void, so it can be typecast to any data type, thus making the
functions generic. These functions take the input as the size of memory requirement.

We can allocate memory at runtime by using the function malloc. malloc allocates memory
specified using an argument in terms of bytes, and returns the pointer to storage from where the
memory is allocated. We can deallocate the memory by using the function free.
Syntax

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 133
Example Program

#include <stdio.h>
#include <malloc.h>
main()
{
int *base; \\ A
int i;
int cnt=0;
int sum=0;
printf("how many integers you have to store \n");
scanf("%d",&cnt); \\ B
base = (int *)malloc(cnt * sizeof(int)); \\ C
printf("the base of allocation is %16lu \n",base); \\ D
if(!base) \\ E
printf("unable to allocate size \n");
else
{
for(int j=0;j<cnt;j++) \\ F
*(base+j)=5;
}
sum = 0;
for(int j=0;j<cnt;j++) \\ G
sum = sum + *(base+j);
printf("total sum is %d\n",sum);
free(base); \\ H
printf("the base of allocation is %16lu \n",base);
base = (int *)malloc(cnt * sizeof(int));
printf("the base of allocation is %16lu \n",base);
base = (int *)malloc(cnt * sizeof(int)); \\ I
printf("the base of allocation is %16lu \n",base);
base = (int *)calloc(10,2); \\ J
printf("the base of allocation is %16lu \n",base);
}

Explanation

1. This program demonstrates the use of dynamic memory allocation for processing n
integers where n is not defined at compilation time, but the user instead specifies the
number of integers to be processed.
2. The processing adds 5 to the value of each integer.
3. Statement B reads how many integers you have to process.
4. Statement C allocates memory for the required integers by using the function malloc.
5. malloc takes the size in bytes as input.
6. The size of the operator returns how many bytes can be occupied by one unit of the
specified data type. The size of int returns two bytes. If you give the value cnt as 10
then it will allocate 20 bytes.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 134
7. malloc returns the pointer to void, which is typecast as a pointer to an integer. The
value starts at the address of the memory from where allocations are done.
8. You can again allocate more or less memory by using the function malloc. You can
again allocate memory without deallocating previous memory as given by statement I.
You can allocate the memory similarly to malloc by using the function calloc.
calloc takes two arguments: total number of data and the size of each data.

Array of Pointers
 The way there can be an array of ints or an array of floats, similarly there can be an array
of pointers.
 Since a pointer variable always contains an address, an array of pointers would be
nothing but a collection of addresses.
 The addresses present in the array of pointers can be addresses of normal variables or
addresses of array elements or any other addresses.
 All rules that apply to an ordinary array apply to the array of pointers as well. I think a
program would clarify the concept.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 135
Explanation
 The above figure shows the contents and the arrangement of the array of pointers in
memory. As you can observe, arr contains addresses of int variables i, j, k and l.
 The for loop in the program picks up the addresses present in arr and prints the values
present at these addresses.
 An array of pointers can even contain the addresses of other arrays.

Example Program
//Program to show the array of pointers

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

void main()
{
int *a[3],b[3][3],i,j;
clrscr();
for(i=0;i<3;i++)
a[i]=&b[i][0];
printf("\nEnter the elements:");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nThe array elements are:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\n%d",*(a[i]+j));
}
}
getch();
}

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 136
Programming Applications
This section contains two applications.
 The first is a rewrite of the selection sort, this time using pointers.
 The second uses dynamic arrays.

Selection Sort with Pointers

Dynamic Arrays

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 137
BINARY INPUT/OUTPUT
Text Versus Binary Streams

Text Files

Binary Files
A binary file is a collection of data stored in the internal format of the computer. Unlike text
files, the data do not need to be reformatted as they are read and written; rather, the data are
stored in the file in the same format that they are stored in memory. Binary files are read and
written using binary streams known as block input/output functions. The following figure shows
the operation of block read and write functions.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 138

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 139

A file can be opened in the write state using either the write or append mode. In write mode, the
writing starts at the beginning of the file. If the file already exists, its data are lost. In append
mode, the data are added at the end of the file. If the file exists, the writing begins after the
existing data. If the file does not exist, a new file is created.

Opening Binary Files


The basic open operation is unchanged for binary files – only the mode changes. The function
declaration for fopen is repeated here for convenience.

FILE* fopen(const char* filename,const char* mode);

Closing binary Files


Just like text files, binary files must be close when they are not needed anymore. Closing
destroys the file table and erases the logical name.

int fclose(FILE* sp);

Standard Library Functions for Files


The following are some of the library functions for files

Block Input/Output Functions


The C language uses the block input and output functions to read and write data to binary files.
As we discussed previously, when we read and write binary files, the data are transferred just as
they are found in memory. There are not format conversions. This means that, with the exception
of character data we cannot “see” the data in a binary file; it looks like hieroglyphics. If you have
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 140
ever accidently opened a binary file in a text editor, you have seen these strange results. The
block read function is file read (fread). The block write function is file (fwrite).

File Read: fread


The function fread, whose declaration is shown below, reads a specified number of bytes from a
binary file and places them into memory at the specified location.

int fread (void* pInArea,


int elementSize,
int count,
FILE* sp);

File Write: fwrite


The function fwrite, whose declaration is shown below, writes a specified number of items to a
binary file.

int fwrite ( void* pOutArea,


int elementSize,
int count,
FILE* sp);

The parameters for file write correspond exactly to the parameters for the file read function.

File Status Functions


C provides three functions to handle file status questions:
Test end of file(feof), test error(ferror), and clear error(clearer)

Test End of File: foef


The feof function is used to check if the end of file has been reached. If the file is at the end –
that is, if all data have been read – the function returns nonzero (true). If end of file has not been
reached, zero(false) is returned. The function declraration is shown below.

int feof (FILE* stream);

Test Error: ferror

int ferror (FILE* stream);

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 141

Clear Error: clearerr

void clearerr (FILE* stream);

Positioning Functions

Rewind File: rewind


The rewind function simple sets the file position indicator to the beginning of the file. The
function declaration is shown below.

void rewind (FILE* stream);

Current Location: ftell

long int ftell (FILE* stream);

Set Position: fseek

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 142
int fseek (FILE* stream, long offset, int wherefrom);

#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2

System File Operations

Remove File: remove

Rename File: rename

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 143

Create Temporary File: tmpfile

Converting File Type


A rather common but somewhat trivial problem is to convert a text file to a binary file and vice
versa. C has no standard functions for these tasks. We must write a program to make the
conversion.

Creating a Binary File from a Text File


To create a binary file, we usually start with data provided by the user. Since the user is
providing the data, it will be in human readable form- that is, in text form. If only a small amount
of initial data is required, they are often read from a keyboard. With a lot of data, however, it is
easier for the user to enter the data with a text editor and then read the text file and create the
binary file.

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 144

Creating a Text File from a Binary File

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 145

Linked Lists

Linked list is one of the fundamental data structures in C.


Linked list is a dynamic data structure whose length can be increased or decreased at run time.

How Linked lists are different from arrays? Consider the following points:

 An array is a static data structure. This means the length of array cannot be altered at run
time. While, a linked list is a dynamic data structure.
 In an array, all the elements are kept at consecutive memory locations while in a linked
list the elements (or nodes) may be kept at any location but still connected to each other.

When to prefer linked lists over arrays? Linked lists are preferred mostly when you don‟t know
the volume of data to be stored. For example, In an employee management system, one cannot
use arrays as they are of fixed length while any number of new employees can join. In scenarios
like these, linked lists (or other dynamic data structures) are used as their capacity can be
increased (or decreased) at run time (as an when required).

1. Linked List is Series of Nodes


2. Each node Consist of two Parts i.e. Data Part & Pointer Part
3. Pointer Part stores the address of the next node

Problem Solving and Computer Programming By: H. Ateeq Ahmed


Department of CSE 146
Example

What is a node ?

1. Each Linked List Consists of Series of Nodes


2. In above Diagram , Linked List Consists of three nodes Node1, Node2 and Node3.
3. Node1 has two parts, one data part which consists of the 5 as data and the second part
which contain the address of the next node.

Types of Linked Lists


(1) Singly Linked List
(2) Doubly Linked List
(3) Circular Linked List

1. Singly Linked List


 In this type of Linked List two successive nodes are linked together in linear fashion .
 Each Node contain address of the next node to be followed.
 In Singly Linked List only Linear or Forward Sequential movement is possible.
 Elements are accessed sequentially , no direct access is allowed.

Explanation
 It is most basic type of Linked List in C.
 It is simple sequence of dynamically allocated nodes.
 Each Node has its successor and predecessor.
 First Node does not have predecessor while last node does not have any successor.
Problem Solving and Computer Programming By: H. Ateeq Ahmed
Department of CSE 147
 Last Node have successor reference as “NULL“.
 In Singly Linked List access is given only in one direction thus Accessing Singly
Linked is Unidirectional.
 We can have multiple data fields inside Node but we have only single “Link” for next
node.

Insertion and Deletion


Refer Lab Record – Singly Linked List Program.

Advantages of Linked Lists


1. Linked List is Dynamic data Structure .
2. Linked List can grow and shrink during run time.
3. Insertion and Deletion operations are Easier
4. Efficient Memory Utilization ,i.e. no need to pre-allocate memory
5. Faster Access time.
6. Linear Data Structures such as Stack, Queue can be easily implemented using Linked
list

Disadvantages of Linked Lists


1. Wastage of memory
2. No Random accessing of elements
3. Time Consuming
4. Reverse Traversing is Difficult

*******

Problem Solving and Computer Programming By: H. Ateeq Ahmed

You might also like