0% found this document useful (0 votes)
2K views101 pages

My Notes PPS

The document outlines the syllabus for a programming course. It covers 5 units: (1) introduction to programming concepts, algorithms, and C language basics; (2) arrays, strings, structures, and pointers; (3) preprocessors and file handling; (4) functions and dynamic memory allocation; and (5) algorithms and complexity analysis. Each unit covers common data structures, programming concepts, and techniques relevant to problem solving using C programming.

Uploaded by

Shaik Ansar
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)
2K views101 pages

My Notes PPS

The document outlines the syllabus for a programming course. It covers 5 units: (1) introduction to programming concepts, algorithms, and C language basics; (2) arrays, strings, structures, and pointers; (3) preprocessors and file handling; (4) functions and dynamic memory allocation; and (5) algorithms and complexity analysis. Each unit covers common data structures, programming concepts, and techniques relevant to problem solving using C programming.

Uploaded by

Shaik Ansar
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/ 101

Programming for Problem Solving Riyaz Mohammed

JNTU HYDERABAD

PROGRAMMING FOR PROBLEM SOLVING

B.TECH./COMMON TO ALL BRANCHES/R18

SYLLABUS

UNIT – I

Introduction to Programming: Introduction to components of a computer


system: disks, primary and secondary memory, processor, operating system,
compilers, creating, compiling and executing a program etc., Number
systems.

Introduction to Algorithms: steps to solve logical and numerical problems.


Representation of Algorithm, Flowchart/Pseudo code with examples, Program
design and structured programming.

Introduction to C Programming Language: variables (with data types and


space requirements), Syntax and Logical Errors in compilation, object and
executable code, Operators, expressions and precedence, Expression
evaluation, Storage classes (auto, extern, static and register), type conversion,
The main method and command line arguments.

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

Arrays, Strings, Structures and Pointers

Arrays: one and two-dimensional arrays, creating, accessing and


manipulating elements of arrays.

Page 1 of 101
Programming for Problem Solving Riyaz Mohammed

Strings: Introduction to strings, handling strings as array of characters, basic


string functions available in C (strlen, strcat, strcpy, strstr etc.), arrays of
strings.

Structures: Defining structures, initializing structures, unions, Array of


structures.

Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and


Structures, Use of Pointers in selfreferential structures, usage of
selfreferential structures in linked list (no implementation) Enumeration data
type.

UNIT – III

Preprocessor and File handling in C

Preprocessor: Commonly used Preprocessor commands like include, define,


undef, if, ifdef, ifndef.

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

Function and Dynamic Memory Allocation

Functions: Designing structured programs, Declaring a function, Signature


of a function, Parameters and return type of a function, passing parameters
to functions, call by value, Passing arrays to functions, passing pointers to
functions, idea of call by reference, Some C standard functions and libraries.

Recursion: Simple programs, such as Finding Factorial, Fibonacci series etc.,


Limitations of Recursive functions.

Dynamic memory allocation: Allocating and freeing memory, Allocating


memory for arrays of different data types.

Page 2 of 101
Programming for Problem Solving Riyaz Mohammed

UNIT – V

Introduction to Algorithms: Algorithms for finding roots of a quadratic


equations, finding minimum and maximum numbers of a given set, finding if
a number is prime number, etc.

Basic searching in an array of elements (linear and binary search techniques),


Basic algorithms to sort array of elements (Bubble, Insertion and Selection
sort algorithms), Basic concept of order of complexity through the example
programs.

*****

Page 3 of 101
Programming for Problem Solving Riyaz Mohammed

UNIT – I

INTRODUCTION TO COMPONENTS OF A COMPUTER SYSTEM

Computer Systems: “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.”

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.

Cache memory: It is used to store the data and instructions referred by


processor.

Secondary Memory: The following are the different kinds of memories.

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

An operating system is a software which acts as an interface between the end


user and computer hardware. Every computer must have at least one OS to
run other programs. An application like Chrome, MS Word, Games, etc needs
some environment in which it will run and perform its task.

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

Types of Operating Systems:

1) Single user Operating systems: A single-user operating system is a


