My Notes PPS
My Notes PPS
JNTU HYDERABAD
SYLLABUS
UNIT – I
Bitwise operations: Bitwise AND, OR, XOR and NOT operators Conditional
Branching and Loops: Writing and evaluation of conditionals and consequent
branching with if, if-else, switch-case, ternary operator, goto, Iteration with
for, while, do-while loops I/O: Simple input and output with scanf and printf,
formatted I/O, Introduction to stdin, stdout and stderr. Command line
arguments.
UNIT – II
Page 1 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – III
Files: Text and Binary files, Creating and Reading and writing text and binary
files, Appending data to existing files, Writing and reading structures using
binary files, Random access using fseek, ftell and rewind functions.
UNIT – IV
Page 2 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – V
*****
Page 3 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – I
Types of software:
Primary memory: The following are the types of memories which are treated
as primary.
Page 4 of 101
Programming for Problem Solving Riyaz Mohammed
ROM: It represents Read Only Memory that stores data and instructions even
when the computer is turned off. The Contents in the ROM cannot be modified
once if they are written. It is used to store the BIOS information.
RAM: It represents Random Access Memory that stores data and instructions
when the computer is turned on. The contents in the RAM can be modified
any no. of times by instructions. It is used to store the programs under
execution.
Magnetic Storage: The Magnetic Storage devices store information that can
be read, erased and rewritten a number of times. Example: Floppy Disks,
Hard Disks, Magnetic Tapes.
Optical Storage: The optical storage devices that use laser beams to read and
write stored data. Example: CD (Compact Disk), DVD (Digital Versatile Disk).
OPERATING SYSTEM
The OS helps you to communicate with the computer without knowing how
to speak the computer's language. It is not possible for the user to use any
computer or mobile device without having an operating system.
Page 5 of 101
Programming for Problem Solving Riyaz Mohammed
COMPILER
A compiler should comply with the syntax rule of that programming language
in which it is written. However, the compiler is only a program and cannot fix
errors found in that program. So, if you make a mistake, you need to make
changes in the syntax of your program. Otherwise, it will not compile.
Page 6 of 101
Programming for Problem Solving Riyaz Mohammed
Creating & Running Programs: 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. The following are the four steps in this process:
Page 7 of 101
Programming for Problem Solving Riyaz Mohammed
2) Compiling the Programs: The code in a source file stored on the disk must
be translated into machine language. This is the job of the compiler. The
Compiler is a computer program that translates the source code written in a
high-level language into the corresponding object code of the low-level
language. This translation process is called compilation.
Page 8 of 101
Programming for Problem Solving Riyaz Mohammed
INTRODUCTION TO ALGORITHMS
step 1: start
else
endif
step 5: stop
Page 9 of 101
Programming for Problem Solving Riyaz Mohammed
Symbols Used in Flowchart: Different symbols are used for different states
in flowchart, for example: Input/output and decision making has different
symbols. The table below describes all the symbols that are used in making
flowchart. The following are the standard symbols used in drawing flowcharts:
Page 10 of 101
Programming for Problem Solving Riyaz Mohammed
Examples:
Page 11 of 101
Programming for Problem Solving Riyaz Mohammed
Page 12 of 101
Programming for Problem Solving Riyaz Mohammed
Page 13 of 101
Programming for Problem Solving Riyaz Mohammed
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:
Expected Output:
Hello World!
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.
Page 14 of 101
Programming for Problem Solving Riyaz Mohammed
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.
DATA TYPES
A data type is used to indicate the type of value stored in a variable. A data
type indicates the following:
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.
i. 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.
Page 15 of 101
Programming for Problem Solving Riyaz Mohammed
Example:
ii. Unsigned Integers: Unsigned integers uses all 16 bits to store the
magnitude.
2) Floating point data types: These are used to store real numbers i.e.,
decimal point numbers or numbers with fractional values.
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.
Page 16 of 101
Programming for Problem Solving Riyaz Mohammed
OPERATORS
1) Arithmetic operators.
2) Relational operators.
3) Logical operators.
4) Assignment operators.
5) Increment and Decrement operators.
6) Conditional operators.
7) Bitwise operators.
8) Special operators.
1) Arithmetic Operators:
2) Relational operators:
Page 17 of 101
Programming for Problem Solving Riyaz Mohammed
3) Logical operators:
Syntax:
exp1?exp2:exp3;
7) Bitwise operators
8) Special operators:
ii. sizeof operator: It return the no. of bytes the operand occupies.
Page 18 of 101
Programming for Problem Solving Riyaz Mohammed
Eg: sizeof(operand)
EXPRESSIONS
Example: c=a+b*d;
Types of Expressions:
1) Postfix.
2) Prefix.
3) Unary.
4) Binary.
5) Ternary.
1) Postfix:
Page 19 of 101
Programming for Problem Solving Riyaz Mohammed
2) 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.
3) Unary:
4) Binary:
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
Page 20 of 101
Programming for Problem Solving Riyaz Mohammed
the operators of the same precedence are evaluated either from left to right or
from right to left depending upon the level. The following are the two distinct
levels of Arithmetic operators:
When an expression contains two operators of equal priority then the tie
between them is settled using the associativity of operators. Associativity are
of two types:
1) Left to Right.
2) 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.
Page 21 of 101
Programming for Problem Solving Riyaz Mohammed
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.
To fully define a variable one needs to mention not only its ‘type’ but also its
‘storage class’. In other words, not only do all variables have a data type, they
also have a ‘storage class’. A variable name identifies some physical location
within the computer where the string of bits representing the variable’s value
is stored. There are basically two kinds of locations in a computer where such
a value may be kept— Memory and CPU registers. It is the variable’s storage
class that determines in which of these two locations the value is stored.
Page 22 of 101
Programming for Problem Solving Riyaz Mohammed
Example Program
void main( )
auto int i;
clrscr();
printf("%d,i) ;
getch();
Page 23 of 101
Programming for Problem Solving Riyaz Mohammed
A value stored in a CPU register can always be accessed faster than the one
that is stored in memory. Therefore, if a variable is used at many places in a
program it is better to declare its storage class as register. A good example of
frequently used variables is loop counters. We can name their storage class
as register.
Example Program:
void main( )
register int i;
clrscr();
printf("%d",i);
getch();
Page 24 of 101
Programming for Problem Solving Riyaz Mohammed
Let us now compare the two programs and their output given below to
understand the difference between the automatic and static storage classes.
The above programs consist of two functions main( ) and increment( ). The
function increment( ) gets called from main( ) thrice. Each time it increments
the value of i and prints it. The only difference in the two programs is that one
uses an auto storage class for variable i, whereas the other uses static storage
class.
Like auto variables, static variables are also local to the block in which they
are declared. The difference between them is that static variables don’t
disappear when the function is no longer active. Their values persist. If the
control comes back to the same function again the static variables have the
same values they had last time around.
Page 25 of 101
Programming for Problem Solving Riyaz Mohammed
4) External storage class: The features of a variable whose storage class has
been defined as external are as follows:
External variables differ from those we have already discussed in that their
scope is global, not local. External variables are declared outside all functions,
yet are available to all functions that care to use them.
Example Program:
int x = 21;
void main( )
extern int y ;
int y = 31;
Here, x and y both are global variables. Since both of them have been defined
outside all the functions both enjoy external storage class. Note the difference
between the following:
extern int y;
int y = 31;
Here the first statement is a declaration, whereas the second is the definition.
When we declare a variable no space is reserved for it, whereas, when we
define it space gets reserved for it in memory. We had to declare y since it is
Page 26 of 101
Programming for Problem Solving Riyaz Mohammed
being used in printf( ) before it’s definition is encountered. There was no need
to declare x since its definition is done before its usage.
Also remember that a variable can be declared several times but can be
defined only once.
TYPE CONVERSION
Page 27 of 101
Programming for Problem Solving Riyaz Mohammed
BITWISE OPERATIONS
Bitwise operators are special types of operators that are used in programming
the processor. In processor, mathematical operations like: addition,
subtraction, addition and 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.
The above operators can be grouped in to the following two major categories:
i. 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.
Page 28 of 101
Programming for Problem Solving Riyaz Mohammed
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
Page 29 of 101
Programming for Problem Solving Riyaz Mohammed
Example Program
#include <stdio.h>
void main()
int a=12,b=25;
printf("Output=%d",a|b);
getch();
Expected Output
Output=29
iii. 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 ^.
Page 30 of 101
Programming for Problem Solving Riyaz Mohammed
Example Program:
#include <stdio.h>
void main()
int a=12,b=25;
printf("Output=%d",a^b);
getch();
Expected Output:
Output=21
i. 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
>>.
Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.
Page 31 of 101
Programming for Problem Solving Riyaz Mohammed
ii. Left Shift Operator (>>): The left shift operator will shift the bits towards
left for the given number of times.
Let’s take the binary representation of 2 assuming int is 1 byte for simplicity.
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++)
Page 32 of 101
Programming for Problem Solving Riyaz Mohammed
printf("\n");
for (i=0;i<=2;i++)
getch();
Expected Output:
Right Shift by 2: 53
Page 33 of 101
Programming for Problem Solving Riyaz Mohammed
1) Simple if.
2) if else.
3) Nested if.
1) Simple if:
Syntax:
if(condition)
statement1;
2) if else:
Syntax:
if(condition)
statement1;
else
statement2;
Page 34 of 101
Programming for Problem Solving Riyaz Mohammed
3) 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.
Page 35 of 101
Programming for Problem Solving Riyaz Mohammed
1) else if ladder.
2) Switch.
1) else if ladder:
Syntax:
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
else
statement-n;
2) Switch: A switch statement is used to select from more than one choice in
program.
Page 36 of 101
Programming for Problem Solving Riyaz Mohammed
Syntax:
switch(expression)
case value1:
statement-1;
break;
case value-2;
statement-2;
break;
default:
statement-n;
Page 37 of 101
Programming for Problem Solving Riyaz Mohammed
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.
Page 38 of 101
Programming for Problem Solving Riyaz Mohammed
Page 39 of 101
Programming for Problem Solving Riyaz Mohammed
(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);
Page 40 of 101
Programming for Problem Solving Riyaz Mohammed
Looping Applications:
Page 41 of 101
Programming for Problem Solving Riyaz Mohammed
FORMATTED I/O
The functions printf( ) and scanf( ) perform formatted output and input— that
is, they can read and write data in various formats that are under your
control.
The scanf( ) function, its complement, reads data from the keyboard.
Both functions can operate on any of the built-in data types, plus null-
terminated character strings.
1) printf()
2) scanf()
3) printf(): This function is used to print result on the monitor.
Syntax:
printf(“control string”,arg1,arg2,….,argn);
Page 42 of 101
Programming for Problem Solving Riyaz Mohammed
Examples:
printf(“%d”,a);
printf(“%d%c”,num,ch);
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);
*****
Page 43 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – II
ARRAYS
main( )
int x ;
x=5;
x = 10 ;
Page 44 of 101
Programming for Problem Solving Riyaz Mohammed
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.
Syntax:
Data-type array-name[Size];
type var_name[size];
Like other variables, arrays must be explicitly declared so that the compiler
can allocate space for them in memory. Here, type declares the base type of
the array, which is the type of each element in the array, and size defines how
many elements the array will hold.
For example, to declare a 100- element array called balance of type float, use
this statement: float balance[100];
Example:
int a[5];
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.
Page 45 of 101
Programming for Problem Solving Riyaz Mohammed
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
or
int a[]={2,4,6,8,10};
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
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
int a[5]={2,4,6,8,10};
Page 46 of 101
Programming for Problem Solving Riyaz Mohammed
clrscr();
printf("\nFirst element=%d",a[0]);
printf("\nFifth element=%d",a[4]);
getch();
Expected Output:
First element=2
Fifth element=10
TWO-DIMENSIONAL ARRAYS
Two dimensional arrays are often expressed and analyzed as matrix of rows
and columns.
Syntax:
Example:
Page 47 of 101
Programming for Problem Solving Riyaz Mohammed
The array arrangement shown in matrix form is only conceptually true. This
is because memory doesn’t contain rows and columns.
Memory Representation:
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
int a[3][2]={{2,4},{6,8},{10,12}},i,j;
clrscr();
for(i=0;i<3;i++)
for(j=0;j<2;j++)
printf("\n%d",a[i][j]);
Page 48 of 101
Programming for Problem Solving Riyaz Mohammed
getch();
10
12
Once an array is declared, the individual elements of the array can be referred
by the use of subscript. Subscript specifies the element position in the array.
Subscript starts at 0. i.e. first number is started at position 0, second number
is started at position 1 etc.
sum=0;
Page 49 of 101
Programming for Problem Solving Riyaz Mohammed
STRINGS
String Taxonomy:
Delimited Strings:
When you declare the string, you should ensure that you should have
sufficient room for the null character.
Page 50 of 101
Programming for Problem Solving Riyaz Mohammed
Defining Strings:
Memory for strings must be allocated before the string can be used.
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
Page 51 of 101
Programming for Problem Solving Riyaz Mohammed
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.
Example Program:
#include<stdio.h>
#include<conio.h>
Page 52 of 101
Programming for Problem Solving Riyaz Mohammed
void main()
char str[]="Computer";
int l;
clrscr();
l=strlen(str);
printf("\nLength=%d",l);
getch();
Expected Output:
Length=8
2) 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.
3) 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 “Computer Science”.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
char *str;
clrscr();
strcpy(str,str1);
Page 53 of 101
Programming for Problem Solving Riyaz Mohammed
strcat(str,str2);
printf("\n%s",str); // or puts(str);
getch();
Expected Output:
Computer Science
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
nonmatching pairs of characters.
Example Program:
//strcmp
#include<stdio.h>
#include<conio.h>
void main()
char *str1,*str2;
int res;
clrscr();
printf("\nEnter string1:");
gets(str1);
printf("\nEnter string2:");
gets(str2);
res=strcmp(str1,str2);
Page 54 of 101
Programming for Problem Solving Riyaz Mohammed
if(res==0)
else
getch();
Expected Output:
Enter string1:Computer
Enter string2:Computer
STRUCTURES
Syntax:
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};
Page 55 of 101
Programming for Problem Solving Riyaz Mohammed
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 ;
float price ;
int pages ;
};
Page 56 of 101
Programming for Problem Solving Riyaz Mohammed
(or)
struct book
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
INITIALIZING 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 ;
};
Example Program:
void main()
struct book
char name ;
Page 57 of 101
Programming for Problem Solving Riyaz Mohammed
float price ;
int pages ;
};
clrscr();
getch();
Expected Output:
Name=B
Price=130.00
Pages=550
UNIONS
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.
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:
Page 58 of 101
Programming for Problem Solving Riyaz Mohammed
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:
int rno;
char grade;
};
int rno;
char grade;
};
void main()
union student2 u;
clrscr();
Page 59 of 101
Programming for Problem Solving Riyaz Mohammed
printf("\nRollno=%d",s.rno);
printf("\nGrade=%c",s.grade);
printf("\nRollno=%d",u.rno);
printf("\nGrade=%c",u.grade);
getch();
Expected Output:
Rollno=25
Grade=A
Rollno=50
Grade=B
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.
ARRAY OF STRUCTURES
If we want to store data of 100 books we would be required to use 100 different
structure variables from b1 to b100, which is definitely not very convenient.
A better approach would be to use an array of structures. The syntax we use
to reference each element of the array b is similar to the syntax used for arrays
of ints and chars. For example, we refer to zeroth book’s price as b[0].price.
Similarly, we refer first book’s pages as b[1].pages.
Page 60 of 101
Programming for Problem Solving Riyaz Mohammed
Example Program:
//Array of structures
struct student
int rno;
char name[20];
};
void main()
int i;
clrscr();
printf("\n***Students Details***");
for(i=0;i<2;i++)
printf("\n-----------------\n");
getch();
Expected Output:
***Students Details***
Roll no=25
Name=Ritchie
-----------------
Roll no=20
Page 61 of 101
Programming for Problem Solving Riyaz Mohammed
Name=Babbage
POINTERS
(Or)
A pointer is memory variable that stores a memory address. Pointer can have
any name that is legal for other variable and it is declared in the same fashion
like other variable but it is always denoted by “*” operator.
Syntax:
Data-type *variable;
Example:
int *i;
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
int a=10,*ptr;
clrscr();
getch();
Page 62 of 101
Programming for Problem Solving Riyaz Mohammed
Expected Output:
Address of a is 65524
Value of a is 10
Advantages of pointers:
POINTERS TO ARRAYS
p1 = str;
Here, p1 has been set to the address of the first array element in str. To access
the fifth element in str, you could write
str[4]
or
*(p1+4)
Both statements will return the fifth element. Remember, arrays start at 0. To
access the fifth element, you must use 4 to index str. You also add 4 to the
pointer p1 to access the fifth element because p1 currently points to the first
element of str. (Recall that an array name without an index returns the
starting address of the array, which is the address of the first element.)
Page 63 of 101
Programming for Problem Solving Riyaz Mohammed
Example Program:
Page 64 of 101
Programming for Problem Solving Riyaz Mohammed
POINTERS TO STRUCTURES
//Pointer to structure
void main()
struct student
char name[20];
int rno;
float per;
};
getch();
Expected Output:
Name:Taufeeq
Rollno:25
Percentage:71.00
Page 65 of 101
Programming for Problem Solving Riyaz Mohammed
We can’t use ptr.name or ptr.rno because ptr is not a structure variable but
a pointer to a structure, and the dot operator requires a structure variable on
its left.
Self Referential structures are those structures that have one or more pointers
which point to the same type of structure, as their member.
Example:
struct node {
int data1;
char data2;
};
int main()
Page 66 of 101
Programming for Problem Solving Riyaz Mohammed
return 0;
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:
Example Program 1
Page 67 of 101
Programming for Problem Solving Riyaz Mohammed
Expected Output:
CSE=5
ECE=4
EEE=2
*****
Page 68 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – III
PREPROCESSOR
Example Program:
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main(){
clrscr() ;
scanf("%ld",&radius);
Page 69 of 101
Programming for Problem Solving Riyaz Mohammed
area = PI * SQR(radius) ;
printf("area = %ld",area);
getch();
Output:
2) #undef: #undef is used to destroy a macro that was already created using
#define.
3) #ifdef: #ifdef returns TRUE if the macro is defined and returns FALSE if
the macro is not defined.
5) #if: #if uses the value of specified macro for conditional compilation.
In C programming language, there are some pre-defined macros and they are
as follows...
Page 70 of 101
Programming for Problem Solving Riyaz Mohammed
FILES
File is a collection of data that stored on secondary memory like hard disk of
a computer. Generally, a file is used to store user data in a computer. In other
words, computer stores the data using files.
C programming language supports two types of files and they are as follows:
1) Text File (or) ASCII File: The file that contains ASCII codes of data like
digits, alphabets and symbols is called text file (or) ASCII file.
2) Binary File: The file that contains data in the form of bytes (0's and 1's) is
called as binary file.
FILE OPERATIONS IN C
1) Creating (or) Opening a file: To create a new file or open an existing file,
we need to create a file pointer of FILE type. Following is the sample code for
creating file pointer.
File *f_ptr ;
File *f_ptr ;
Page 71 of 101
Programming for Problem Solving Riyaz Mohammed
The above example code creates a new file called abc.txt if it does not exists
otherwise it is opened in writing mode.
2) Reading from a file: The reading from a file operation is performed using
the following pre-defined file handling methods:
i. getc()
ii. getw()
iii. fscanf()
iv. fgets()
v. fread()
3) Writing into a file: The writing into a file operation is performed using the
following pre-defined file handling methods:
i. putc()
ii. putw()
iii. fprintf()
iv. fputs()
v. fwrite()
Page 72 of 101
Programming for Problem Solving Riyaz Mohammed
fclose( *f_ptr )
The method fclose() returns '0'on success of file close otherwise it returns EOF
(End Of File).
*****
Page 73 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – IV
FUNCTIONS
Page 74 of 101
Programming for Problem Solving Riyaz Mohammed
Examples:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
float n,res;
clrscr();
scanf("%f",&n);
res=sqrt(n);
printf("\nSquare root=%f",res);
getch();
Expected Output:
Square root=5.000000
2) 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)
Page 75 of 101
Programming for Problem Solving Riyaz Mohammed
local variables;
statements;
Advantages of functions:
Example Program:
#include<stdio.h>
#include<conio.h>
printf("\nI am fine!");
void main()
clrscr();
printf("\nHow r u?");
Page 76 of 101
Programming for Problem Solving Riyaz Mohammed
getch();
Expected Output:
How r u?
I am fine!
There are two ways in which we can pass the parameters to the function:
1) Call by value.
2) Call by reference.
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>
int z;
z=x;
x=y;
Page 77 of 101
Programming for Problem Solving Riyaz Mohammed
y=z;
void main()
int a=10,b=20;
clrscr();
getch();
Expected Output:
Example Program:
//call by reference
#include<stdio.h>
#include<conio.h>
Page 78 of 101
Programming for Problem Solving Riyaz Mohammed
int *z;
*z=*x;
*x=*y;
*y=*z;
void main()
int a=10,b=20;
clrscr();
getch();
Expected Output:
RECURSION
Page 79 of 101
Programming for Problem Solving Riyaz Mohammed
1) Direct recursion.
2) Indirect recursion.
1) Directive recursion: The direct recursion function calls itself till the
condition is true.
Example Program:
int fact(int n)
int f;
if(n==0 || n==1)
return(1);
return(f);
void main()
int n,res;
clrscr();
n=5;
res=fact(n);
printf("\nFactorial=%d",res);
Page 80 of 101
Programming for Problem Solving Riyaz Mohammed
getch();
Expected Output:
Factorial=120
#include<stdio.h>
#include<conio.h>
void main()
long int f;
int n;
clrscr();
scanf("%d",&n);
f=fact(n);
getch();
return(1);
else
Page 81 of 101
Programming for Problem Solving Riyaz Mohammed
m=x*fact(x-1);
return(m);
#include<stdio.h>
#include<conio.h>
int fib(int);
void main()
int i, n;
clrscr();
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d", fib(i));
getch();
int fib(int x)
if(x==1|| x==2)
return(x-1);
Page 82 of 101
Programming for Problem Solving Riyaz Mohammed
else
return(fib(x-1)+fib(x-2));
MEMORY ALLOCATION
Page 83 of 101
Programming for Problem Solving Riyaz Mohammed
Note: If the memory allocation is success it returns the starting address else
it returns the NULL.
#include<stdio.h>
#include<conio.h>
void main()
int *a,i,n,sum=0;
scanf("%d",&n);
a=(int *)malloc(n*size(int));
if(a!=NULL)
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sum=sum+a[i];
else
Page 84 of 101
Programming for Problem Solving Riyaz Mohammed
getch();
ii. The calloc ( ) function: This function is used to allocate multiple blocks
of contiguous memory in bytes. All the blocks are of same size.
X=realloc(y, 30);
The first statement allocated memory space of size 50 bytes and returns the
starting address of the memory through the pointer x. the second statement
reallocates (decreases) the already allocated space to 30 bytes.
iv. The free ( ) function: The free ( ) function is used to free (release or de
allocate) the block of unused or already used memory.
Page 85 of 101
Programming for Problem Solving Riyaz Mohammed
free (x);
The first statement allocated memory space of 50 bytes and returns the
starting address of the allocated memory through a pointer variable x. The
second statement frees the allocated memory
*****
Page 86 of 101
Programming for Problem Solving Riyaz Mohammed
UNIT – V
INTRODUCTION TO ALGORITHMS
3. If (d < 0)
Display "Roots are Imaginary, calculater1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/
2a.
else if (d = 0)
else
#include <stdio.h>
#include <math.h>
int main()
discriminant = b*b-4*a*c;
if (discriminant > 0)
Page 87 of 101
Programming for Problem Solving Riyaz Mohammed
root1 = (-b+sqrt(discriminant))/(2*a);
root2 = (-b-sqrt(discriminant))/(2*a);
else if (discriminant == 0)
else
realPart = -b/(2*a);
imaginaryPart = sqrt(-discriminant)/(2*a);
imaginaryPart);
return 0;
Output:
Page 88 of 101
Programming for Problem Solving Riyaz Mohammed
Iterate through array to find maximum and minimum element in array. Run
loop from first to last array element i.e. 0 to size - 1. Loop structure should
look like for(i=0; i<size; i++).
Inside loop for each array element check for maximum and minimum. Assign
current array element to max, if (arr[i] > max). Assign current array element
to min if it is less than min i.e. perform min = arr[i] if (arr[i] < min).
include <stdio.h>
int main()
int arr[MAX_SIZE];
scanf("%d", &size);
Page 89 of 101
Programming for Problem Solving Riyaz Mohammed
scanf("%d", &arr[i]);
max = arr[0];
min = arr[0];
max = arr[i];
min = arr[i];
return 0;
Page 90 of 101
Programming for Problem Solving Riyaz Mohammed
Output:
START
STOP
#include <stdio.h>
int main() {
int n, i, flag = 0;
scanf("%d", &n);
if (n % i == 0) {
flag = 1;
break;
Page 91 of 101
Programming for Problem Solving Riyaz Mohammed
if (n == 1)
else
if (flag == 0)
else
return 0;
Output:
29 is a prime number.
Page 92 of 101
Programming for Problem Solving Riyaz Mohammed
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:
#include<stdio.h>
#include<conio.h>
void main()
int a[10],i,n,x;
clrscr();
printf("\nEnter n:");
scanf("%d",&n);
printf("\nEnter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&x);
Page 93 of 101
Programming for Problem Solving Riyaz Mohammed
getch();
int i,flag;
for(i=0;i<n;i++)
if(b[i]==x)
flag=1;
break;
if(flag==1)
printf("\nElement found!");
else
Expected Output:
Enter n:3
Enter 3 elements:
10
25
50
Element found!
Page 94 of 101
Programming for Problem Solving Riyaz Mohammed
Pass-1:
Pass-2:
Page 95 of 101
Programming for Problem Solving Riyaz Mohammed
Pass-3
Pass-4
Page 96 of 101
Programming for Problem Solving Riyaz Mohammed
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so
we're keeping it short and precise.
Bubble sort starts with very first two elements, comparing them to check
which one is greater.
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
We know then that 10 is smaller 35. Hence they are not sorted.
Page 97 of 101
Programming for Problem Solving Riyaz Mohammed
We swap these values. We find that we have reached the end of the array.
After one iteration, the array should look like this
To be precise, we are now showing how an array should look like after each
iteration. After the second iteration, it should look like this
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is
completely sorted.
Page 98 of 101
Programming for Problem Solving Riyaz Mohammed
It finds that both 14 and 33 are already in ascending order. For now, 14 is in
sorted sub-list.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list.
Here we see that the sorted sub-list has only one element 14, and 27 is greater
than 14. Hence, the sorted sublist remains sorted after swapping.
So we swap them.
Page 99 of 101
Programming for Problem Solving Riyaz Mohammed
We swap them again. By the end of third iteration, we have a sorted sub-list
of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-
list.
For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is stored presently, we search the whole list and
find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the
minimum value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of
the list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at
the second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a
sorted manner.
The same process is applied to the rest of the items in the array.