PSCP Material
PSCP Material
As per
R13 CSE
Syllabus
By
H. Ateeq Ahmed, M.Tech.,
Assistant Professor of CSE,
Kurnool.
First I thank Almighty God for giving me the knowledge to learn and teach
various students.
a magical way…”
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.”
Software
Types of 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
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.
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
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.
Example C program
#include<stdio.h>
#include<conio.h>
void main()
{
printf(“Hello to CSE!”);
getch();
}
Expected Output
Hello to CSE!
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.
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
#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!
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.
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
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.
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.
(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);
(b) putchar()
This function displays a single character on an output device.
Syntax
puts(var);
(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
Introduction
Top-down Design
Construction of Loops
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
Implementation of Algorithms
Documentation of programs
Debugging Programs
Program Verification
Redundant computations
Referencing array elements
Inefficiency due to late termination
Early detection of desired output conditions
*******
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
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
Example-1
x=a-b/3+c*2-1
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
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.
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)
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
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);
rem=n1%n2;
printf("\nRemainder=%f",rem);
getch();
}
Expected Output
Enter two numbers:25
4
Quotient=6.250000
Remainder=1.000000
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.
Operators
Operators are C tokens which can join together individual constants, variables, array elements
etc.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and Decrement operators
Conditional operators
Bitwise operators
Special operators
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 ‗=‘.
(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.
void main()
{
int age;
clrscr();
printf(―Enter the age:‖);
scanf(―%d‖,&age);
if(age>=18)
printf(―\nEligible for Voting.‖);
else
printf(―\nNot eligible.‖);
getch();
}
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
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.
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.
Syntax
while(condition)
{
statements;
}
Syntax
for(initialization;condition;iteration)
{
statements;
}
Syntax
do
{
statements;
}
while(condition);
Counting
Thus
Finally
Factorial Computation
Base Conversion
We have
Array Techniques
Introduction
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
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>
Expected Output
Enter the number:25
Square root=5.000000
Syntax:
return-type function-name(parameter-list)
{
local variables;
statements;
}
Advantages of functions
#include<stdio.h>
#include<conio.h>
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.
void main()
{
clrscr();
sum();
getch();
}
void main()
{
int a,b;
clrscr();
a=10;
b=20;
sum(a,b);
getch();
}
void main()
{
int res;
clrscr();
res=sum();
printf("\nSum=%d",res);
getch();
}
void main()
{
int x,y,res;
clrscr();
x=10;
y=15;
res=sum(x,y);
printf("\nSum=%d",res);
getch();
}
Example Program:
//call by value
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
clrscr();
printf("\nValues before swap are %d %d",a,b);
Expected Output
Values before swap are 10 20
Swapped values are 20 10
Values after swap are 10 20
Example Program:
//call by reference
#include<stdio.h>
#include<conio.h>
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.
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.
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.
Array Declaration
Data-type array-name[Size];
Examples
int a[5];
a
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
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.
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();
}
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
#include<stdio.h>
#include<conio.h>
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
#include<stdio.h>
#include<conio.h>
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
Expected Output
Enter any three numbers:
10
20
30
10
20
30
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3],i;
clrscr();
printf("\nEnter any three numbers:");
for(i=0;i<3;i++)
scanf("%d",&a[i]);
getch();
}
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.”
Example
int a[3][2]={{2,4}, {6,8}, {10,12}};
Column Index
Row Index
Memory Representation:
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
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
2 6 4 8 5
Iteration-1
2 6 4 8 5
2 6 4 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
Searching
“Searching is a process of finding the exact location of an element in a list.”
Example
#include<stdio.h>
#include<conio.h>
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]);
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!
Pass-1
Pass-2
Pass-3
Pass-4
*******
String Taxonomy
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.
Defining Strings
Memory for strings must be allocated before the string can be used.
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.
Example Program
void main( )
{
char name[ ] = "CSE" ;
printf ( "%s", name ) ;
}
Expected Output
CSE
void main()
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "\nHello %s!", name ) ;
}
Expected Output
Enter your name:Ateeq
Hello Ateeq!
The usage of functions gets( ) and its counterpart puts( ) is shown below.
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.
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
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
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();
}
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”
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);
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.
(a) Construct individual arrays, one for storing names, another for storing prices and still another
for storing number of pages.
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
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,
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 ;
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 } ;
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
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("\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
Example Program
//Structure within Structure
void main()
{
struct student // outer structure
{
char name[20];
int rno;
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.
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
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);
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
Operators Meaning
The above operators can be grouped in to the following two major categories.
(1) Logical bitwise operators
(2) Shift operators.
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 |.
Example Program
#include <stdio.h>
void main()
{
int a=12,b=25;
printf("Output=%d",a|b);
getch();
}
Expected Output
Output=29
Example Program
#include <stdio.h>
void main()
{
int a=12,b=25;
printf("Output=%d",a^b);
getch();
}
Expected Output
Output=21
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
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
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
Mask
Mask defines which bits you want to keep, and which bits you want to clear.
Mask: 00001111b
Value: 01010101b
Result: 00000101b
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
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.
int i = 3 ;
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.
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
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
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 Expressions
Rvalue Expressions
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.
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();
}
*res=*ptr1+*ptr2; // addition
printf("\nSum=%d",*res);
*res=*ptr1-*ptr2; // subtraction
printf("\nDifference=%d",*res);
*res=*ptr1**ptr2; // multiplication
printf("\nProduct=%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
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
#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.
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.
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();
}
Dynamic Arrays
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.
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.
The parameters for file write correspond exactly to the parameters for the file read function.
Positioning Functions
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
Linked Lists
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).
What is a node ?
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.
*******