system in which only one user can access the computer system at a
time.
2) Multiuser Operating systems: A multi-user operating system allows
more than one user to access a computer system at one time.
3) Distributed Operating systems: A distributed operating system is a
software over a collection of independent, networked, communicating,
and physically separate computational nodes. They handle jobs which
are serviced by multiple CPUs.

COMPILER

A compiler is a computer program that transforms code written in a high-level


programming language into the machine code. It is a program which
translates the human readable code to a language a computer processor
understands (binary 1 and 0 bits). The computer processes the machine code
to perform the corresponding tasks.

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

Conclusion of Compiler vs Interpreter:

1) A compiler is a computer program which transforms code written in a


high-level programming language into the machine code.
2) An interpreter is a computer program, which coverts each high-level
program statement into the machine code.
3) Compliers generates intermediate machine code that is saved to the
computer as an exe.
4) Interpreter never generates any intermediate machine code.
5) The interpreter converts the source code line-by-line during RUN Time.
6) The compiler needs a lot of time analyzing and processing the program.
7) Interpreter spends less time on analyzing and processing a program.

CREATING, COMPILING & EXECUTING A PROGRAM ETC

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:

1) Writing and Editing the program.


2) Compiling the program.
3) Linking the program with the required modules.
4) Executing the program.

Page 7 of 101
Programming for Problem Solving Riyaz Mohammed

1) Writing and Editing Programs: The software used to write programs is


known as a text editor. A text editor helps us enter, change and store
character data. Once we write the program in the text editor we save it using
a filename stored with an extension of C. This file is referred as source code
file.

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.

3) Linking Programs: The Linker assembles all functions, the programs


functions and system functions into one executable program.

4) Executing Programs: To execute a program we use an operating system


command, such as run, to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating system
program known as the loader. It locates the executable program and reads it
into memory. When everything is loaded the program takes control and it
begin execution.

Page 8 of 101
Programming for Problem Solving Riyaz Mohammed

INTRODUCTION TO ALGORITHMS

Algorithm is a finite sequence of instructions, each of which has a clear


meaning and can be performed with a finite amount of effort in a finite length
of time. No matter what the input values may be, an algorithm terminates
after executing a finite number of instructions.

We represent an algorithm using a pseudo language that is a combination of


the constructs of a programming language together with informal English
statements. The ordered set of instructions required to solve a problem is
known as an algorithm.

The characteristics/properties of a good algorithm are:

1) Precision: the steps are precisely stated (defined).


2) Uniqueness: results of each step are uniquely defined and only depend
on the input and the result of the preceding steps.
3) Finiteness: the algorithm stops after a finite number of instructions
are executed.
4) Input: the algorithm receives input.
5) Output: the algorithm produces output.
6) Generality: the algorithm applies to a set of inputs.

Example: Write a algorithm to find out number is odd or even?

step 1: start

step 2: input number

step 3: rem=number mod 2

step 4: if rem=0 then

print "number even"

else

print "number odd"

endif

step 5: stop

Page 9 of 101
Programming for Problem Solving Riyaz Mohammed

FLOWCHART/PSEUDO CODE WITH EXAMPLES

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. Flowchart is very helpful in writing program and
explaining program to others.

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:

1) Draw a Flowchart to determine whether the number is even or odd:

2) Draw a flowchart to add two numbers entered by user

Page 11 of 101
Programming for Problem Solving Riyaz Mohammed

3) Draw flowchart to find the largest among three different numbers


entered by user

Page 12 of 101
Programming for Problem Solving Riyaz Mohammed

STRUCTURED PROGRAMMING CONCEPT

Structured programming (sometimes known as modular programming) is a


subset of procedural programming that enforces a logical structure on the
program being written to make it more efficient and easier to understand and
modify. Certain languages such as Ada, Pascal, and dBASE are designed with
features that encourage or enforce a logical program structure.

Structured programming frequently employs a top-down design model, in


which developers map out the overall program structure into separate
subsections. A defined function or set of similar functions is coded in a
separate module or submodule, which means that code can be loaded into
memory more efficiently and that modules can be reused in other programs.
After a module has been tested individually, it is then integrated with other
modules into the overall program structure.

Almost any language can use structured programming techniques to avoid


common pitfalls of unstructured languages. Unstructured programming must
rely upon the discipline of the developer to avoid structural problems, and as
a consequence may result in poorly organized programs. Most modern
procedural languages include features that encourage structured
programming. Object-oriented programming (OOP) can be thought of as a type
of structured programming, uses structured programming techniques for
program flow, and adds more structure for data to the model.

INTRODUCTION TO C PROGRAMMING 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.

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:

Our First 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) Type of value stored in a variable.


2) Memory allocated for data value.
3) 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.

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

1-> Negative number

0-> Positive number

Example:

signed int x=10;

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

Operators are C tokens which can join together individual constants,


variables, array elements etc.

C operators are classified into the following categories:

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:

4) Assignment operators: It is used to assign the result of an expression to


a variable. It is denoted as =

5) Increment and Decrement operators:

6) 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.

7) Bitwise operators

8) 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.

Page 18 of 101
Programming for Problem Solving Riyaz Mohammed

Eg: sizeof(operand)

EXPRESSIONS

An expression consists 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:

1) It consists of four operands namely a,b,c,d.


2) It also consists of three operators =,+,*
3) The result of the expression is assigned to a variable c.

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:

PRECEDENCE & 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

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:

1) High priority arithmetic operators are *,/,%


2) Low priority arithmetic operators are +, -

If parenthesis is used then expression within the parenthesis is evaluated


first.

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

EXPRESSION EVALUATION [OR] 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.

STORAGE CLASSES (AUTO, EXTERN, STATIC AND REGISTER)

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.

A variable’s storage class tells us:

1) Where the variable would be stored?


2) What will be the initial value of the variable, if initial value is not
specifically assigned? (i.e., the default initial value).
3) What is the scope of the variable; i.e., in which functions the value of
the variable would be available?
4) What is the life of the variable; i.e., how long would the variable exist?

Page 22 of 101
Programming for Problem Solving Riyaz Mohammed

There are four storage classes in C:

1) Automatic storage class.


2) Register storage class.
3) Static storage class.
4) External storage class.

1) Automatic storage class: The features of a variable defined to have an


automatic storage class are as under:

Example Program

void main( )

auto int i;

clrscr();

printf("%d,i) ;

getch();

The above program shows how an automatic storage class variable is


declared, and the fact that if the variable is not initialized it contains a garbage
value.

2) Register storage class: The features of a variable defined to be of register


storage class are as under:

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

Here, even though we have declared the storage class of i as register, we


cannot say for sure that the value of i would be stored in a CPU register. Why?
Because the number of CPU registers are limited, and they may be busy doing
some other task. What happens in such an event... the variable works as if
its storage class is auto.

3) Static storage class: The features of a variable defined to have a static


storage class are as under:

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 ;

printf ( "\n%d %d", x, 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

Type conversion is classified in to two types:

1) Implicit Type Conversion.


2) Explicit Type Conversion (Casting).

1) 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.

2) 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.

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.

C language supports the following bitwise operators.

The above operators can be grouped in to the following two major categories:

1) Logical bitwise operators.


2) Shift operators.

1) Logical Bitwise Operators:

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

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

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

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

iv. 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 ~.

2) Shift Operators: There are two shift operators in C programming: Right


shift operator and Left shift operator.

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

Example: int a=8>>1;

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.

Example: int a=2<<1;

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("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

IF, IF-ELSE, SWITCH-CASE, TERNARY OPERATOR, GOTO, ITERATION


WITH FOR, WHILE, DO-WHILE LOOPS

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:

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;

If the condition is TRUE then statement1 is executed otherwise statement2 is


will be executed.

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.

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.

Page 35 of 101
Programming for Problem Solving Riyaz Mohammed

The following are the two types of Multiway selection statements:

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

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.

Page 39 of 101
Programming for Problem Solving Riyaz Mohammed

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

Page 40 of 101
Programming for Problem Solving Riyaz Mohammed

Comparing while and do while loops:

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 printf( ) function writes data to the console.

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.

The following are the two types of formatted I/O functions:

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

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

*****

Page 43 of 101
Programming for Problem Solving Riyaz Mohammed

UNIT – II

ARRAYS, STRINGS, STRUCTURES AND POINTERS

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

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

ONE DIMENSIONAL ARRAYS

The general form for declaring a one-dimensional array is

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

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

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

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

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.

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

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

Page 47 of 101
Programming for Problem Solving Riyaz Mohammed

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:

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

Page 48 of 101
Programming for Problem Solving Riyaz Mohammed

getch();

Expected Output: The array elements are

10

12

ACCESSING ELEMENTS OF AN ARRAY

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.

Entering data into an array:

int num [10];

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

Printf (“enter a number”);

Scanf (“%d”, & num [i]);

Reading data from an array:

To add the elements of an array to variable sum

sum=0;

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

sum = sum + a [i];

Page 49 of 101
Programming for Problem Solving Riyaz Mohammed

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.

Page 50 of 101
Programming for Problem Solving Riyaz Mohammed

A string literal is enclosed in double quotes.

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

Page 51 of 101
Programming for Problem Solving Riyaz Mohammed

BASIC STRING FUNCTIONS AVAILABLE IN C [OR] 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.

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

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:

//strcpy & strcat

#include<stdio.h>

#include<conio.h>

void main()

char *str;

char *str1="Computer",*str2=" Science";

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

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

printf("\nStrings are equal");

else

printf("\nStrings are not equal");

getch();

Expected Output:

Enter string1:Computer

Enter string2:Computer

Strings are equal

STRUCTURES

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 ;

......

......

};

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,

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 ;

float price ;

int pages ;

};

Page 56 of 101
Programming for Problem Solving Riyaz Mohammed

struct book b1, b2, b3 ;

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

};

struct book b1 = { "Basic", 130.00, 550 } ;

struct book b2 = { "Physics", 150.80, 800 } ;

Example Program:

void main()

struct book

char name ;

Page 57 of 101
Programming for Problem Solving Riyaz Mohammed

float price ;

int pages ;

};

struct book b1 = { 'B', 130.00, 550 } ;

clrscr();

printf ( "Name= %c", b1.name ) ;

printf ( "\nPrice = %f", b1.price ) ;

printf ( "\nPages = %d", b1.pages ) ;

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:

The syntax of union is similar to the structure which is shown below

union <union_ name>

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:

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

Page 59 of 101
Programming for Problem Solving Riyaz Mohammed

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

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.

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

struct student s[2]={{25,"Ritchie"},{20,"Babbage"}}; // structure array


initialization

int i;

clrscr();

printf("\n***Students Details***");

for(i=0;i<2;i++)

printf("\nRoll no=%d \nName=%s",s[i].rno,s[i].name);

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

“A Pointer is a variable that can store the address of another variable”.

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

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

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:

1) Pointers save the memory space.


2) Pointers are used to increase the speed of execution.
3) Pointers are used to reduce the length and complexity of a program.
4) Pointers are useful for representing two dimensional and multi
dimensional arrays.
5) The memory is accessed efficiently with the pointers.

POINTERS TO ARRAYS

There is a close relationship between pointers and arrays.

Consider this program fragment:

char str[80], *p1;

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

The way we can have a pointer pointing to an int, or a pointer pointing to a


char, similarly we can have a pointer pointing to a struct.

Such pointers are known as „structure pointers‟.

//Pointer to structure

void main()

struct student

char name[20];

int rno;

float per;

};

struct student s={"Taufeeq",25,71.00};

struct student *ptr;

ptr=&s; // pointer “ptr” pointing to structure variable “s”

printf("\nName:%s \nRollno:%d \nPercentage:%.2f",ptr->name,ptr->rno,ptr-


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

In such cases C provides an operator ->, called an arrow operator to refer to


the structure elements. Remember that on the left hand side of the ‘.’
structure operator, there must always be a structure variable, whereas on the
left hand side of the “->” operator there must always be a pointer to a
structure.

USE OF POINTERS IN SELFREFERENTIAL STRUCTURES

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;

struct node* link;

};

int main()

struct node ob;

Page 66 of 101
Programming for Problem Solving Riyaz Mohammed

return 0;

In the above example “link” is a pointer to a structure of type “node”.

Hence, the structure “node” is a self-referential structure with “link” as the


referencing pointer. An important point to consider is that the pointer should
be initialized properly before accessing, as by default it contains garbage
value.

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

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

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 AND FILE HANDLING IN C

PREPROCESSOR

In C programming language, preprocessor directive is a step performed before


the actual source code compilation. It is not part of the compilation.
Preprocessor directives in C programming language are used to define and
replace tokens in the text and also used to insert the contents of other files
into the source file.

When we try to compile a program, preprocessor commands are executed first


and then the program gets compiled.

Every preprocessor command begins with # symbol. We can also create


preprocessor commands with parameters.

COMMONLY USED PREPROCESSOR COMMANDS LIKE INCLUDE,


DEFINE, UNDEF, IF, IFDEF, IFNDEF

Following are the preprocessor commands in C programming language...

1) #define: #define is used to create symbolic constants (known as macros)


in C programming language. This preprocessor command can also be used
with parameterized macros.

Example Program:

#include<stdio.h>

#include<conio.h>

#define PI 3.14

#define SQR(x) x*x //Parameterized Macro

void main(){

double radius, area ;

clrscr() ;

printf("Enter the radius: ");

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.

4) #ifndef: #ifndef returns TRUE if the specified macro is not defined


otherwise returns FALSE.

5) #if: #if uses the value of specified macro for conditional compilation.

6) #else: #else is an alternative for #if.

7) #elif: #elif is a #else followed by #if in one statement.

8) #endif: #endif is used terminate preprocessor conditional macro.

9) #include: #include is used to insert specific header file into C program.

10) #error: #error is used to print error message on stderr.

11) #pragma: #pragma is used to issue a special command to the compiler.

In C programming language, there are some pre-defined macros and they are
as follows...

1) __ DATE __ : The current date as characters in "MMM DD YYYY" format.


2) __ TIME __ : The current time as characters in "HH : MM : SS" format.
3) __ FILE __ : This contains the current file name.
4) __ LINE __ : This contains the current line number.

Page 70 of 101
Programming for Problem Solving Riyaz Mohammed

5) __ STDC __ : Defines 1 when compiler compiles with ANSI Standards.

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.

TEXT AND BINARY FILES

C programming language supports two types of files and they are as follows:

1) Text Files (or) ASCII Files.


2) Binary Files.

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.

Generally, the binary files are compiled version of text files.

FILE OPERATIONS IN C

The following are the operations performed on files in c programming


language:

1) Creating (or) Opening a file.


2) Reading data from a file.
3) Writing data into a file.
4) Closing a file.

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 ;

We use the pre-defined method fopen() to create a new file or to open an


existing file. There are different modes in which a file can be opened. Consider
the following code...

File *f_ptr ;

Page 71 of 101
Programming for Problem Solving Riyaz Mohammed

*f_ptr = fopen("abc.txt", "w") ;

The above example code creates a new file called abc.txt if it does not exists
otherwise it is opened in writing mode.

In C programming language, there different modes are available to open a file


and they are shown in the following table.

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

4) Closing a file: Closing a file is performed using a pre-defined method


fclose().

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

FUNCTION AND DYNAMIC MEMORY ALLOCATION

FUNCTIONS

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

1) 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.

Page 74 of 101
Programming for Problem Solving Riyaz Mohammed

Examples:

printf(), scanf() etc.

Example Program: Write a C program to display the square root of a number.

#include<stdio.h>

#include<conio.h>

#include<math.h>

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

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:

1) A function provides modularity and readability to the software.


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

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

Page 76 of 101
Programming for Problem Solving Riyaz Mohammed

getch();

Expected Output:

How r u?

I am fine!

PASSING PARAMETERS/ARGUMENTS TO FUNCTIONS [OR] 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.

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

Page 77 of 101
Programming for Problem Solving Riyaz Mohammed

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

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

Page 78 of 101
Programming for Problem Solving Riyaz Mohammed

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

RECURSION

In C, it is possible for the functions to call themselves. A function is called


‘recursive’ if a statement within the body of a function calls the same function.
Thus recursion is the process of defining something in terms of itself.

Page 79 of 101
Programming for Problem Solving Riyaz Mohammed

Let us now see a simple example of recursion. Suppose we want to calculate


the factorial value of an integer. As we know, the factorial of a number is the
product of all the integers between 1 and that number.

The recursion can be:

1) Direct recursion.
2) Indirect recursion.

1) Directive recursion: The direct recursion function calls itself till the
condition is true.

2) Indirect recursion: In indirect recursion a function calls another function


then the called function calls the calling function

Example Program:

int fact(int n); // function prototype

int fact(int n)

int f;

if(n==0 || n==1)

return(1);

f=fact(n-1)*n; //fact() is recursive function

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

SIMPLE PROGRAMS: FINDING FACTORIAL, FIBONACCI SERIES ETC.

Example1: Write a C program to find the factorial of a given number using


recursion

#include<stdio.h>

#include<conio.h>

long int fact(int);

void main()

long int f;

int n;

clrscr();

printf("Enter the number");

scanf("%d",&n);

f=fact(n);

printf("The factorial of a given number is %ld", f);

getch();

long int fact(int x)

long int m; if(x==1|| x==0)

return(1);

else

Page 81 of 101
Programming for Problem Solving Riyaz Mohammed

m=x*fact(x-1);

return(m);

Output: Enter the number 5

The factorial of a given number is 120

Example 2: Write a C program to find the Fibonacci series using recursion

#include<stdio.h>

#include<conio.h>

int fib(int);

void main()

int i, n;

clrscr();

printf("Enter the number");

scanf("%d",&n);

printf("The fibnocci series is");

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

Output: Enter the number 5

The Fibonacci series is 0 1 1 2 3

MEMORY ALLOCATION

Memory allocations mean allocating sufficient memory space to all the


variables in the program. Memory space can be allocated in two ways. They
are:

1) Static memory allocation.


2) Dynamic memory allocation.

1) Static memory allocation: To allocating the memory at the time of


compilation, then it is said to be a static memory allocation.

2) Dynamic memory allocation: To allocating the memory at the time of


execution, then it is said to be dynamic memory allocation. In C language
there are 4 ways to allocating the memory:

i. The malloc( ) function.


ii. The calloc( ) function.
iii. The realloc( ) function.
iv. The free( ) function.

i. The malloc ( ) function: This is used to allocate a contiguous block of


memory in bytes.

Syntax: Pointer variable=(cast-type *) malloc(size);

Example: x=(int *)malloc(20);

x=(int *) malloc(10 *sizeof(int)); on execution of malloc, 10 times the size of an


int (ie., 10*2=20 bytes) is allocated and the starting address of the first byte
is assigned to pointer x of type int.

Page 83 of 101
Programming for Problem Solving Riyaz Mohammed

Where pointer-variable is a valid C variable already defined. Cast –type is the


type of the pointer returned by malloc ( ) such as int, char…etc. size is the
required size of memory in byte.

Note: If the memory allocation is success it returns the starting address else
it returns the NULL.

Example: Write a C program to perform sum of array elements by using


malloc( ) function

#include<stdio.h>

#include<conio.h>

void main()

int *a,i,n,sum=0;

printf("enter the size of array");

scanf("%d",&n);

a=(int *)malloc(n*size(int));

if(a!=NULL)

printf("enter the elements");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

sum=sum+a[i];

printf("sum of given elements are %d",sum);

else

printf("memory can not be allocated");

Page 84 of 101
Programming for Problem Solving Riyaz Mohammed

getch();

Output: Enter the size of the array 5

Enter the elements 1 2 3 4 5

Sum of given elements are 15

ii. The calloc ( ) function: This function is used to allocate multiple blocks
of contiguous memory in bytes. All the blocks are of same size.

Syntax: pointer-variable =(cast-type *) calloc(n, size);

Example: x=(int *) calloc(5,10);

Where pointer-variable is a valid C variable already defined. Cast-type is the


type of the pointer returned by calloc ( ) such as int, char ….etc. ‘n’ is the
number of blocks and size is the required size of memory in bytes. Note: If the
memory allocation is success it returns the starting address else it returns
NULL.

iii. The realloc ( ) function: The realloc () function is used to increase or


decrease the size of memory previously allocated by using malloc/calloc ()
function.

Syntax: new-pointer=realloc (old-pointer, new-size);

Where new-pointer is valid C variable previously defined. Old-pointer is the


pointer variable used in malloc( ) or calloc( ) function. New-size is the size of
the new memory needed.

Example: y= (int * )malloc(50);

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

Syntax: free (pointer-variable);

Where pointer-variable is a pointer to the memory block which has been


already created by malloc ( ) or calloc ( ) function.

Example: x= (int *) malloc (50);

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

FINDING ROOTS OF A QUADRATIC EQUATIONS

Algorithm to find all the roots of a quadratic equation:

1. Input the value of a, b, c.

2. Calculate k = b*b - 4*a*c

3. If (d < 0)

Display "Roots are Imaginary, calculater1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/
2a.

else if (d = 0)

Display "Roots are Equal" and calculate r1 = r2 = (-b / 2*a)

else

Display "Roots are real and calculate r1 = -b + ?d / 2*a andr2 = -b - ?d / 2*a

4. Print r1 and r2.

5. End the algorithm.

Program to find all the roots of a quadratic equation:

#include <stdio.h>

#include <math.h>

int main()

double a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

printf("Enter coefficients a, b and c: ");

scanf(“%lf %lf %lf”,&a, &b, &c);

discriminant = b*b-4*a*c;

// condition for real and different roots

if (discriminant > 0)

Page 87 of 101
Programming for Problem Solving Riyaz Mohammed

// sqrt() function returns square root

root1 = (-b+sqrt(discriminant))/(2*a);

root2 = (-b-sqrt(discriminant))/(2*a);

printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);

//condition for real and equal roots

else if (discriminant == 0)

root1 = root2 = -b/(2*a);

printf(“root1 = root2 = %.2lf;”, root1);

// if roots are not real

else

realPart = -b/(2*a);

imaginaryPart = sqrt(-discriminant)/(2*a);

printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart,


realPart,

imaginaryPart);

return 0;

Output:

Page 88 of 101
Programming for Problem Solving Riyaz Mohammed

FINDING MINIMUM AND MAXIMUM NUMBERS OF A GIVEN SET

Below is the step by step descriptive logic to find maximum or minimum in


array. Input size and element in array, store it in some variable say size and
arr. Declare two variables max and min to store maximum and minimum.
Assume first array element as maximum and minimum both, say max = arr[0]
and min = arr[0].

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

Program to find maximum and minimum element in array:

include <stdio.h>

#define MAX_SIZE 100 // Maximum array size

int main()

int arr[MAX_SIZE];

int i, max, min, size;

/* Input size of the array */

printf("Enter size of the array: ");

scanf("%d", &size);

/* Input array elements */

printf("Enter elements in the array: ");

Page 89 of 101
Programming for Problem Solving Riyaz Mohammed

for(i=0; i<size; i++)

scanf("%d", &arr[i]);

/* Assume first element as maximum and minimum */

max = arr[0];

min = arr[0];

/* Find maximum and minimum in all array elements. */

for(i=1; i<size; i++)

/* If current element is greater than max */

if(arr[i] > max)

max = arr[i];

/* If current element is smaller than min */

if(arr[i] < min)

min = arr[i];

/* Print maximum and minimum element */

printf("Maximum element = %d\n", max);

printf("Minimum element = %d", min);

return 0;

Page 90 of 101
Programming for Problem Solving Riyaz Mohammed

Output:

Enter size of the array: 10

Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10

Maximum element = 100

Minimum element = -10

FINDING IF A NUMBER IS PRIME NUMBER

Algorithm for finding if a number is prime number:

START

Step 1: Take integer variable A

Step 2: Divide the variable A with (A-1 to 2)

Step 3: If A is divisible by any value (A-1 to 2) it is not prime

Step 4: Else it is prime

STOP

Program to find if a number is prime number:

#include <stdio.h>

int main() {

int n, i, flag = 0;

printf("Enter a positive integer: ");

scanf("%d", &n);

for (i = 2; i <= n / 2; ++i)

// condition for non-prime

if (n % i == 0) {

flag = 1;

break;

Page 91 of 101
Programming for Problem Solving Riyaz Mohammed

if (n == 1)

printf("1 is neither prime nor composite.");

else

if (flag == 0)

printf("%d is a prime number.", n);

else

printf("%d is not a prime number.", n);

return 0;

Output:

Enter a positive integer: 29

29 is a prime number.

BASIC SEARCHING IN AN ARRAY OF ELEMENTS (LINEAR AND BINARY


SEARCH TECHNIQUES)

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

1) Linear Search or Sequential Search.


2) Binary Search.

1) Linear Search or Sequential 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

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:

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

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

Page 93 of 101
Programming for Problem Solving Riyaz Mohammed

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!

Page 94 of 101
Programming for Problem Solving Riyaz Mohammed

2) Binary Search: In binary search method, the key element is searched in


the following way:

i. The array is sorted.


ii. Locate the middle element of the array.
iii. Compare the value at that location with the search key.
iv. If they are equal - done!
v. Otherwise, decide which half of the array contains the search key.
vi. Repeat the search on that half of the array and ignore the other half.
vii. The search continues until the key is matched or no elements remain
to be searched.

Pass-1:

Pass-2:

Page 95 of 101
Programming for Problem Solving Riyaz Mohammed

Pass-3

Pass-4

BASIC ALGORITHMS TO SORT ARRAY OF ELEMENTS (BUBBLE,


INSERTION AND SELECTION SORT ALGORITHMS)

Sorting: Sorting refers to arranging data in a particular order or format.


Sorting algorithm specifies the way to arrange data in a particular order. The
importance of sorting lies in the fact that data searching can be optimized to
a very high level, if data is stored in a sorted manner. Sorting is also used to
represent data in more readable formats.

Following are some of the examples of sorting in real-life scenarios:

1) Telephone Directory: The telephone directory stores the telephone


numbers of people sorted by their names, so that the names can be
searched easily.
2) Dictionary: The dictionary stores words in an alphabetical order so
that searching of any word becomes easy.

Page 96 of 101
Programming for Problem Solving Riyaz Mohammed

1) Bubble Sort or Exchange Sort: Bubble sort is a simple sorting algorithm.


This sorting algorithm is comparison-based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they are not
in order. This algorithm is not suitable for large data sets.

How Bubble Sort Works?

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.

In this case, value 33 is greater than 14, so it is already in sorted locations.


Next, we compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.

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.

2) Insertion Sort: This is an in-place comparison-based sorting algorithm.


Here, a sub-list is maintained which is always sorted. For example, the lower
part of an array is maintained to be sorted. An element which is to be inserted
in this sorted sub-list, has to find its appropriate place and then it has to be
inserted there. Hence the name, insertion sort. The array is searched
sequentially and unsorted items are moved and inserted into the sorted sub-
list (in the same array). This algorithm is not suitable for large data sets.

How Insertion Sort Works?

We take an unsorted array for our example.

Insertion sort compares the first two elements.

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.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

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.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with


10.

These values are not in a sorted order.

So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Page 99 of 101
Programming for Problem Solving Riyaz Mohammed

Again we find 14 and 10 in an unsorted order.

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.

3) Selection sort: Selection sort is a simple sorting algorithm. This sorting


algorithm is an in-place comparison-based algorithm in which the list is
divided into two parts, the sorted part at the left end and the unsorted part at
the right end. Initially, the sorted part is empty and the unsorted part is the
entire list. The smallest element is selected from the unsorted array and
swapped with the leftmost element, and that element becomes a part of the
sorted array. This process continues moving unsorted array boundary by one
element to the right. This algorithm is not suitable for large data sets.

How Selection Sort Works?

Consider the following depicted array as an example.

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.

Page 100 of 101


Programming for Problem Solving Riyaz Mohammed

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.

Following is a pictorial depiction of the entire sorting process

Page 101 of 101

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy