Você está na página 1de 278

Structured Programming Approach

Prof: S. Rathod

Structured
Programming
Approach

[0]

Structured Programming Approach

Prof: S. Rathod

WHY LEARN PROGRAMMING:


A computer is machine. Programming helps you to understand computer.
A program is a set of logically related instruction that is arranged in a
sequence that directs the computer in solving problem.
The process of writing a program is called programming.
Software:
Software nothing but computer program.
Types:
System software: It is a collection of program that interfaces with hardware.
Example: Language Translator, Operating system
Application software: It is enable the computer to solve a specific data processing
task

PROGRAMMING LANGUAGE:
A set of rules that provide a way of telling a computer what operation to perform is
called computer programming language.
Types:
1) High level: It is used to write application programs. It is easy to prepare and
debug.
Example: BASIC,COBOL(Common Business Oriented Programming Language)
and FORTRAN (formula translation language).
2) Middle level:It is used for writing application and system program.
Example: C
[1]

Structured Programming Approach

Prof: S. Rathod

3) low level: It is mostly used to write system program.


Example: Assembly Language.
COMPILER:
A compiler is a computer program (or a set of programs) that transforms source
code written in a programming language (the source language) into another
computer language (the target language), with the latter often having a binary form
known as object code.

INTERPRETER:
Computer language processor that translates a program line-by-line
(statement-by-statement) and carries out the specified actions in sequence.

The difference between an interpreter and a compiler


Interpreter

Compiler

Translates program one statement at a


time.

Scans the entire program and translates


it as a whole into machine code.

It takes less amount of time to analyze


the source code but the overall
execution time is slower.

It takes large amount of time to analyze


the source code but the overall
execution time is comparatively faster.

No intermediate object code is


generated, hence are memory efficient.

Generates intermediate object code


which further requires linking, hence
requires more memory.

Continues translating the program until


the first error is met, in which case it
stops. Hence debugging is easy.

It generates the error message only


after scanning the whole program.
Hence debugging is comparatively
hard.
[2]

Structured Programming Approach

Programming language like Python,


Ruby uses interpreters.

Prof: S. Rathod

Programming language like C, C++ use


compilers.

LINKER:
Linker convert machine understandable format into Operating system
understandable format.
If these piece of code need some other source file to be linked the linker link
them to make it a executable file.
LOADER:
It is a program used by an operating system to load programs from a
secondary to main memory so as to be executed. Usually large applications
are written into small modules and are then compiled into object codes.
Loader : is entity which actually load and runs the program into RAM
WHAT IS STRUCTURED PROGRAMMING APPROACH?
Structured: It means highly organized or arranged in a definite pattern.
Programming: Telling computer to do something for us.
Approach: It means a methodology used to perform a task
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.
Structured programming facilitates program understanding and modification
and has a top-down design approach, where a system is divided into
compositional subsystems.
Process of Programming:
1) Understand the problem to be solved
2) Think and design solution logic
3) Write the program in the chosen programming language.
4) Translate the program to m/c code.
5) Test the program with sample data and Put the program into operation.
[3]

Structured Programming Approach

Prof: S. Rathod

Structured Programming

Object Oriented Programming

Structured Programming is designed Object Oriented Programming


which focuses on process/ logical designed which focuses on data.
structure and then data required for that
process.

is

Structured programming follows top- Object oriented programming follows


down approach.
bottom-up approach.
Structured Programming is also known Object Oriented Programming supports
as Modular Programming and a subset inheritance, encapsulation, abstraction,
of procedural programming language.
polymorphism, etc.
In Structured Programming, Programs In Object Oriented Programming,
are divided into small self contained Programs are divided into small entities
functions.
called objects.
Structured Programming is less secure Object Oriented Programming is more
as there is no way of data hiding.
secure as having data hiding feature.
Structured Programming can solve Object Oriented Programming can
moderately complex programs.
solve any complex programs.
Structured Programming provides less Object Oriented Programming provides
reusability, more function dependency. more
reusability,
less
function
dependency.
Less abstraction and less flexibility.

More abstraction and more flexibility.

WHAT IS PROBLEM DEFINITION?


The definition of a problem is something that has to be solved or an unpleasant or
undesirable condition that needs to be corrected.
ALGORITHM
Program=algorithm+data
[4]

Structured Programming Approach

Prof: S. Rathod

Algorithm for problems is written in any human readable language.


Therefore algorithms are not computer programs, but they are descriptions
containing natural language and familiar structures from programming
language.
Algorithm is a part of plan for a computer program.
It is an effective procedure for solving the problem in a finite no of step.
PROPERTIES:
Finiteness: - an algorithm terminates after a finite numbers of steps.
Definiteness: - each step in algorithm is unambiguous. This means that the
action specified by the step cannot be interpreted (explain the meaning of) in
multiple ways & can be performed without any confusion.
Input:- an algorithm accepts zero or more inputs
Output:- it produces at least one output.
Effectiveness:- it consists of basic instructions that are realizable. This
means that the instructions can be performed by using the given inputs in a
finite amount of time.
EFFICIENCY:
Time efficiency - a measure of amount of time for an algorithm to execute.
Space efficiency - a measure of the amount of memory needed for an algorithm to
execute.
Function g asymptotically dominates function f if there are positive constants c and
n0 such that
c*g(n) >= f(n) for all n>= n0
That is, g asymptotically dominates f if g dominates f for all "large" values of n.
CASES:
In these cases, it is important to consider:
worst-case: The situation that would require the most amount of processing.
[5]

Structured Programming Approach

Prof: S. Rathod

best-case: The situation that would require the least amount of processing.
average-case: The average amount of required processing. This option is the
most difficult to compute because you must consider the probabilities of all
possible cases and the amount of processing required for each case.
Example:
Consider: Search for an element in a list
Best case search when item at beginning
Worst case when item at end
Average case somewhere between
WAYS OF REPRESENTATION:
step form ----- statement of an algorithm
pseudocode -----statement of an algorithm
flowchart ----- Graphical representation
FEATURES:
Sequence ----- called process
Decision ----- called selection
Repetition ----- called iteration /looping
1) Algorithm:(To add two numbers)
Step 1: Start.
Step 2: Print Enter two numbers : .
Step 3: Input num1,num2.
Step 4: result = num1+num2.
Step 5: Print result.
Step 6: Stop.

[6]

Structured Programming Approach

Prof: S. Rathod

2) Algorithm:(multiply and display the product of two floating point numbers)


Step 1: Start.
Step 2: Print Enter two floating numbers:
Step 3: Input num1, num2.
Step 4: result = num1*num2.
Step 5: Print result.
Step 6: Stop.
3) Algorithm :( To calculate the square of a number)
Step 1: Start.
Step 2: Print Enter a numbers:
Step 3: Input x
Step 4: Square = x * x
Step 5: Print Square
Step 6: Stop
4) Algorithm :( finds Simple Interest)
Step 1: Start
Step 2: Print Enter principal amount, rate of interest, no. of years
Step 3: Input principal, Int_rate, years
Step 4: Simple_Int = (principal, Int_rate, years)/100
Step 5: Print Simple_Int
Step 6: Stop
5) Algorithm :(calculate area and perimeter of rectangle)
Step 1: Start
Step 2: Print Enter length and breadth of the rectangle
Step 3: Input length and breadth
Step 4: Calculate area and perimeter of rectangle as:
Area= length * breadth
Perimeter= 2* (length + breadth)
Step 5: Print area and perimeter of rectangle
Step 6: Stop
[7]

Structured Programming Approach

Prof: S. Rathod

6) Algorithm :( calculates area of circle.)


Step 1: Start
Step 2: Print Enter input as radius of a circle
Step 3: Input radius
Step 4: Calculate area of circle as: area=3.14 *r*r
Step 5: Print area of circle
Step 6: Stop
7) Algorithm :( find greatest among three integers)
Step 1: START.
Step 2: PRINT Enter three numbers:
Step 3: INPUT a, b, c.
Step 4: IF a>b, GOTO step 5, ELSE GOTO step 6.
Step 5: IF a>c THEN max=a, ELSE max=c AND GOTO step 7.
Step 6: IF b>c THEN max=b, ELSE max=c.
Step 7: PRINT max.
Step 8: STOP.
8) Algorithm :(To Swap Two Numbers using temporary variable)
Step 1: Start.
Step 2: Print Enter two numbers:
Step 3: Input values for num1, num2.
Step 4: Use a temporary variable for swapping two nos,
i) Assign first number to temporary variable.
ii) Assign second number to first number.
iii) Assign temporary variable to second number.
Step 5: Display swapped nos.
Step 6: Stop.
9) Algorithm :( To Swap Two Numbers without using temporary variable.)
Step 1: Start.
Step 2: Print Enter two numbers: .
Step 3: Input values for num1, num2.
[8]

Structured Programming Approach

Prof: S. Rathod

Step 4: Without temporary variable for swapping two nos,


i) Add two nos. & assign result to first number.
ii) Subtract second no. from first no. & assign result to second number.
iii) Subtract second no. from first no. & assign result to first number.
Step 5: Display swapped nos.
Step 6: Stop.
10) Algorithm :( Calculate the gross salary that includes basic salary, 50%DA,
40%HRA.)
Step 1: Start
Step 2: Input the value for basic_salary
Step 3: Calculate the HRA and DA of user entered basic_salary
Step 4: Calculate Gross_Salary i.e. sum of basic_salary, HRA and DA
Step 5: Display the calculated Gross_Salary
Step 6: Stop
11) Algorithm :( To check whether triangle can be drawn or not and classify
type)
Step 1: Start
Step 2: Input the side A ,B, C
step 3: IF A+B>C AND B+C>A AND C+A>B
THEN
PRINTTRIANGLE CAN BE DRAWN
ELSE
PRINT
TRIANGLE CAN NOT BE DRAWN GO TO 7
Step 4:

IF A=B AND B=C THEN EQUILATERAL TRIANGLE GO TO 7

Step 5: IF A=B OR B=C OR C=A THEN ISOSCELE TRIANGLE GO TO 7


[9]

Structured Programming Approach

Prof: S. Rathod

Step 6: PRINT SCALENE TRIANGLE


Step 7: Stop

FLOWCHART
A Flowchart is a graphical representation of an algorithm.
A flowchart is a type of diagram that represents an algorithm or process,
showing the Steps as boxes of various kinds, and their order by connecting
these with arrows. This diagrammatic representation can give a step-by-step
solution to a given problem.

only one flow line should come out from process symbol

[10]

Structured Programming Approach

Prof: S. Rathod

Only one flow line should enter in decision symbol, but two or three flow lines,
one for each possible answer, should leave the decision symbol.

only one flow line is used in conjunction with terminal symbol

1) Flow Chart: (To add two numbers)

2) Flow Chart: (Calculate the gross salary that includes basic salary, 50%DA,
40%HRA)
[11]

Structured Programming Approach

Prof: S. Rathod

3) Flow Chart: (find greatest among three integers)

[12]

Structured Programming Approach

Prof: S. Rathod

4) Flow Chart: (find all the roots of a quadratic equations)

5) Flow Chart: (the Fibonacci series till term1000)

[13]

Structured Programming Approach

Prof: S. Rathod

What is C?
C is a general-purpose computer programming language developed in 1972 by
Dennis Ritchie at the Bell Telephone Laboratories. C is a structured programming
language, which means that it allows you to develop programs using well-defined
control structures and provides modularity (breaking the task into multiple sub
tasks that are simple enough to understand and to reuse). C is often called a
middle-level language because it combines the best elements of low-level or
machine language with high-level languages.
Why you should learn C?
You should learn C because:
C is simple.
There are only 32 keywords so C is very easy to master. Keywords are
words that have
special meaning in C language.
C programs run faster than programs written in most other languages.
C enables easy communication with computer hardware making it easy to
write system programs such as compilers and interpreters.
Getting Started with C
Instead of straight-away learning how to write programs, we must first know what
alphabets, numbers and special symbols are used in C, then how using them
constants, variables and keywords are constructed, and finally how are these
combined to form an instruction. A group of instructions would be combined later
on to form a program. This is illustrated in the Figure

[14]

Structured Programming Approach

Prof: S. Rathod

A Simple Program
The following program is written in the C programming language.
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
}
A NOTE ABOUT C PROGRAMS
In C, lowercase and uppercase characters are very important! All commands in C
must be lowercase.The C programs starting point is identified by the word
main()
This informs the computer as to where the program actually starts. The brackets
that follow the keyword main indicate that there are no arguments supplied to this
program
The two braces, { and }, signify the begin and end segments of the program. The
purpose of the statement
include <stdio.h>
is to allow the use of the printf statement to provide program output. Text to be
displayed by printf() must be enclosed in double quotes. The program has only one
statement
printf("Programming in C is easy.\n");
printf() is actually a function (procedure) in C that is used for printing variables
and text. Where text appears in double quotes "", it is printed without modification.
There are some exceptions however. This has to do with the \and % characters.
These characters are modifiers, and for the present the \ followed by the n
character represents a newline character. Thus the program prints
[15]

Structured Programming Approach

Prof: S. Rathod

Programming in C is easy.
Summary of major points:
program execution begins at main()
keywords are written in lower-case
statements are terminated with a semi-colon
text strings are enclosed in double quotes
C is case sensitive, use lower-case
\n means position the cursor on the beginning of the next line
printf() can be used to display text to the screen
The curly braces {} define the beginning and end of a program block.
Character set:
Character set are the set of alphabets, letters and some special characters that are
valid in C language.
Alphabets:
Uppercase: A B C .................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits:
0123456789
Token of c language
1) Variable/Identifier
2) Keywords
3) Constant
4) Assignment
5) Initialization
6) Operator
[16]

Structured Programming Approach

Prof: S. Rathod

Variables:
Variables are memory location in computer's memory to store data.
To indicate the memory location, each variable should be given a unique
name called identifier.
Variable names are just the symbolic representation of a memory location.
Syntax:
Examples

<datatype> nameofvariable;
int num;
Here, num is a variable of integer type.

Rules for writing variable name in C


1. Variable name can be composed of letters (both uppercase and lowercase
letters), digits and underscore '_' only.
2. The first letter of a variable should be either a letter or an underscore. But, it is
discouraged to start variable name with an underscore though it is legal. It is
because, variable name that starts with underscore can conflict with system names
and compiler may complain.
3. There is no rule for the length of length of a variable. However, the first 31
characters of a variable are discriminated by the compiler.So; the first 31 letters of
two variables in a program should be different.
Escape Sequence

[17]

Structured Programming Approach

Prof: S. Rathod

Keywords :
Keywords are the words whose meaning has already been explained to the C
compiler.
The keywords cannot be used as variable names.
The keywords are also called Reserved words.
There are only 32 keywords available.

Data Types
A C language programmer has to tell the system before-hand, the type of numbers
or characters or variable he is using in his program. These can be done by using
data types. Data types indicate the type of data hold by variable. There are many
data types in C language. A C programmer has to use appropriate data type as per
his requirement. C language data types can be broadly classified into three
categories, namely:
1. Primary data type
2. Derived data type
3. User defined data type
4. Valueless

[18]

Structured Programming Approach

Prof: S. Rathod

Primary data type:


All C Compilers accept the following fundamental data types
1. Int
2. Char
3. Float
4. Double
5. void
Character Type:
A single character can be defined as a defined as a character type of data.
Characters are usually stored in 8 bits of internal storage.
The qualifier signed or unsigned can be explicitly applied to char.
Unsigned characters have values between 0 and 255.
Signed characters have values from 128 to 127.
The keyword used to define character variables is,
char
An example of a character value is the letter A.
char 'A';
Sr.
No.

Data Type

Size
bits

Char or Signed Char 8

-128 to 127

Unsigned Char

0 to 255

in Range

[19]

Structured Programming Approach

Prof: S. Rathod

Integer Type:
Integers are whole numbers with a machine dependent range of values.
C has 3 classes of integer storage namely
1. short int,
2. int,
3. long int.
All of these data types have signed and unsigned forms Unsigned integers
(positive values only).
A short int requires half the space than normal integer values.
Unsigned numbers are always positive and consume all the bits for the
magnitude of the number.
The long and unsigned integers are used to declare a longer range of values.
The keyword used to define integers is, int
An example of declaring an integer variable called sum is,
int sum;
Sr. No.

Data Type

Size in bits Range

short int or signed short int

-128 to 127

unsigned short int

0 to 255

int or signed int

16

-32768 to 32767

unsigned int

16

0 to 65535

5.

long int or signed long int

32

-2147483648
2147483647

unsigned long int

32

0 to 4294967295

[20]

to

Structured Programming Approach

Prof: S. Rathod

Floating Point Types:


Floating point number represents a real number (with six precision like
2.123456).
Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is insufficient, we can use
the double(with ten precision like 2.1234567891). to define the number.
The double is same as float but with longer precision. To extend the
precision further we can use long double which consumes 80 bits of memory
space.
The keyword used to define float variables is,
float
An example of declaring a float variable called money is,
float money;
Sr. No.

Data Type

Size in bits

Range

Float

32

3.4 e-38 to 3.4 e+38

Double

64

1.7e-308 to 1.7e+308

Long Double

80

3.4 e-4932 to 3.4 e+4932

Void Type:
Void is an empty data type normally used as a return type in C functions to
declare that no value will be return by the function. The void data type has no
values and no operations. It's a datatype that represents the lack of a data type.
Constant:
Constants are the terms that can't be changed during the execution of a program.
For example: 1, 2.5, "Programming is easy." etc. In C,constants can be classified
as:
Constant is the entity that does not change.
[21]

Structured Programming Approach

Prof: S. Rathod

Types of C Constants
C constants can be divided into two major categories:
1) Primary Constants
2) Secondary Constants
These constants are further categorized as shown In fig.

Integer Constants
1) Integer constants are the numeric constants(constant associated with
number) without any fractional part or exponential part.
2) It must not have a decimal point.
3) It can be either positive or negative
4) The allowable range for integer constants is -32768 to 32767.
5) Default sign is positive
6) EX: 567, -3456, +876 etc

Types of integer constants:


Decimal constant (base 10):
Decimal digits: 0 1 2 3 4 5 6 7 8 9 & something other than 0.
For example: 0, -9, 22 etc
[22]

Structured Programming Approach

Prof: S. Rathod

Octal constant (base 8):


Octal digits: 0 1 2 3 4 5 6 7 & first digit must be 0.
For example: 021, 077, 033 etc

Hexadecimal constant (base 16):


Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F & begin with
0x.
For example: 0x7f, 0x2a, 0x521 etc
Real Constants
1) Real constants are often called Floating Point constants.
2) A real constant must have at least one digit.
3) It must have a decimal point.
4) It could be either positive or negative.
5) Ex: 345.67, -567.23, +34.8
Character Constants
1) A character constant is a single alphabet, a single digit or a single special
symbol enclosed within single inverted commas.
2) The maximum length of a character constant can be 1 character.
3) Ex.: 'Y' , '7' , '='

String constants
String constants are the constants which are enclosed in a pair of double-quote
marks.
[23]

Structured Programming Approach

Prof: S. Rathod

For example:
"good"

//string constant

""

//null string constant

""

//string constant of six white space

"x"

//string constant having single character.

"Earth is round\n" //prints string with newline

Assignment:
The = operator is used to assign values to data variables.The most common
assignment operator is =. This operator assigns the value in right side to the left
side.
For example:
var=5

//5 is assigned to var

a=c;

//value of c is assigned to a

5=c;

// Error! 5 is a constant.

Initialization :
Assigning a value to the variable during declaration of variable is called
initialization.
When variable is declared ,the compiler does not assign any value to the
variable.
Example: int i; -------->Tentative declaration

Syntax: <datatype> variablename=constant;


[24]

Structured Programming Approach

Prof: S. Rathod

Example: int i=10;

DECIMAL NUMBERS
In the decimal number systems each of the ten digits, 0 through 9,
represents a certain quantity.
The position of each digit in a decimal number indicates the magnitude of
the quantity represented and can be assigned a weight.
The weights for whole numbers are positive powers of ten that increases
from right to left, beginning with 10 = 1 that is 10 10 10 10

[25]

Structured Programming Approach

Prof: S. Rathod

For fractional numbers, the weights are negative powers of ten that decrease from
left to right beginning with 10 that is 10 10 10. 10 10 10
The value of a decimal number is the sum of digits after each digit has been
multiplied by its weights as in following examples.

Express the decimal number 87 as a sum of the values of each digit.


The digit 8 has a weight of 10 which is 10 as indicated by its position. The digit 7
has a weight of 1 which is 10 as indicated by its position.

87 = (8 x 1) + (7 x 0 )

Express the decimal number 725.45 as a sum of the values of each digit.

725. 45 = (7 x 10) + (2 x 10) + (5 x 10) + (4 x 10) + (5 x 10) = 700 + 20 + 5


+ 0.4 + 0.05

BINARY NUMBERS
The binary system is less complicated than the decimal system because it
has only two digits, it is a base-two system.
The two binary digits (bits) are 1 and 0. The position of a 1 or 0 in a binary
number indicates its weight, or value within the number, just as the position
of a decimal digit determines the value of that digit.
The weights in a binary number are based on power of two as:
.. 4 2 2 2 1 2 0 . 2 -1 2 -2 .
With 4 digits position we can count from zero to 15.
[26]

Structured Programming Approach

Prof: S. Rathod

The right-most bit is the least significant bit (LSB) in a binary whole
number and has a weight of 2 =1. The weights increase from right to left by
a power of two for each bit.
The left-most bit is the most significant bit (MSB); its weight depends on
the size of the binary number.
BINARY-TO-DECIMAL CONVERSION
The decimal value of any binary number can be found by adding the weights of all
bits that are 1 and discarding the weights of all bits that are 0
Example Lets convert the binary whole number 101101 to decimal

HEXADECIMAL NUMBERS
The hexadecimal number system has sixteen digits and is used primarily as a
compact way of displaying or writing binary numbers because it is very easy
to convert between binary and hexadecimal.
Long binary numbers are difficult to read and write because it is easy to drop
or transpose a bit. Hexadecimal is widely used in computer and
microprocessor applications.
The hexadecimal system has a base of sixteen; it is composed of 16 digits
and alphabetic characters.
The maximum 3-digits hexadecimal number is FFF or decimal 4095 and
maximum 4-digit hexadecimal number is FFFF or decimal 65.535.
[27]

Structured Programming Approach

Prof: S. Rathod

BINARY-TO-HEXADECIMAL CONVERSION
Simply break the binary number into 4-bit groups, starting at the right-most bit and
replace each 4-bit group with the equivalent hexadecimal symbol as in the
following example

HEXADECIMAL-TO-DECIMAL CONVERSION
One way to find the decimal equivalent of a hexadecimal number is to first convert
the hexadecimal number to binary and then convert from binary to decimal.

DECIMAL-TO-HEXADECIMAL CONVERSION
Repeated division of a decimal number by 16 will produce the equivalent
hexadecimal number, formed by the remainders of the divisions.
The first remainder produced is the least significant digit (LSD). Each
successive division by 16 yields a remainder that becomes a digit in the
equivalent hexadecimal number. When a quotient has a fractional part, the
fractional part is multiplied by the divisor to get the remainder.

[28]

Structured Programming Approach

Prof: S. Rathod

OCTAL NUMBERS
Like the hexadecimal system, the octal system provides a convenient way to
express binary numbers and codes. However, it is used less frequently than
hexadecimal in conjunction with computers and microprocessors to express binary
quantities for input and output purposes.
The octal system is composed of eight digits, which are:
0, 1, 2, 3, 4, 5, 6, 7
To count above 7, begin another column and start over: 10, 11, 12, 13, 14, 15, 16,
17, 20, 21 and so on.
Counting in octal is similar to counting in decimal, except that the digits 8 and 9
are not used.
OCTAL-TO-DECIMAL CONVERSION
Since the octal number system has a base of eight, each successive digit
position is an increasing power of eight, beginning in the right-most column
with 8.
The evaluation of an octal number in terms of its decimal equivalent is
accomplished by multiplying each digit by its weight and summing the
products.

[29]

Structured Programming Approach

Prof: S. Rathod

DECIMAL-TO-OCTAL CONVERSION
A method of converting a decimal number to an octal number is the repeated
division-by-8 method, which is similar to the method used in the conversion
of decimal numbers to binary or to hexadecimal.
Lets convert the decimal number 359 to octal. Each successive division by 8
yields a remainder that becomes a digit in the equivalent octal number. The
first remainder generated is the least significant digit (LSD).

OCTAL-TO-BINARY CONVERSION
Because each octal digit can be represented by a 3-bit binary number, it is very
easy to convert from octal to binary.

[30]

Structured Programming Approach

Prof: S. Rathod

BINARY-TO-OCTAL CONVERSION
Conversion of a binary number to an octal number is the reverse of the octal-tobinary conversion.

Operator:
Operators are the symbols used to indicate operation on the operands. Different
types of Operators supported in C language are given as follows:
1. Arithmetic operators
2. Increments and Decrement Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Arithmetic operators
Arithmetical operators are used to perform basic arithmetical operations which are
explained in following table.

[31]

Structured Programming Approach

Prof: S. Rathod

Sr.
No.
1

Operator

Meaning

Explanation

Example

Addition

Subtraction Used to find out subtraction Ex: 6-5


(difference) of given operands.
Output: 1

Multiplicati Used to find out multiplication of Ex: 6*5


on
given operands.
Output: 30

Division

Used to find out division of given Ex: 10/5


operands.
Output: 2

Modulus

Used to find out the remainder Ex: 10/5


from division.
Output: 0

Used to find out addition of given Ex: 5+6


operands.
Output: 11

Arithmetic Expression (Arithmetic Instruction):


A C arithmetic expression consists of a variable name on the left hand side of
assignment operator (=) and operands (variable names & constants) on the right
hand side of =. The operands are connected by arithmetic operators like +, -, *, and
/.
Ex.: int a;
float b, result ;
a = 5400;
b = 0.5;
result = a * b / a + 3.2 * 2 / 5 ;
Here,
[32]

Structured Programming Approach

Prof: S. Rathod

*, /, -, + are the arithmetic operators.


= is the assignment operator.
2, 5 and 5400 are integer constants.
3.2 and 0.5 are real constants.
a is an integer variable.
b, result are real variables.

Type of Arithmetic Statement in C:


A C arithmetic statement could be of three types. These are as follows:
1. Integer mode arithmetic statement - This is an arithmetic statement in which
all operands are either integer variables or integer constants.
Ex.: int i, j;
i = 20;
j = i * 20 + 5;
2. Real mode arithmetic statement - This is an arithmetic statement in which all
operands are either real constants or real variables.
Ex.: float i,j ;
j = 12.5;
i = j + 23.123 / 4.5 * 0.3442;
3. Mixed mode arithmetic statement - This is an arithmetic statement in which
some of the operands are integers and some of the operands are real.
Ex.: float i, avg;
int a, b, num ;
[33]

Structured Programming Approach

Prof: S. Rathod

avg = ( a + b + i + num ) / 4 ;
Hierarchy of Operations / Arithmetic Operation Precedence and Associativity:
While executing an arithmetic expression, which has two or more operators, we
may have some problems as to how exactly does it get executed. Hierarchy of
Operations gives solution to this problem. The priority or precedence in which the
operations in an arithmetic statement are performed is called the hierarchy of
operations. The precedence of commonly used operators is shown in following
table.
When an expression contains two operators of equal priority the tie between them
is settled using the associativity of the operators. Associativity can be of two
typesLeft to Right or Right to Left.
Priority

Operators

Description

Associativit
y

1st

*,/, %

multiplication, division, modulo


division

Left to right

2nd

+,-

addition, subtraction

Left to right

3rd

assignment

Right to left

Ex: Determine the operations precedence and evaluate the following expression:
i=2*3/4+4/4+8-2+5/8
Solution:
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8

operation: *

i=1+4/4+8-2+5/8

operation: /

i = 1 + 1+ 8 - 2 + 5 / 8

operations: /
[34]

Structured Programming Approach

Prof: S. Rathod

i=1+1+8-2+0
i=2+8-2+0

operation: /
operation: +

i = 10 - 2 + 0

operation: +

i=8+0

operation : -

i=8

operations: +

Note that 6 / 4 give 1 and not 1.5. This so happens because 6 and 4 both are
integers and therefore would evaluate to only an integer constant. Similarly 5 / 8
evaluates to zero, since 5 and 8 are integer constants and hence must return an
integer value.
Conversion of arithmetic statement to a C arithmetic statement
Some of the examples of Conversion of arithmetic statement to a C arithmetic
statement are shown in following table.
Algebraic Expression

C Expression

axbcxd

a*bc*d

(x + y) (a - b)

(m + n) * (a + b)

7y3+y2 + 2y + 9

7*y*y*y+y*y+2*y
+9

Example: Program to demonstrate the working of arithmetic


#include <stdio.h>
int main()
{
int a=9,b=4,c;
[35]

Structured Programming Approach

Prof: S. Rathod

c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}
Output:
a+b=13 a-b=5 a*b=36 a/b=2
Remainder when a divided by b=1
Increments and Decrement Operators:
The increment and decrement operators are one of the unary operators which are
very useful in C language. They are extensively used in for and while loops. The
syntax of the operators is given below
1. ++ variable name
2. variable name ++
3. variable name
4. Variable name

[36]

Structured Programming Approach

Prof: S. Rathod

The increment operator ++ adds the value 1 to the current value of operand and the
decrement operator subtracts the value 1 from the current value of operand.
Ex: int i=42
i++ = i=i+1 =i=43
i-- = i=i-1 =i=42
++i = i=i+1 =i=43
--i = i=i-1 =i=42
POSTFIX

a) x=a++;
x=a ------> store value of a in memory for variable x
a=a+1 ------> increment value by 1 and store in memory for variable a

b) y=b--;
y=b ------> store value of b in memory for variable y
b=b-1 ------> decrement value by 1 and store in memory for variable b

PREFIX:
value of operand increment /decrement before it is fetch for computation.
a) x=++a;
a=a+1 ------> increment value by 1 and store in memory for variable a
x=a

------> store value of a in memory for variable x

b) y=--b;
b=b-1 ------> decrement value by 1 and store in memory for variable b
[37]

Structured Programming Approach

y=b

Prof: S. Rathod

------> store value of b in memory for variable y

NOTE:
1) To evaluate the expression first find all pre operation from expression and
calculate new value.
2) put that new value in the expression and evaluate expression.
3) find all post operation from expression and evaluate the same and that final
value of variable those we need to print.
Expression
original value

x=3

y=4

PREOPERATIO
N

(--x)

no pre operation

new value

EXPRESSION

z = (x++) + x + (--x) + (y++)


10 =

POSTOPERATI
ON
final value

z=?

+ 2+

+ 4

(x++)

(y++)

10

Relational Operators:
Relational Operators are used to compare two operands. That is why; they are also
known as Comparison operators.

[38]

Structured Programming Approach

Prof: S. Rathod

Sr.
No
.

Operat
or

Meanin
g

Exampl
e

Explanation

<

Less
than

Ex: a<b

Check whether the value a is less than


stored in a is less than b.
b

>

Greater Ex: a>b


than

Check whether the value a is greater


stored in a is greater than b. than b

<=

Less
Ex: a<=b Check whether the value a is less than
than or
stored in a is less than or or equal to
equal to
equal to b.

>=

Greater Ex: a>=b Check whether the value a is greater


than or
stored in a is greater than or than or equal
equal to
equal to b.
to

==

Equal to Ex: a==b Check whether the value a is equal to b


stored in a is equal to than
b.

=!

Not
Ex: a=!b Check whether the value a is not equal
equal to
stored in a is not equal to to b
than b.

Ex: Assume a=3, b=4;


If a<b (i.e. 3<4), result will be true.
If a>b (i.e. 3>4), result will be false

[39]

is true if

Structured Programming Approach

Prof: S. Rathod

Logical Operators:
C allows usage of three logical operators, namely, AND OR and NOT.
Sr.
No.

Operator

Meaning

Example

Explanation

&&

Logical
AND

(Condition
1) True if all conditions are true
&& (Condition 2
)

||

Logical
OR

(Condition 1) || True if any one


(Condition 2 )
conditions are true

Logical
NOT

!((Condition 1) Use to reverses the logical


&& (Condition 2 state of its operand. If a
))
condition is true then Logical
NOT operator will make false.

or

all

Ex:

a=4, b=5, c=6


(a < b) && (b < c)
(4 < 5) && (5 < 6)
True && True
Result: True
Assignment Operators
S.N. Operator
Meaning

Explanation

Example

Simple
assignment
operator

Assigns values from C = A + B will


right side operands to assign value of A +
left side operand
B into C

+=

Add
AND It adds right operand to C
+= A is
assignment
the left operand and equivalent to C =
operator
assign the result to left C + A
[40]

Structured Programming Approach

Prof: S. Rathod

operand
3

-=

Subtract AND It
subtracts
right C
-=
A
is
assignment
operand from the left equivalent to C =
operator
operand and assign the C - A
result to left operand

*=

Multiply AND It
multiplies
right C
*=
A
is
assignment
operand with the left equivalent to C =
operator
operand and assign the C * A
result to left operand

/=

Divide
AND It divides left operand C
/=
A
assignment
with the right operand equivalent to
operator
and assign the result to
C=C/A
left operand

%=

Modulus AND It takes modulus using C %= A is


assignment
two operands and assign equivalent to C =
operator
the result to left operand C % A

is

Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation. Assume if A = 60;
and B = 13; Now in binary format they will be as follows:
A = 0011 1100, B = 0000 1101
Operato
r

Description

Example

&

Binary AND Operator copies a bit to the (A & B) will give 12


result if it exists in both operands.
which is 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61


either operand.
which is 0011 1101
[41]

Structured Programming Approach

Prof: S. Rathod

Binary XOR Operator copies the bit if it is (A ^ B) will give 49


set in one operand but not both.
which is 0011 0001

Binary Ones Complement Operator is unary (~A ) will give -60


and has the effect of 'flipping' bits.
which is 1100 0011

<<

Binary Left Shift Operator. The left operands A << 2 will give 240
value is moved left by the number of bits which is 1111 0000
specified by the right operand.

>>

Binary Right Shift Operator. The left A >> 2 will give


operands value is moved right by the number
of bits specified by the right operand.

The truth tables for &, |, and ^ are as follows:


p

p&q

p|q

p^q

Conditional Operators:
The conditional operator is also called as ternary operators.It is the combination
of ? and :.
Syntax:
expression 1 ? expression 2 : expression 3
[42]

Structured Programming Approach

Prof: S. Rathod

If expression 1 is true, then the value returned will be expression 2, otherwise the
value returned will be expression 3.
Ex:

max = a>b ? a : b;
max=condition ? true : false;
max=a>b? (a>c?a:c) : (b>c?b:c) ;

Special Operators
C supports some special operators of interest such as
comma operator, :
Comma (,) operator is used to link the related expressions together. Comma used
expressions are linked from left to right and the value of the rightmost expression
is the value of the combined expression. The comma operator has the lowest
precedence of all operators.
Example:
sum= (X=5,Y=3,X+Y);
LEFT TO RIGHT
The result will be sum=8(After evaluating last expression and its value return as a
result). The comma operator is also used to separate variables during declaration.
size of operator:
The sizeof operator is not a library function but a keyword, which returns the size
of the operand in bytes. The size of operator always, precedes its operand. The
information obtained from this operator can be very useful when transferring a
program to a different computer. This operator can be used for dynamic memory
allocation. The various expressions and results of sizeof operator are
Expression
Result
sizeof(char)
1
sizeof(int)
2
[43]

Structured Programming Approach

sizeof(float)
sizeof(double)

Prof: S. Rathod

4
8

pointer operators (& and *):


& ----->address operator
* --------> value operator
member selection operators (. and ->).
Operator priority:
Order Category

Operato
Operation
r

Associativity

()
[]
1

Highest
precedence

L R
Function call

Left

to Right

::
.

Logical
negation (NOT)
R

Unary

Bitwise
1s
Right -> Left
complement

Unary plus
[44]

Structured Programming Approach

Member
Access

Multiplicati
on

Prof: S. Rathod

Unary minus

++

Pre or post
increment

--

Pre or post
decrement

&

Address

Indirection

Size of

Size of operant
in bytes

.*

Dereference
LR

Dereference

Multiply

Divide

Modulus

Binary Plus

LR

LR

Additive

Shift

Binary Minus

<<

Shift Left
[45]

LR

Structured Programming Approach

Prof: S. Rathod

>>

Shift Right

<

Less than

<=

Less than
equal to

or
LR

Relational
>

Greater than

>=

Greater than or
equal to

==

Equal to
LR

Equality
!=

Not Equal to

Bitwise
AAND

&

Bitwise AND

LR

10

Bitwise
XOR

Bitwise XOR

LR

11

Bitwise OR

Bitwise OR

LR

12

Logical
AND

&&

Logical AND

LR

14

Conditional

?:

Ternary
Operator

RL

[46]

Structured Programming Approach

15

Prof: S. Rathod

Assignment

*=

Assign product

%=

Assign
reminder

/=

Assign quotient

+=

Assign sum

-=

Assign
difference
RL

Assignment
&=

Assign bitwise
AND

^=

Assign bitwise
XOR

|=

Assign bitwise
OR

<<=

Assign left shift

>>=

Assign
shift

right

[47]

Structured Programming Approach

Prof: S. Rathod

Implicit Type Conversion:


C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the
expression can be evaluated without loosing any significance. This automatic
conversion is known as implicit type conversion.
Explicit Conversion:
The process of such a local conversion is known as explicit conversion or casting a
value. The general form of a cast is:
(type-name)expression
Where type-name is one of the standard C data types. The expression may be a
constant, variable or an expression.
Example:
x = (int) 7.5 // 7.5 is converted to integer by truncation
I/O Statements
The standard input output functions are available in the header file <stdio.h> and
should be included in the program to use those functions.
Types :
1. UnFormatted I/O functions
Input Functions
getch(),
getche(),
getchar(),
gets().
[48]

Structured Programming Approach

Prof: S. Rathod

output Function
putch()
putchar()
puts()
2. Formatted I/O functions
output Function
printf()
Input function
scanf()

Format Specifiers:
Following is the list of most commonly used format specifiers that can be used
with the printf( ) function.
Sr. No.

Format
Specifier

Data Type

What get printed?

%d

Integer

Print interger

%f

Float

Print real value

%c

Character

Print character

%s

String

Print String

%u

unsigned
integer

Print unsigned integer

%d

short int

Print interger
[49]

Structured Programming Approach

Prof: S. Rathod

%ld

long int

Print interger

%lf

double

Print double value

%Lf

long double

Print double value

Formatted
Input Statement:
scanf()
The scanf function allows you to accept input from standard in, which for us
is generally the keyboard.
The scanf function can do a lot of different things, but it is generally
unreliable unless used in the simplest ways.
It is unreliable because it does not handle human errors very well.
But for simple programs it is good enough and easy-to-use.
Syntax:
scanf(control string, &variable01, &variable02, );
Example:
scanf(%d, &number);
Output Statement:
Printf() : It displays information on screen.
It returns the number of characters printed.
It displays the text you put inside the double quotes.
It requires the backslash character(escape sequence) to display some special
characters.
It can display variables by using the % conversion character.
Printf format: a string argument followed by any additional arguments.
Syntax:
printf ( "format string", list of variables ) ;
[50]

Structured Programming Approach

Prof: S. Rathod

The format string can contain:


1.Characters that are simply printed as they are.
Ex: printf(Enter the number);
2. Format specifier that begin with a % sign like %d, %f etc
Ex: printf(Entered Number is : %d, num);
3.Escape sequences that begin with a \ sign such as /n, /t.
Ex: printf (\nAverage = %d", avg);
Unformatted I/O
Input Functions
getch(): Normally we will use it at the end of the main(). It just accepts a keystroke
and never displays it and proceeds further.

getche() will accept a character from keyboard display it immediately does not
wait for Enter key to pressed for proceeding.

getchar() -will accept a character from keyboard displays immediately while


typing and need Enter key to pressed for proceeding.

gets():
gets( ) receives a string from the keyboard. it gets a string from the keyboard. It is
terminated when an Enter key is hit. Thus, spaces and tabs are perfectly acceptable
as part of the input string.

[51]

Structured Programming Approach

Prof: S. Rathod

output Function
putchar():
putchar print a character on the screen.
puts():
The puts( ) function works exactly opposite to gets( ) function. It displays a string
to the screen.
Standard Maths functions (math.h)
Function

Synta
x

abs

abs( x) Returns the absolute value of an


integer

sqrt

pow

exp

log

Description

sqrt(x) Function returns the square root of


x.
pow(
x, y)

Function returns the value of x


raised to the power y (i.e. xy).

exp(
x)

Function returns the value of e raised to the power x (i.e. ex).

log(x) Function returns the natural


logarithm of x (i.e. loge(x)).

Example
y = abs(-12)
O/P: y=12
y = sqrt(100)
O/P: y = 10
y = pow(2,2);
O/P: y=4
y = exp(0.5);
O/P: y = 1.648721
y = log(10);
O/P: y= 2.302585E

log10

log10( Function returns the base-10


y = log10(100)
x)
logarithm of x (i.e. log10(x)).
O/P: y = 2.000000

sin

sin(f)

Function returns the sine of f

[52]

y = sin(90)

Structured Programming Approach

Prof: S. Rathod

O/P: y = 1
cos

cos(f)

Function returns the cosine of f

y = cos(60);
O/P: y= 0.500008

tan

tan(x)

Function returns the tangent of x

y = tan(45);
O/P: y = 0.999998

ceil

Function returns value of x rounded


y = ceil(0.5);
ceil(x) up to the next whole number.
O/P: y = 1.000000

floor

floor(
x)

Function returns the value of y = floor(15.258);


parameter x rounded down to the O/P:
nearest integer.
y = 15.000000

BASIC PROGRAM:
Write a Program to display a sentence on the screen.
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming");

//displays the content inside quotation

return 0;
}
Output:
C Programming

[53]

Structured Programming Approach

Prof: S. Rathod

Note: Every C program starts executing code from main() function. Inside main(),
there is a printf()function which prints the content inside the quotation mark which
is "C Programming" in this case.

WAP to Display the number entered by user


#include <stdio.h>
#include <conio.h>
void main()
{
int num;
printf("Enter a integer: ");
scanf("%d",&num);
*/

/* Storing a integer entered by user in variable num

printf("You entered: %d",num);


getch();
}
Output:
Enter a integer: 25 You entered: 25
Program to add two nos. with user input
#include<stdio.h>
#include<conio.h>
void main()
{
[54]

Structured Programming Approach

Prof: S. Rathod

int num1;
float num2,result;
clrscr();
printf("Enter one integer and one floating point no. : ");
scanf("%d%f",&num1,&num2);
result=num1+num2;
printf("Result of addition : %f",result);
getch();
}
OUTPUT :
Enter one integer and one floating point no. : 10 12.2
Result of addition : 22.200001

Write a C program to multiply and display the product of two floating point
numbers entered by user.
#include <stdio.h>
#include <conio.h>
void main( )
{
float num1, num2, product;
printf("Enter two numbers: ");
scanf("%f %f",&num1,&num2);
[55]

Structured Programming Approach

product = num1*num2;

Prof: S. Rathod

/* Performs multiplication and stores it */

printf("Product: %f",product);
getch();
}
Output:
Enter two numbers: 2.4 1.1 Product: 2.640000

Write a simple program to calculate the square of a number


Program:
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int x, y;
printf("Enter a number:");
scanf("%d",&x);
y=x*x;
printf("The square of %d is %d",x,y);
getch();
}

[56]

Structured Programming Approach

Prof: S. Rathod

Write a Program to find Simple Interest


#include<stdio.h>
#include<conio.h>
void main ()
{
float Int_rate, years, principal, simple_Int;
clrscr();
printf("Enter the principal amount, rate of interest and no. of years:");
scanf("%f%f%f", &principal, &Int_rate, &years);
simple_Int = principal * Int_rate*years / 100;
printf("The simple interest is %f", simple_Int) ;
getch();
}

calculate area and perimeter of rectangle.


#include<stdio.h>
#include<conio.h>
void main ()
{
float length, breadth, area, perimeter;
clrscr();
printf("Enter the length and breadth of the rectangle:");
[57]

Structured Programming Approach

Prof: S. Rathod

scanf("%f%f",&length,&breadth);
area= length * breadth;
perimeter= 2* (length + breadth);
printf("The area of rectangle is= %f and its perimeter is = %f",area, perimeter);
getch();
}

calculate area of circle.


#include<stdio.h>
#include<conio.h>
void main ()
{
float r, area;
clrscr();
printf("Enter the radius of a circle:");
scanf("%f",&r);
area=3.14 *r*r;
printf("The area is equal:%f",area);
getch();
}

[58]

Structured Programming Approach

Prof: S. Rathod

Write a Program to find ASCII value of a character entered by user.


#include <stdio.h>
#include <conio.h>
void main()
{
char ch;
printf("Enter a character: ");
scanf("%c",&ch);

/* Takes a character from user */

printf("ASCII value of %c = %d",ch,ch);


getch();
}
Output: Enter a character: G ASCII value of G = 71

Write C Program to compute remainder and quotient


#include <stdio.h>
#include <conio.h>
void main()
{
int dividend, divisor, quotient, remainder;
printf("Enter dividend: ");
scanf("%d",&dividend);
printf("Enter divisor: ");
[59]

Structured Programming Approach

Prof: S. Rathod

scanf("%d",&divisor);
quotient=dividend/divisor;
remainder=dividend%divisor;

/* Computes quotient */
/* Computes remainder */

printf("Quotient = %d\n",quotient);
printf("Remainder = %d",remainder);
getch();
}
Output:
Enter dividend: 25 Enter divisor: 4
Quotient = 6 Remainder = 1

Write program to computes the size of variable using sizeof operator.


#include <stdio.h>
#include <conio.h>
void main()
{
int a;
float b;
double c;
char d;
printf("Size of int: %d bytes\n",sizeof(a));
printf("Size of float: %d bytes\n",sizeof(b));
[60]

Structured Programming Approach

Prof: S. Rathod

printf("Size of double: %d bytes\n",sizeof(c));


printf("Size of char: %d byte\n",sizeof(d));
getch();
}
Output:
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte

Greatest of three no using ternary operator


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,maxT;
clrscr();
printf("Enter three nos. : ");
scanf("%d%d%d",&a,&b,&c);
printf("\nFirst No. is : %d",a);
printf("\nSecond No. is : %d",b);
printf("\nThird No. is : %d",c);
[61]

Structured Programming Approach

Prof: S. Rathod

printf("\nFrom ternary operator");


maxT=a>b?(a>c?a:c):(b>c?b:c);
printf("Greatest no. is :%d",maxT);
getch();
}

OUTPUT :
Enter three nos. : 20 40 10
First No. is : 20
Second No. is : 40
Third No. is : 10
From ternary operator, Greatest no. is : 40

Write a program to swap two integers using temporary variable & without
using temporary variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,temp;
clrscr();
printf("Enter two nos. : ");
[62]

Structured Programming Approach

Prof: S. Rathod

scanf("%d %d", &num1,&num2);


printf("\nUsing temporary variable,");
printf("\nBefore swapping : %d %d",num1,num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("\nAfter swapping : %d %d",num1,num2);
printf("\n\nWithout Using temporary variable,");
printf("\nBefore swapping : %d %d",num1,num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
printf("\nAfter swapping : %d %d",num1,num2);
getch();
}
OUTPUT :
Enter two nos. : 10 20
Using temporary variable,
Before swapping : 10 20 After swapping : 20 10
Without Using temporary variable,
Before swapping : 20 10 After swapping : 10 20

[63]

Structured Programming Approach

Prof: S. Rathod

Write a program to check whether an integer is odd or even using conditional


operator
#include <stdio.h>
#include <conio.h>
void main()
{
int num;
printf("Enter an integer you want to check: ");
scanf("%d",&num);
((num%2)==0) ? printf("%d is even.",num) : printf("%d is odd.",num);
getch();
}

Calculate the gross salary that includes basic salary, 50%DA, 40%HRA.
#include<stdio.h>
#include<conio.h>
void main()
{
float basic_salary,HRA,DA,Gross_Salary;
clrscr();
printf("Enter the basic salary : Rs. ");
scanf("%f", &basic_salary);
[64]

Structured Programming Approach

Prof: S. Rathod

HRA = 0.4 * basic_salary;


DA = 0.5 * basic_salary;
Gross_Salary=basic_salary + DA + HRA;
printf("The Gross Salary is : %f",Gross_Salary);
getch();
}
OUTPUT :
Enter the basic salary : Rs. 100
The Gross Salary is : 190.000000

Program to find roots of a quadratic equation using standard functions when


coefficients are entered by user.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
float x1,x2;
clrscr();
printf("Enter the coefficients of the quadratic equation:");
scanf("%d %d %d",&a,&b,&c);
[65]

Structured Programming Approach

Prof: S. Rathod

x1=(-b+pow((b*b-4*a*c),0.5))/(2*a);
x2=(-b-pow((b*b-4*a*c),0.5))/(2*a);
printf("The roots of quadratic equation are:%f and %f",x1,x2);
getch();
}
Program to accept temperature in Fahrenheit from user and convert into the
Celsius.
#include<stdio.h>
#include<conio.h>
void main()
{
float fah,cel;
clrscr();
printf("Enter temperature(fahrenheit) : ");
scanf("%f",&fah);
cel = (fah-32)/1.8;
printf("Temperature(celsius) : %4.2f ",cel);
getch();
}
OUTPUT :
Enter temperature(fahrenheit) : 68
Temperature(celsius) : 20.00

[66]

Structured Programming Approach

Prof: S. Rathod

EXPRESSING ALGORITHM-SELECTION AND ITERATION

SELECTION
The statement in the program executed in order in which they appear is called
sequential execution.but sometime,
1) Need to select set of statement from several alternatives
2) Skip statement depending on condition
3) Repeat statement for known time.

Control Statements
Control structures are used to transfer the control from one statement in a program
to any other statement. The control statements are classified are followed.
Unconditional Statement
Decision Making Statement
Looping Statement
Conditional control statement:
Condition to make a decision which involve logical test.
test result either true or false.
Depending upon result, statement will execute and after that control transfer
to statement in program and start execution from that point. This is called
conditional execution.
c provide variety of conditional statements
a) if
b) if -else
c) nested if
d) ladder elseif
e) switch statement
[67]

Structured Programming Approach

Prof: S. Rathod

The if, if...else and nested if...else statement are used to make one-time decisions in
C Programming, that is, to execute some code/s and ignore some code/s depending
upon the test expression.
IF STATEMENTS
The if statements allows branching (decision making) depending upon the value or
state of variables. This allows statements to be executed or skipped, depending
upon decisions.
Syntax
if (test expression)
{
statement/s to be executed if test expression is true;(simple or compound)
}
simple: Single statement no need to specify braces
compound: collection of statement place between braces
Flowchart of if statement

[68]

Structured Programming Approach

Prof: S. Rathod

Write a C program to print the number entered by user only if the number
entered is negative.
#include <stdio.h>
Void main()
{
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0)
{

/* checking whether number is less than 0 or not. */

printf("Number = %d\n",num);
}
printf("The if statement in C programming is easy.");
getch();
}
Output1:
Enter a number to check. -2
Number = -2
The if statement in C programming is easy.
Output2:
Enter a number to check. 5
The if statement in C programming is easy.
[69]

Structured Programming Approach

Prof: S. Rathod

program uses an if statement to validate the user's input to be in the range 10.
#include <stdio.h>
void main()
{
while( valid == 0 )
{
printf("Enter a number between 1 and 10 -->");
scanf("%d",&number);

/* assume number is valid */

valid = 1;
if( number < 1 )
{
printf("Number is below 1. Please re-enter\n");
valid = 0;
}
if( number > 10 )
{
printf("Number is above 10. Please re-enter\n");
valid = 0;
}
}
printf("The number is %d\n", number );
[70]

Structured Programming Approach

Prof: S. Rathod

if...else statement
The if...else statement is used if the programmer wants to execute some statement/s
when the test expression is true and execute some other statement/s if the test
expression is false.
Syntax of if...else
if (test expression)
{
statements to be executed if test expression is true;(simple or compound)
}
else
{
statements to be executed if test expression is false;(simple or compound)
}
Flowchart of if...else statement

[71]

Structured Programming Approach

Prof: S. Rathod

Write a C program to check whether a number entered by user is even or odd


#include <stdio.h>
int main()
{
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
Output1:
Enter a number you want to check. 25 25 is odd.
Output2:
Enter a number you want to check. 2 2 is even.

WAP to check whether a character is vowel or consonant


#include<stdio.h>
#include<conio.h>
void main()
[72]

Structured Programming Approach

Prof: S. Rathod

{
char ch;
clrscr();
printf(enter character);
scanf(%c,&ch);
if(ch==a||ch==A||ch==e||ch==E||ch==i||ch==I||ch==o||ch==O||ch==u
||ch==U)
printf(\n %c is vowel,ch);
else
printf(\n%c is consonant,ch);
getch();
}
OUTPUT:
enter character i
i is vowel

Write a program to check whether a year is leap year or not using if else
statement.(three criteria 1)divisible by 4 2) divisible by 400 3) not divisible by
100 according to gregorian calendar )
#include<stdio.h>
#include<conio.h>
void main()
{
[73]

Structured Programming Approach

Prof: S. Rathod

int year;
clrscr();
printf("Enter a year:");
scanf("%d",&year);
if(year%4==0 && year%100!=0 || year%100==0 && year%400==0)
printf("Leap Year");
else
printf("Not a leap year");
getch();
}
Output 1: Enter year: 1900 1900 is not a leap year.
Output 2: Enter year: 2012 2012 is a leap year.

Write a program to check whether a character is alphabet or not.


#include <stdio.h>
#include <conio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
[74]

Structured Programming Approach

Prof: S. Rathod

printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Output 1: Enter a character: *
* is not an alphabet
Output 2: Enter a character: K
K is an alphabet

Write a program that calculates the square roots of a quadratic equation.


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,d,r1,r2;
clrscr();
printf("Enter coefficients(a,b,c) : ");
scanf("%f%f%f",&a,&b,&c);
if((b*b-4*a*c)>=0)
{
d = sqrt(b*b - 4*a*c);
r1 = (-b+d)/2*a;
r2 = (-b-d)/2*a;
printf("Roots are : %4.2f , %4.2f ",r1,r2);
}
[75]

Structured Programming Approach

Prof: S. Rathod

else printf("Roots are imaginary.");


getch();
}
OUTPUT :
Enter coefficients(a,b,c) : 1 4 4
Roots are : -2.00 , -2.00
Enter coefficients(a,b,c) : 1 -5 6
Roots are : 3.00 , 2.00
Enter coefficients(a,b,c) : 1 3 5
Roots are imaginary.
Nested if Statement:
If an if..else statement appears as a statement in another if or else block then it is
called nested if..else.
Syntax:
if (condition1)
{
if (condition2)
{
Statement block-1;
}
else
{
Statement block-2;
}
}
else
{
Statement block-3;
[76]

Structured Programming Approach

Prof: S. Rathod

}
Next statement
Execution:
1. Check testexpression-1
2. If true check test expression-2
If expression2 is true
Execute statement block-1 and goto step3
If the expression-2 is false
Execute statement block-2 and goto step3
If the expression-1 is false
Execute statement block 3 and goto step 3
3. Execute next statement following if ..else structure.
/* Program to find the biggest of three numbers using nested if */
#include<stdio h>
#include<conio h>
void main()
{
int a,b,c;
clrscr();
printf("Enter three integers:");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("a is the biggest");
else
printf("c is biggest");
}
else
[77]

Structured Programming Approach

Prof: S. Rathod

if(b>c)
printf("b is biggest");
else
printf("c is biggest");
getch();
}
Output 1:
Enter three integers:78 542 12
B is biggest
Output 2:
Enter three integers:178 54 12
A is biggest
Output 3:
Enter three integers:8 2 12
C is biggest
ladder elseif OR if..else if Statement
The else..if ladder is used for multiple decision making. In this construct each else
is associated with another if statement. The default else is optional. The conditions
are evaluated from top to bottom one by one.
Syntax:
if(condition1)
{
Statement block 1;
}
else if(condition2)
{
Statement block-2;
[78]

Structured Programming Approach

Prof: S. Rathod

}
else if(condition3)
{
Statement block-3;
}

else if(condition-n)
{
Statement block-n;
}
else
{
Default statement block;
}
Execution:
In this structure the testing starting from the top, if any of the test expression
returns true then the corresponding statement block will be executed and
then the control is transferred to the next statement following the whole else
if.
If none of the test expression is true then the default else block if present will
be evaluated and the control is transferred to the next statement.
/* To display the grade of the student */
ALGORITHM:
Step 1: START.
Step 2: PRINT Enter the percentage(0-100) : .
Step 3: INPUT perc.
Step 4: IF perc>=70 , PRINT Distinction AND GOTO step 9.
Step 5: IF perc>=60 , PRINT First Class AND GOTO step 9.
Step 6: IF perc>=50 , PRINT Second Class AND GOTO step 9.
Step 7: IF perc>=40 , PRINT Pass Class AND GOTO step 9.
[79]

Structured Programming Approach

Prof: S. Rathod

Step 8: PRINT Fail.


Step 9: STOP.
FLOWCHART:

PROGRAM
#include<stdio h>
#include<conio h>
[80]

Structured Programming Approach

Prof: S. Rathod

void main()
{
float avg;
clrscr();
printf("Enter the average mark of the student:");
scanf("%f",&avg);
if(avg<=100&& avg>=0)
{
if(avg>=70)
printf("\n Distinction");
else if(avg>=60)
printf("\n\tFirst class");
else if(avg>50)
printf("\n\t second class");
else if(avg>40)
printf("\n\tjust pass");
else
printf("\nfail");
}
else
printf(\n invalid input);
getch();
[81]

Structured Programming Approach

Prof: S. Rathod

}
OUTPUT:
Enter percentage scored (0-100) : 65
First Class
WAP to check enter character is uppercase lowercase numeric or symbolic
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf(enter character);
scanf(%c,&ch);
if((ch>=A)&&(ch<=Z))
printf(\nuppercase);
else if((ch>=a)&&(ch<=z))
printf(\nlowercase);
else if((ch>=0)&&(ch<=9))
printf(\nnumeric);
else
printf(\nsymbol);
getch();
}

[82]

Structured Programming Approach

Prof: S. Rathod

Write a program to accept the coordinates of a point on XY plane and radius


of any circle whose center is at origin. Determine whether the point lies inside,
outside or on the circumference of the circle.
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
float x,y,r,d;
clrscr();
printf("Enter x & y co-ordinates of point : ");
scanf("%d%d",&x, &y);
printf("Enter radius : ");
scanf("%d",&r);
d = sqrt((x*x)+(y*y));
if(d<r)
printf("Point lies inside the circle.");
else if(d>r)
printf("Point lies outside the circle.");
else
printf("Point lies on the circle.");
getch();
}
OUTPUT :
Enter x & y co-ordinates of point : 3 0
Enter radius : 3
Point lies on the circle.
Enter x & y co-ordinates of point : 3 4
Enter radius : 3
Point lies outside the circle.
[83]

Structured Programming Approach

Prof: S. Rathod

Enter x & y co-ordinates of point : 4 5


Enter radius : 6
Point lies inside the circle.
SWITCH STATEMENT:
Decision making are needed when, the program encounters the situation to choose
a particular statement among many statements. If a programmer has to choose one
block of statement among many alternatives, nested if...else can be used but, this
makes programming logic complex. This type of problem can be handled in C
programming using switch statement.
Syntax
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
default:
code/s to be executed if n doesn't match to any cases;
}

The value of n is either an integer or a character in above syntax. If the value of n


matches constant in case, the relevant codes are executed and control moves out of
the switch statement. If the n doesn't matches any of the constant in case, then the
default codes are executed and control moves out of switch statement.
[84]

Structured Programming Approach

Prof: S. Rathod

Write a program using Switch case, which display the number in word format
when user enters in digit from 0 to 9.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a single digit number:");
scanf("%d",&n);
switch(n)
{
case 0:printf("Zero");
break;
[85]

Structured Programming Approach

Prof: S. Rathod

case 1:printf("One");
break;
case 2:printf("Two");
break;
case 3:printf("Three");
break;
case 4:printf("Four");
break;
case 5:printf("Five");
break;
case 6:printf("Six");
break;
case 7:printf("Seven");
break;
case 8:printf("Eight");
break;
case 9:printf("Nine");
break;
}
getch();
}

Write a program using Switch case, which display the Months in word format
when user enters in digit from 1 to 12.
#include<stdio.h>
#include<conio.h>
void main()
{
int month;
clrscr();
printf("Enter a month number:");
[86]

Structured Programming Approach

Prof: S. Rathod

scanf("%d",&month);
switch(month)
{
case 1:printf("January");
break;
case 2:printf("February");
break;
case 3:printf("March");
break;
case 4:printf("April");
break;
case 5:printf("May");
break;
case 6:printf("June");
break;
case 7:printf("July");
break;
case 8:printf("August");
break;
case 9:printf("September");
break;
case 10:printf("October");
break;
case 11:printf("November");
break;
case 12: printf("December");
break;
default:printf("Invalid month number");
}
getch();
}

[87]

Structured Programming Approach

Prof: S. Rathod

Write a program for calculator using switch-case & do-while loop.


Algorithm:
Step 1: START.
Step 2: PRINT Menu: 1.Add 2.Subtract 3.Multiply 4.Divide Enter the choice :
Step 3: INPUT choice
Step 4: PRINT Enter two operands :
Step 5: INPUT a,b
Step 6: IF choice==1 , add a,b and PRINT result, AND GOTO step 11
Step 7: IF choice==2 , subtract a,b and PRINT result, AND GOTO step 11
Step 8: IF choice==3 , multiply a,b and PRINT result, AND GOTO step 11
Step 9: IF choice==4 , IF b==0, PRINT Invalid Operation ELSE divide a by b
and PRINT result, AND GOTO step 11
Step 10: PRINT Invalid choice
Step 11: PRINT Do you want to continue ?? (y/n) :
Step 12: INPUT ans
Step 13: IF ans==y OR ans==Y GOTO step 2, ELSE GOTO step 14
Step 14: STOP

[88]

Structured Programming Approach

Prof: S. Rathod

Program for calculator using switch-case and do-while.


#include<stdio.h>
#include<conio.h>
void main()
{
[89]

Structured Programming Approach

Prof: S. Rathod

int a,c,choice;
float b,d;
char ans='n';
clrscr();
do
{
printf("\n\n****MENU****");
printf("\n1.ADDITION\n2.SUBTRACTION\n3.MULTIPLICATION\n4.DIVISIO
N");
printf("\nEnter your choice : ");
scanf("%d",&choice);
printf("Enter two operands : ");
scanf("%d%f",&a,&b);
switch(choice)
{
case 1:c=a+b;
printf("Addition of two nos.is : %d",c);
break;
case 2:c=a-b;
printf("Subtraction of two nos.is : %d",c);
break;
case 3:c=a*b;
[90]

Structured Programming Approach

Prof: S. Rathod

printf("Multiplication of two nos.is : %d",c);


break;
case 4: if(b==0)
{
printf("Invalid operation");
}
else
{
d=a/b;
printf("Division of two nos.is : %f",d);
}
break;
default: printf("Wrong INPUT");
}
printf("\nDo you want to continue???");
ans = getche();
}while(ans=='y' || ans=='Y');
getch();
}
OUTPUT:
****MENU****
1.ADDITION
[91]

Structured Programming Approach

Prof: S. Rathod

2.SUBTRACTION
3.MULTIPLICATION
4.DIVISION
Enter your choice : 1
Enter two operands :
20 10
Addition of two nos.is
: 30
Do you want to
continue???y
****MENU****
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.DIVISION
Enter your choice : 4
Enter two operands :
22 0
Invalid operation
Do you want to
continue???y

[92]

Structured Programming Approach

Prof: S. Rathod

ITERATION:
LOOPING:
It is a powerful technique through which a group of statement executed
repeatedly,until certain condition satisfied.
Why looping:
It is require to execute one or more statement of program for more than once.
LOOP:
A loop consist two parts
a) control statement
b) body of loop
Control statements:
It perform logical test whose result is either true or false.
If result is true
the statement contained in the body of loop are executed
otherwise terminated
Control statement either before or after the body of loop.
Control statement is placed before the body of loop called entry
control loop.
If control statement is written after the body of loop is called exit
control loop.
Looping Mechanism:
Initialization: To set initial value of counter.
Decision:Appropriate test condition to determine whether the loop to be
executed or not.
Updation:Increment or Decrement counter value.
[93]

Structured Programming Approach

Prof: S. Rathod

TYPES:
1) while
2) do while
3) for
while:
Syntax:
while (test expression)
{
statement/s to be executed.
}

The while loop checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed, that is, code/s inside the braces { } are
executed. Then again the test expression is checked whether test expression is true
or not. This process continues until the test expression becomes false.

[94]

Structured Programming Approach

Prof: S. Rathod

#include<stdio h>
void main()
{
int i = 0;
while (i<=5)
{
printf(" the value of i is %d\n", i);
i=i+1 ;
}
}
Output :
the value of i is 0
the value of i is 1
the value of i is 2
the value of i is 3
the value of i is 4
Wap for sum of Digit
#include <stdio.h>
#include <conio.h>
void main()
{
int no,sum=0,rem;
clrscr();
printf(enter number);
scanf(%d,&no);
while(no!=0)
[95]

Structured Programming Approach

Prof: S. Rathod

{
rem=no%10;
sum=sum+rem;
no=no/10;
}
printf(\nsum of digit=%d,sum);
getch();
}
OUTPUT:
enter number 123
sum of digit=6

Wap for reverse of number


#include <stdio.h>
#include <conio.h>
void main()
{
int no,rev=0,rem;
clrscr();
printf(enter number);
scanf(%d,&no);
while(no!=0)
[96]

Structured Programming Approach

Prof: S. Rathod

{
rem=no%10;
rev=rev*10+rem;
no=no/10;
}
printf(\nreverse of no=%d,rev);
getch();
}
OUTPUT:
enter number 123
sum of digit=321

Wap for prime number (no divide by 1 or itself so count from 2 to n-1)
#include <stdio.h>
#include <conio.h>
void main()
{
int n,count=2;
clrscr();
printf(enter number);
scanf(%d,&no);
while(count<=n-1)
[97]

Structured Programming Approach

Prof: S. Rathod

{
if(no%count==0)
break;
else
count++;
}
if(count==no)
printf(\n no is a prime no.);
else
printf(\n no is not a prime no.);
getch();
}
OUTPUT:
enter number 7
no is a prime no.

Wap for prime number between 200 to 400 (no divide by 1 or itself so count
from 2 to n-1)
#include <stdio.h>
#include <conio.h>
void main()
{
[98]

Structured Programming Approach

Prof: S. Rathod

int i,n,x=200;
clrscr();
printf(\nFollowing are prime no between 200 to 400 );
while(x<=400)
{
i=2;
while(x%i!=0)
{
i++;
}
if(x==i)
{
printf(%d\t,x);
}
x++;
}
getch();
}

Wap for Armstrong number(sum of power of no=original no)


#include <stdio.h>
#include <conio.h>
[99]

Structured Programming Approach

Prof: S. Rathod

#include <math.h>
void main()
{
int n,temp,digit,sum=0,count=0;
clrscr();
printf(enter number);
scanf(%d,&no);
temp=no;
while(temp!=0)
{
temp=temp/10;
count++;
}
Printf(\nno of digit is %d,count);
temp=no;
while(temp!=0)
{
digit=temp%10;
sum=sum+pow(digit,count);
temp=temp/10;
}
if(no==sum)
[100]

Structured Programming Approach

Prof: S. Rathod

printf(\n no is a Armstrong no.)


else
printf(\n no not a Armstrong no.)
getch();
}
OUTPUT:
enter number 153
no of digit is 3
no is a Armstrong no.

do...while loop
In C, do...while loop is very similar to while loop. Only difference between these
two loops is that, in while loops, test expression is checked at first but, in
do...while loop code is executed at first then the condition is checked. So, the code
are executed at least once in do...while loops.
Syntax
do
{
some code/s;
}while(test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If
it is true, code/s inside body of do are executed again and the process continues
[101]

Structured Programming Approach

Prof: S. Rathod

until test expression becomes false(zero). Notice, there is semicolon in the end of
while (); in do...while loop
Write a program to add all the numbers entered by a user until user enters 0.
#include <stdio.h>
void main()
{
int sum=0,num;
do
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
} while(num!=0);
printf("sum=%d",sum);
}
Output:
Enter a number 3
Enter a number -2
Enter a number 0
sum=1
for LOOP:
Syntax :
for (initialization_statement; test_expression; update statement)
{
statements;
}
Where:
For -----> keyword
initialization_statement -----> initialize the loop index
[102]

Structured Programming Approach

Prof: S. Rathod

test_expression --------> Is a conditional expression that test loop index


reach fixed value
Update statement --------> modify loop index after each iteration
Statements --------> simple/compound
How for loop works in C programming?
The initialization statement is executed only once at the beginning of the for loop.
Then the test expression is checked by the program. If the test expression is false,
for loop is terminated. But if test expression is true then the code/s inside body of
for loop is executed and then update expression is updated. This process repeats
until test expression is false.
This flowchart describes the working of for loop in C programming.

[103]

Structured Programming Approach

Prof: S. Rathod

Handling for loop


1) i=1;
for(; i<=5;i++)
printf(\nInitialization done outside);
2) i=1;
for(; i<=5;)
printf(\nInitialization done outside and modification done inside the body of
loop);
i++;
3) i=1;
for(; ;)
printf(empty structure\n);
if(i>=5)
break;
i++;
4) for(i=1;i<=10;i++);
NOT legal but output for next condition
OUTPUT 11
Write a program to display digits from 1 to 10 using loops.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
[104]

Structured Programming Approach

Prof: S. Rathod

printf("%d\n",i);
}
getch();
}
OUTPUT:
1
2
3
4
5
6
7
8
9
10
Write a program to find the sum of first n natural numbers where n is entered
by user. Note: 1,2,3... are called natural numbers.
#include <stdio.h>
#include<conio.h>
void main()
{
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count)
{
sum=sum+count;
}
printf("Sum=%d",sum);
getch();
}

[105]

Structured Programming Approach

Prof: S. Rathod

Output
Enter the value of n.
19
Sum=190
Write a program to display character from A to Z using loops.
#include <stdio.h>
#include <conio.h>
void main()
{
char c;
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
getch();
}
Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Write a Program to calculate Factorial of a Number entered by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,fact=1;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=fact * i;
}
printf("Factorial of this number is:%d\n",fact);
getch();
[106]

Structured Programming Approach

Prof: S. Rathod

}
Write a program to check whether a number is palindrome or not
#include <stdio.h>
#include <conio.h>
void main()
{
int n, reverse=0, rem,temp;
printf("Enter an integer: ");
scanf("%d", &n);
temp=n;
while(temp!=0)
{
rem=temp%10;
reverse=reverse*10+rem;
temp/=10;
}
if(reverse==n)
printf("%d is a palindrome.",n);
else
printf("%d is not a palindrome.",n);
getch();
}
Output:
Enter an integer: 12321
12321 is a palindrome.
Write a program to print Fibonacci Series up to N, when value of N is entered
by user.
#include<stdio.h>
#include<conio.h>
void main()
[107]

Structured Programming Approach

Prof: S. Rathod

{
int a=0,b=1,c,i,n;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
printf("Fibonacci Series\n0\n1\n");
for(i=1;i<=n-2;i++)
{
c=a+b;
printf("%d\n",c);
a=b;
b=c;
}
getch();
}
Output: Enter number: 10
Fibonacci Series:
0
1
1
2
3
5
8
13
21
34
Write a program to Generate Multiplication Table up to 10.
#include <stdio.h>
#include <conio.h>
void main()
[108]

Structured Programming Approach

Prof: S. Rathod

{
int n, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{ printf("%d * %d = %d\n", n, i, n*i); }
getch();
}
Output:
Enter an integer to find multiplication table: 9
9*1=9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
Write a program for decimal to binary conversion
#include<stdio.h>
#include<conio.h>
void main()
{
int dec,bin=0,rem=0;
clrscr();
printf(\nenter no:);
[109]

Structured Programming Approach

Prof: S. Rathod

scanf(%d,&dec);
for(i=1;dec!=0;i*=10)
{
rem=dec%2;
bin=bin+i*rem;
dec=dec/2;
}
printf(\nBinary no %d,bin);
getch();
}
OUTPUT:
enter no: 5
Binary no 101

SERIES PROGRAMMING
a) 1 +1/2 + 1/3 +1/41/n
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
float sum=0.0;
clrscr();
printf("Enter the no. of terms : ");
[110]

Structured Programming Approach

Prof: S. Rathod

scanf("%d",&n);
for(i=1; i<=n; i++)
{
sum=sum+(1.0/i);
}
printf(\n sum is %f,sum);
getch();
}
b) 1 -1/2 + 1/3 -1/41/n
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,sign=1;
float sum=0.0;
clrscr();
printf("Enter the no. of terms : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
if(i%2==0)
{
sign=sign*(-1);
}
else
[111]

Structured Programming Approach

Prof: S. Rathod

{
sign=1;
}
sum=sum+sign(1.0/i);
}
printf(\n sum is %f,sum);
getch();
}
c) 1 + 1/22 + 1/32 + 1/421/n2
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,n;
float sum=0.0;
clrscr();
printf("Enter the no. of terms : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
sum=sum+(1.0)/pow(i,2);
}
printf(\n sum is %f,sum);
getch();
[112]

Structured Programming Approach

Prof: S. Rathod

}
d) 1 + 1/2!+1/3!+-----1/n!
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,fact;
float sum=0.0;
clrscr();
printf("Enter the no. of terms : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
fact=fact*i;
sum=sum+1.0/fact;
}
printf(\n sum is %f,sum);
getch();
}
Write a program to find the result of the series :
1 + 2^2 / 3! + 3^2 / 5! + ..+ n^2 / m!*/
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
[113]

Structured Programming Approach

Prof: S. Rathod

int i,j,n,fact;
long double t=0,sum=0;
clrscr();
printf("Enter the no. of terms : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
fact=1;
for(j=1; j<=((2*i)-1); j++)
{
fact=fact*j;
}
t=pow(i,2)/fact;
sum=sum+t;
}
printf("\nSum of series is : %Lf",sum);
getch();
}
OUTPUT :
Enter the no. of terms : 3
Sum of series is : 1.741667

Nested for LOOP:

[114]

Structured Programming Approach

Prof: S. Rathod

PATTERN PROGRAMMING
PATTERN 1

Program:
123
123
123

# include <conio.h>
# include <stdio.h>
void main()
[115]

Structured Programming Approach

Prof: S. Rathod

{
int i,j;
clrscr();
for(i=1;i<=3;i++)
{
for(j=i;j<=3;j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
}

Program:
111
222
333
# include <conio.h>
# include <stdio.h>
void main()
{
int i,j;
clrscr();
[116]

Structured Programming Approach

Prof: S. Rathod

for(i=1;i<=3;i++)
{
for(j=i;j<=3;j++)
{
printf("%d",i);
}
printf("\n");
}
getch();
}

Program:
ABCDE
BCDEF
CDEFG
DEFGH
EFGHI

# include <conio.h>
# include <stdio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
[117]

Structured Programming Approach

Prof: S. Rathod

for(j=i;j<=i+4;j++)
{
printf("%c",(char)(64+j));
}
printf("\n");
}
getch();
}
OUTPUT:
ABCDE
BCDEF
CDEFG
DEFGH
EFGHI

PATTERN 2

Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
[118]

Structured Programming Approach

Prof: S. Rathod

printf("* ");
}
printf("\n");
}
getch();
}

#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}
A
AB
ABC
ABCD
#include <stdio.h>
#include <conio.h>
void main()
[119]

Structured Programming Approach

Prof: S. Rathod

{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
printf("%c ",(char)(64+j));
}
printf("\n");
}
getch();
}

#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
[120]

Structured Programming Approach

Prof: S. Rathod

printf("%c ",(char)(64+i));
}
printf("\n");
}
getch();
}

#include<stdio.h>
#include <conio.h>
void main()
{
int rows,i,j,k=1;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;++j)
{
printf("%d ",k);
k++;
}
[121]

Structured Programming Approach

Prof: S. Rathod

printf("\n");
}
getch();}

REVERSE OF PATTERN 2

#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=rows;i>=1;--i)
{
for(j=1;j<=i;++j)
{
printf("* ");
}
printf("\n");
}
getch();
}

[122]

Structured Programming Approach

Prof: S. Rathod

#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,rows;
printf("Enter the number of rows: ");
scanf("%d",&rows);
for(i=rows;i>=1;--i)
{
for(j=1;j<=i;++j)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}
PATTERN 3

#include<stdio.h>
#include<conio.h>
void main()
[123]

Structured Programming Approach

Prof: S. Rathod

{
int n,i,j,sp,k=1;
clrscr();
printf("Enter no. of lines : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(sp=1;sp<=n-i;sp++)
{
printf(" ");
}
for(j=1; j<=i;j++)
{
printf("%c",(char)(64+k));
k++;
}
printf("\n");
}
getch();
}

Program:
1
12
123
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,sp;
clrscr();
[124]

Structured Programming Approach

Prof: S. Rathod

printf("Enter no. of lines : ");


scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(sp=1;sp<=n-i;sp++)
{
printf(" ");
}
for(j=1; j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
}

Program:
1
22
333

#include<stdio.h>
#include<conio.h>
[125]

Structured Programming Approach

Prof: S. Rathod

void main()
{
int n,i,j,sp;
clrscr();
printf("Enter no. of lines : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(sp=1;sp<=n-i;sp++)
{
printf(" ");
}
for(j=1; j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
getch();
}

[126]

Structured Programming Approach

Prof: S. Rathod

PATTERN 4

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter the number of lines:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
[127]

Structured Programming Approach

Prof: S. Rathod

{
printf("*");
}
for(j=i-1;j>=1;j--)
{
printf("*");
}
printf("\n");
}
getch();
}

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter the number of lines:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
[128]

Structured Programming Approach

Prof: S. Rathod

{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("%d",j);
}
for(j=i-1;j>=1;j--)
{
printf("%d",j);
}
printf("\n");
}
getch();
}

OUTPUT:
Enter the number of lines:3
1
121
12321

[129]

Structured Programming Approach

Prof: S. Rathod

REVERSE OF PATTERN 4

#include<stdio.h>
#include <conio.h>
void main()
{
int rows,i,j,sp;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows;i>=1;--i)
{
for(sp=0;sp<rows-i;sp++)
{
printf(" ");
}
for(j=i;j<=2*i-1;++j)
{
printf("* ");
}
for(j=0;j<i-1;++j)
{
printf("* ");
[130]

Structured Programming Approach

Prof: S. Rathod

}
printf("\n");
}
getch();
}

PATTERN 5

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter the number of * in the centre line:");
scanf("%d",&n);
[131]

Structured Programming Approach

Prof: S. Rathod

for(i=1;i<=n;i++) //upper triangle


{
for(j=1;j<=n-i;j++) //space
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}

for(i=n-1;i>=1;i--) // lower triangle


{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
[132]

Structured Programming Approach

Prof: S. Rathod

}
getch();
}

OUTPUT:
Enter the number of * in the centre line:3
*
**
***
**
*
Program to display the given pattern.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,sp;
clrscr();
printf("Enter the total no. of lines : ");
scanf("%d", &n);
n=n/2+1;
for(i=1;i<=n;i++)
{
for(sp=1;sp<=n-i;sp++)
{
printf(" ");
}
for(j=1;j<=(2*i)-1;j++)
{
printf("*");
[133]

Structured Programming Approach

Prof: S. Rathod

}
printf("\n");
}
for(i=n-1;i>=1;i--)
{
for(sp=1;sp<=n-i;sp++)
{
printf(" ");
}
for(j=1;j<=(2*i)-1;j++)
{
printf("*");
}
printf(\n);
}
getch();
}
OUTPUT :
Diamond Pattern :
Enter the total no. of lines : 5
*
***
*****
***
*
C Programming break and continue Statement
There are two statements built in C programming, break; and continue; to alter the
normal flow of a program. Loops perform a set of repetitive task until text
expression becomes false but it is sometimes desirable to skip some statement/s
inside loop or terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used. The break; statement is also
used in switch statement to exit switch statement.

[134]

Structured Programming Approach

Prof: S. Rathod

break Statement
In C programming, break is used in terminating the loop immediately after it is
encountered. The break statement is used with conditional if statement.
Syntax
break;
The break statement can be used in terminating all three loops for, while and
do...while loops.

The figure below explains the working of break statement in all three type of loops.

[135]

Structured Programming Approach

Prof: S. Rathod

Continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases,
continue statements are used.
Syntax
continue;
Just like break, continue is also used with conditional if statement.

For better understanding of how continue statements works in C programming.


Analyze the figure below which bypasses some code/s inside loops using continue
statement.

[136]

Structured Programming Approach

Prof: S. Rathod

goto Statement
In C programming, goto statement is used for altering the normal sequence of
program execution by transferring control to some other part of the program.

Syntax
goto label;
.............
.............
.............
label:
statement;

[137]

Structured Programming Approach

Prof: S. Rathod

In this syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code
below it.

Example of break,continue and goto statement


Break

continue

goto

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

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

int i;

lbl:

if(i==2||i==4)

if(i==2||i==4)

if(i<=5)

break;

continue;

printf(%d,i);

i++;

printf(%d,i);

printf(%d,i);

goto lbl;

Output: 1

Output: 135

Output:
12345

[138]

Structured Programming Approach

Prof: S. Rathod

ARRAY
Each program is designed mostly to do some kind of processing on data oe
information so that desired result generated.
To hold data or value to be processed.we declare variable of specific data in
the program.
Each variable can hold only one value at a time.
We have seen few input value for data processing & declare few variable so
it is manageable.
It we need to perform operation on several input so declare lots of variable
with separate name so it became tedious task.
This problem can be handled by using derived data structure Array.
Definition
It is a set of similar data-items that shares common name.Due to this
property array also call homogeneous data structure.
Array is a sequential/linear data structure which means value are stored and
Placed in the adjacent memory location.
Array can be differentiate from one another by their index position .
Types of Arrays:

[139]

Structured Programming Approach

Prof: S. Rathod

Single dimensional Array:


So far,we have been been declaring simple variables as:
int i;
It declares a single variable, named i, of type int. It is also possible to declare an
array of several elements.
The declaration is given as
Syntax:
data-type array_name[size];

Ex:

int a[10];

It declares an array, named a, consisting of ten elements, each of type int.


Simply speaking, an array is a variable that can hold more than one value. Once
an array is declared, let us see how individual elements in the array can be referred.
This is done with subscript, the number in the brackets following the array name.
This number specifies the elements position in the array. All the array elements are
numbered, starting with 0. We can represent the
array a above with a picture like this:

In C, arrays are zero-based: the ten elements of a 10-element array are numbered
from 0 to 9. The subscript which specifies a single element of an array is simply
an integer expression in square brackets.
The first element of the array is a[0],
the second element is a[1], etc.
[140]

Structured Programming Approach

Prof: S. Rathod

Thus, a[2] is not the second element of the array, but the third in memory location.
Array Initialization:
It is possible to initialize some or all elements of an array when the array is
defined. The
Syntax:
data-type array_name[size]={list of values,..};
Ex: int a[4] = {10, 20, 30, 40};
The pictorial representation of above array is

The list of values, enclosed in braces {}, separated by commas, provides the initial
values for successive elements of the array.
Till the array elements are not given any specific values, they are supposed to
contain garbage values. If the array is initialised where it is declared, mentioning
the dimension of the array is optional as in the following example.
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;

Accessing Elements of an Array:


In the following program we are using the variable i as a subscript to refer to
various elements of the array. This variable can take different values and hence can
refer to the different elements in the array in turn. This ability to use variables as
subscripts is what makes arrays so useful.
Ex:

int i;
for(i = 0; i < 10; i + +)
[141]

Structured Programming Approach

Prof: S. Rathod

{
a[i] = 0;
}
This loop sets all ten elements of the array a to 0.

Entering Data into an Array:


Here is the section of code that places data into an array:
Ex:

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


{
printf ( "\nEnter the values " ) ;
scanf ( "%d", &a[i] ) ;
}

The for loop is used to receive the values from the user 10 times repeatedly. The
first time through the loop, i has a value 0, so the scanf( ) function will cause the
value entered to be stored in the array element a[0] which the first element of the
array. This process will be repeated until i becomes 9.
In scanf( ) function, we have used the address of operator (&) on the
element a[i] of the array). In so doing, we are passing the address of this particular
array element to the scanf( ) function, rather than its value.
Displaying Data from an Array:
The for loop is used to display the values enter by user in array.
Ex:

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


{
printf ( "%d", a[i] ) ;
}
[142]

Structured Programming Approach

Prof: S. Rathod

Write a program which accepts the N numbers and display it using the
concept of Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[100];
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
for(i=0;i<=n-1;i++)
{
printf("Enter a value:");
scanf("%d",&a[i]);
}
printf("The numbers entered are\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",a[i]);
}
getch();
}

[143]

Structured Programming Approach

Prof: S. Rathod

C program to find the sum marks of n students using arrays.


#include <stdio.h>
int main()
{
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}
Output:
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45

[144]

Structured Programming Approach

Prof: S. Rathod

To find average marks obtained by a class of 30 students in a test


#include<stdio.h>
#include<conio.h>
void main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ;
/* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
/* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
{
sum = sum + marks[i] ; /* read data from an array*/
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
getch( );
}
Write a program which displays all Even and Odd numbers presents in N
numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[100],even=0;
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
[145]

Structured Programming Approach

Prof: S. Rathod

for(i=0;i<n;i++)
{
printf("Enter a value:");
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
if (a[i]%2==0)
Even++;
}
printf("The count of even numbers is %d and that of odd numbers is %d",even,(neven));
getch();
}

Write a program for finding largest element in an array.


#include<stdio.h>
#include<conio.h>
void main( )
{
int n,i,a[100],large;
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
[146]

Structured Programming Approach

Prof: S. Rathod

for(i=0;i<=n-1;i++)
{
printf("Enter a value:");
scanf("%d",&a[i]);
}
large=a[0];
for(i=1;i<=n-1;i++)
{
if(large<a[i])
large=a[i];
}
printf("The largest number is %d",large);
getch();
}

Write a program for finding smallest element in an array.


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[100],small;
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
[147]

Structured Programming Approach

Prof: S. Rathod

for(i=0;i<=n-1;i++)
{
printf("Enter a value:");
scanf("%d",&a[i]);
}
small=a[0];
for(i=1;i<n;i++)
{
if(small>a[i])
small=a[i];
}
printf("The smallest number is %d",small);
getch();
}

Write a program for searching an element in an array.


#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, a[100], key, found=0;
clrscr();
printf( "Enter the number of elements : " );
scanf( "%d" , &n);
[148]

Structured Programming Approach

Prof: S. Rathod

for(i=0;i<n;i++)
{
printf( "Enter value %d : " , i+1);
scanf( "%d" , &a[i] );
}
printf("Enter the element to be searched : ");
scanf( "%d", &key);
for( i = 0 ; i < n ; i++)
{
if( key == a[i] )
{
printf( "\nThe element %d is found at index : %d ", key, i);
found = 1;
}
}
if( !found )
printf( "\nElement Not Found in array" );
getch();
}
OUTPUT :
Enter the number of elements : 5
Enter value 1 : 24
Enter value 2 : 65
Enter value 3 : 32
[149]

Structured Programming Approach

Prof: S. Rathod

Enter value 4 : 17
Enter value 5 : 65
Enter the element to be searched : 65
The element 65 is found at index : 1
The element 65 is found at index : 4

Write a program for sorting elements in an array in descending order.


#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, j, temp, a[100] ;
clrscr();
printf( "Enter the number of elements : ");
scanf( "%d" , &n);
for( i = 0; i <= n -1 ; i++)
{
printf("Enter %d value : ",i+1);
scanf("%d",&a[i]);
}
for( i = 0; i < n -1 ; i++)
{
for( j = 0; j < n -1- i ; j++)
{
[150]

Structured Programming Approach

if(a[j] < a[j+1])

Prof: S. Rathod

//descending if ascending sign will be >

{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf( " After sorting : \n " );
for( i = 0; i <= n -1; i++)
{
printf( " %d \n ", a[i] );
}
getch();
}
OUTPUT :
Enter the number of elements : 5
Enter 1 value : 25
Enter 2 value : 50
Enter 3 value : 60
Enter 4 value : 14
Enter 5 value : 32
After sorting :
60
[151]

Structured Programming Approach

Prof: S. Rathod

50
32
25
14

Write a program for sorting elements in an array in ascending order.


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,j,n,temp,num;
clrscr();
printf("Enter a no of elements:");
scanf("%d",&n);
printf("enter element is");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
[152]

Structured Programming Approach

Prof: S. Rathod

{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}

WAP for reverse of array using different array


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[100],rev[100];
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
[153]

Structured Programming Approach

Prof: S. Rathod

for(i=0;i<n;i++)
{
printf("Enter a value:");
scanf("%d",&a[i]);
}
for(i=0;i<=n-1;i++)
{
rev[n-i-1]=a[i];
}
printf("The reverse of this array is:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",rev[i]);
}
getch();
}
OUTPUT:
Enter the number of elements:4
Enter a value:4
Enter a value:3
Enter a value:2
Enter a value:1
The reverse of this array is:
1
[154]

Structured Programming Approach

Prof: S. Rathod

2
3
4
Write a program to reverse an array using same array.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[100], temp;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter array elements : ");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<n/2; i++)
{
temp=a[n-1-i];
a[n-1-i]=a[i];
a[i]=temp;
}
printf("The reverse of the array is: ");
[155]

Structured Programming Approach

Prof: S. Rathod

for(i=0;i<=n-1;i++)
{
printf("%d",a[i]);
}
getch();
}
Output:
Enter the number of elements : 4
Enter array elements : 1 2 3 4
The reverse of the array is : 4 3 2 1

OR
Write a program to reverse an array containing n elements using the same
array.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[30], i, j, num, temp;
clrscr();
printf("\nEnter no of elements : ");
scanf("%d", &num);
for (i = 0; i < num; i++)
{
[156]

Structured Programming Approach

Prof: S. Rathod

scanf("%d", &arr[i]);
}
j = i - 1;
i = 0;
while (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
printf("\nResult after reversal : ");
for (i = 0; i < num; i++)
{
printf("%d \t", arr[i]);
}
getch();
}
Output:
Enter no of elements : 5
11 22 33 44 55
Result after reversal : 55 44 33 22 11

[157]

Structured Programming Approach

Prof: S. Rathod

Write a program to delete an element from the array. Program should take
input for the position or index from where the element is to be deleted.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100], pos, i, n;
clrscr();
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for ( i = 0 ; i < n ; i++ )
{
scanf("%d", &a[i]);
}
printf("Enter the location where you wish to delete element\n");
scanf("%d", &pos);
for(i=pos-1;i<n-1;i++)
{
a[i]=a[i+1];
}
n=n-1;

//one element less

printf("Resultant array is\n");


for( i = 0 ; i < n ; i++ )
[158]

Structured Programming Approach

Prof: S. Rathod

{
printf("%d\n", a[i]);
}
getch();
}
OUTPUT
Enter number of elements in array
5
Enter 5 elements
1
2
3
4
5
Enter the location where you wish to delete element
4
Resultant array is
1
2
3
5

Write a program to find standard deviation


#include<stdio.h>
[159]

Structured Programming Approach

Prof: S. Rathod

#include<conio.h>
#include<math.h>
void main()
{
int n, i, a[100];
float avg, sum=0, sd;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter array elements : ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
avg += a[i];
}
avg /=n;
for(i=0; i<n; i++)
{
sum +=pow(a[i]-avg,2);
}
sd = sum/n;
sd = pow(sd,0.6);
printf("The standard deviation is %f", sd);
getch();
[160]

Structured Programming Approach

Prof: S. Rathod

}
Output:
Enter the number of elements : 5
Enter array elements : 1 2 3 4 5
The standard deviation is 1.414214

Write a program to cyclically rotate an array in left or right direction


#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, a[100], temp, ch=0;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter array elements : ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("\nCyclically rotate the array in \n\t1.Left\n\t2.Right");
scanf("%d", ch);
switch(ch)
{
[161]

Structured Programming Approach

Prof: S. Rathod

case 1 :
temp=a[0];
for(i=0;i<n;I++)
{
a[i-1]=a[i];
}
a[n-1]=templ
break;
case 2 :
temp=a[n-1];
for(i=n-1; i>0; i--)
{
a[i]=a[i-1];
}
a[0]=temp;
break;
default : printf("INVALID CHOICE");
}
if(ch==1 || ch==2)
{
printf("\nRotated array is : ");
for(i=0; i <=n-1; i++)
{
printf(" %d ",a[i]);
[162]

Structured Programming Approach

Prof: S. Rathod

}
getch();
}

Output:
Enter number of elements : 5
Enter array elements : 1 2 3 4 5
Cyclically rotate the array in
1. Left
2. Right
Enter your choice : 1
Rotated array is : 2 3 4 5 1
Enter number of elements : 5
Enter array eleements : 6 7 8 9 10
Cyclically rotate the array in
1.Left
2.Right
Enter your choice : 2
Rotated array is : 10 6 7 8 9
Enter number of elements : 5
Enter array elements : 1 3 5 7 9
Cyclically roate the array in
1.Left
2.Right
[163]

Structured Programming Approach

Prof: S. Rathod

Enter your choice : 3


INVALID CHOICE

Multidimensional Array
Multidimensional arrays are simply arrays of arrays. The general format of
multidimensional array is:
Syntax:
data-type array_name[size][size];
Ex:
int a[4][2];

Here a is an array of 4 rows and 2 columns. A multidimensional array like a[4][2]


is stored in consecutive memory locations as a[0][0], a[0][1], a[1][0], a[1][1],
a[2][0], a[2][1], a[3][0], a[3][1] ], a[4][0], a[4][1]. Its pictorial representation is
given as follows:

Thus, 1234 is stored in a[0][0], 56 is stored in a[0][1] and so on. The above
arrangement highlights the fact that a two- dimensional array is nothing but a
collection of a number of one- dimensional arrays placed one below the other.

[164]

Structured Programming Approach

Prof: S. Rathod

Initializing a multidimensional Array:


Initialization of a 2-dimensional array is
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;
The arrangement of array elements of a two-dimensional array in memory is
shown below:

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;

/* array declaration */

clrscr();
printf("enter the elements\n");
/* Entering Data into an Array*/
for(i=0;i<3;i++)

/* loop for rows*/

{
for(j=0;j<3;j++)

/*loop for column*/

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

/* store data in array */

}
[165]

Structured Programming Approach

Prof: S. Rathod

}
printf("matrix\n");
/*Displaying Data from an Array*/
for(i=0;i<3;i++)

/* loop for rows*/

{
for(j=0;j<3;j++)

/*loop for column*/

{
printf("%d",a[i][j]);

/* store data in array */

}
printf("\n");
}
getch();
}

Write a program for finding Largest element in the Matrix.


#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,i,j,a[10][10],large;
printf("Enter the number of rows and columns:");
scanf("%d %d",&m,&n);
for(i=0;i<=m-1;i++)
{
[166]

Structured Programming Approach

Prof: S. Rathod

for(j=0;j<=n-1;j++)
{
printf("Enter a value:");
scanf("%d",&a[i][j]);
}
}

large=a[0][0];
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
if(large<a[i][j])
large=a[i][j];
}
}
printf("The largest element in the matrix is %d",large);
getch();
}

Write a program to display addition of diagonal elements of Matrix.


#include<stdio.h>
#include<conio.h>
void main()
[167]

Structured Programming Approach

Prof: S. Rathod

{
int m,n,i,j,a[10][10],sum=0;
clrscr();
printf("Enter the number of rows / columns:");
scanf("%d",&m);
n=m;
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
printf("Enter a value:");
scanf("%d",&a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
sum+=a[i][j];
}
}
printf("The sum of diagonal elements is %d",sum);
getch();
[168]

Structured Programming Approach

Prof: S. Rathod

Program to find transpose of given matrix.


#include<stdio.h>
#include<conio.h>
void main()
{
int r1, c1, i, j;
int a[10][10], b[10][10];
clrscr();
printf("\nEnter the number of rows & columns for Matrix 1 : ");
scanf("%d%d",&r1, &c1);
printf("\nEnter the elements of Matrix 1 : \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nTranspose of Matrix 1 : \n");
for(i=0; i < c1; i++)
{
for(j=0; j < r1; j++)
[169]

Structured Programming Approach

Prof: S. Rathod

{
b[i][j] = a[j][i];
printf(" %d ", b[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT :
Enter the number of rows & columns for Matrix 1 : 3 2
Enter the elements of Matrix 1 :
12
34
56
Transpose of Matrix 1 :
135
246

Program for matrix addition.


#include<stdio.h>
#include<conio.h>
void main()
{
int r1,c1,r2,c2,i,j;
[170]

Structured Programming Approach

Prof: S. Rathod

int a[10][10],b[10][10],c[10][10];
clrscr();
printf("\nEnter the number of rows & columns for Matrix 1 : ");
scanf("%d%d",&r1, &c1);
printf("\nEnter the number of rows & columns for Matrix 2 : ");
scanf("%d%d",&r2, &c2);
if(r1==r2 && c1==c2)
{
printf("\nEnter the elements of Matrix 1 : \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nEnter the elements of Matrix 2 : \n");
for(i=0; i<r2; i++)
{
for(j=0; j<c2; j++)
{
scanf("%d", &b[i][j]);
}
}
[171]

Structured Programming Approach

Prof: S. Rathod

printf("\nMatrix Addition : \n");


for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
c[i][j] = a[i][j] + b[i][j];
printf(" %d ", c[i][j]);
}
}
else
{
printf("\nMatrix addition NOT possible.");
}
getch();
}
OUTPUT :
Enter the number of rows & columns for Matrix 1 : 3 3
Enter the number of rows & columns for Matrix 2 : 2 3
Matrix addition NOT possible.
Enter the number of rows & columns for Matrix 1 : 2 3
Enter the number of rows & columns for Matrix 2 : 2 3
Enter the elements of Matrix 1 :
123
456
[172]

Structured Programming Approach

Prof: S. Rathod

Enter the elements of Matrix 2 :


789
123
Matrix Addition :
8 10 12
579

Program for matrix multiplication.


#include<stdio.h>
#include<conio.h>
void main()
{ int r1, c1, r2, c2, i, j, k ;
int a[10][10], b[10][10], c[10][10];
clrscr();
printf("\nEnter the number of rows & columns for Matrix 1 : ");
scanf("%d%d",&r1, &c1);
printf("\nEnter the number of rows & columns for Matrix 2 : ");
scanf("%d%d",&r2, &c2);
if(c1 != r2)
{
printf("\nMatrix multiplication NOT possible.");
}
else
{
[173]

Structured Programming Approach

Prof: S. Rathod

printf("\nEnter the elements of Matrix 1 : \n");


for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nEnter the elements of Matrix 2 : \n");
for(i=0; i<r2; i++)
{
for(j=0; j<c2; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("\nMatrix Multiplication : \n");
for(i=0; i < r1; i++)
{
for(j=0; j < c2; j++)
{
c[i][j] = 0;
for(k=0; k < r2; k++)
{
[174]

Structured Programming Approach

Prof: S. Rathod

c[i][j] += a[i][k] * b[k][j];


}
printf(" %d ", c[i][j]);
}
printf("\n");
}
}
getch();
}
OUTPUT :
Enter the number of rows & columns for Matrix 1 : 2 3
Enter the number of rows & columns for Matrix 2 : 2 3
Matrix multiplication NOT possible.
Enter the number of rows & columns for Matrix 1 : 3 2
Enter the number of rows & columns for Matrix 2 : 2 3
Enter the elements of Matrix 1 :
12
34
56
Enter the elements of Matrix 2 :
10 11 12
456
Matrix Multiplication :
18 21 24
[175]

Structured Programming Approach

Prof: S. Rathod

46 53 60
74 85 96

MATRIX FORM
Symmetric AT=A
Skew Symmetric AT=-A

WAP for Symmetric Matrix


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],n,m,i,j,d,c;
clrscr();
printf("Enter the dimension of matrix as n*m\n");
scanf("%d%d",&n,&m);
printf("Enter %d elements",m*n);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
[176]

Structured Programming Approach

Prof: S. Rathod

printf("Your matrix is....\n");


for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
c=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j]==a[j][i])
{
c++;
}
}
}
if(c==(m*n))
{
printf("Your Matrix is Symmetric Matrix\n");
}
[177]

Structured Programming Approach

Prof: S. Rathod

else
{
printf("Your Matrix is Not Symmetric Matrix\n");
}
getch();
}

/* OUTPUT
Enter the dimension of matrix as n*m
3
3
Enter 9 elements
1
2
3
2
4
5
3
5
8
Your matrix is....
1

5
[178]

Structured Programming Approach

Prof: S. Rathod

Your Matrix is Symmetric Matrix


*/

WAP for Matrix is Symmetric skew Matrix or not


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],n,m,i,j,d,c;
clrscr();
printf("Enter the dimension of matrix as n*m\n");
scanf("%d%d",&n,&m);
printf("Enter %d elements",m*n);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Your matrix is....\n");
for(i=0;i<n;i++)
{
[179]

Structured Programming Approach

Prof: S. Rathod

for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
c=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j]==((-1)*a[j][i]))
{
c++;
}
}
}
if(c==(m*n))
{
printf("Your Matrix is Symmetric skew Matrix\n");
}
else
{
printf("Your Matrix is Not Symmetric skew Matrix\n");
[180]

Structured Programming Approach

Prof: S. Rathod

}
getch();
}
OUTPUT
Enter the dimension of matrix as n*m
3
3
Enter 9 elements
0
-3
2
3
0
-5
-2
5
0
Your matrix is....
0

-3

-5

-2

Your Matrix is Symmetric skew Matrix

[181]

Structured Programming Approach

Prof: S. Rathod

Four experiments are performed, each experiment consisting of six test


results. The result for each experiment is given below. WAP to compute and
display the average of the test results for each experiment.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,sum;
float avg,a[4][7]={
{23.2,31.5,16.9,28.0,26.3,28.2,0.0},
{34.8,45.2,20.8,39.4,33.4,36.8,0.0},
{19.4,50.6,45.1,20.8,50.6,13.4,0.0},
{36.9,42.7,20.8,10.2,16.8,42.7,0.0}
};
clrscr();
printf("\nsum and average is\n");
for(i=0;i<4;i++)
{
sum=0;
avg=0.0;

//a[i][6]=0;
[182]

Structured Programming Approach

Prof: S. Rathod

for(j=0;j<6;j++)
{
sum=sum+a[i][j];

//a[i][6]=a[i][6]+a[i][j];

}
avg=sum/6.0;

//a[i][6]=a[i][6]/6.0;

a[i][6]=avg;
}
printf("\nT1\tT2\tT3\tT4\tT5\tT6\tavg\n");
for(i=0;i<4;i++)
{
for(j=0;j<7;j++)
{
printf("%.2f\t",a[i][j]);
}
printf("\n");
}
getch();
}
/*
OUTPUT

sum and average is

T1

T2

T3

T4

T5

T6

avg
[183]

Structured Programming Approach

Prof: S. Rathod

23.20 31.50 16.90 28.00 26.30 28.20 25.33


34.80 45.20 20.80 39.40 33.40 36.80 34.50
19.40 50.60 45.10 20.80 50.60 13.40 32.83
36.90 42.70 20.80 10.20 16.80 42.70 27.67

[184]

Structured Programming Approach

Prof: S. Rathod

Strings in C
A string constant is a one-dimensional array of characters terminated by a null
( \0 ).
For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
Each character in the array occupies one byte of memory and the last
character is always \0.
The terminating null (\0) is important, because it is the only way the
functions that work with a string can know where the string ends.
Elements of the character array are stored in contiguous memory locations.
Figure shows the way a character array is stored in memory.
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that,
strings are of chartype.
Syntax:
char s[5];

Initialization of strings:
In C, string can be initialized in different number of ways.
a) Individual character:
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};

[185]

Structured Programming Approach

Prof: S. Rathod

b) Single String:
char c[]="abcd";
OR,
char c[5]="abcd";

Reading words from user.


char c[20];
scanf("%s",c);

Program to demonstrate printing of a string


void main( )
{
char name[ ] = "PIIT" ; /* String Initialization*/
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] ) ;
i++ ;
}
[186]

Structured Programming Approach

Prof: S. Rathod

}
Output: PIIT
We have initialized a character array (string), and then printed out the elements of
this array within a while loop until null character (\0) is encountered.

Write a C program to illustrate how to read string from terminal.


#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s",name);
return 0;
}
Output:
Enter name: PIIT
Your name is PIIT

Write a program to accept and display the string entered by user using gets()
function.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[100];
[187]

Structured Programming Approach

Prof: S. Rathod

printf("Enter a string\n");
gets(a);
printf("The entered string is: %s",a);
getch();
}

String Library Functions: #include<string.h>


Function

Use

strlen

Finds length of a string (counts the number of characters present in


a string)

strlwr

Converts a string to lowercase

strupr

Converts a string to uppercase

strcat

Appends one string at the end of another

strncat

Appends first n characters of a string at the end of another

strcpy

Copies a string into another

strncpy

Copies first n characters of one string into another. The base


addresses of the source and target strings should be supplied to
this function.

strcmp

Compares two strings

strncmp

Compares first n characters of 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.

strcmpi

Compares two strings without regard to case ("i" denotes that this
function ignores case)

stricmp

Compares two strings without regard to case (identical to strcmpi)


[188]

Structured Programming Approach

Prof: S. Rathod

strnicmp

Compares first n characters of two strings without regard to case

strdup

Duplicates a string

strchr

Finds first occurrence of a given character in a string

strrchr

Finds last occurrence of a given character in a string

strstr

Finds first occurrence of a given string in another string

strset

Sets all characters of string to a given character

strnset

Sets first n characters of a string to a given character

strrev

Reverses string

Write a program to accept the string using gets() function from user and
display its length.
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
int l;
char a[100];
printf("Enter a string\n");
gets(a);
l=strlen(a);
printf("The length of the entered string is: %d",l);
getch();
}

C Program to Find the Length of a String without using strlen() funtion.


#include <stdio.h>
int main()
{
[189]

Structured Programming Approach

Prof: S. Rathod

char s[100],i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
return 0;
}
Enter a string: Piit Length of string:4
OR
#include <stdio.h>
int main()
{
char s[100];
int len=0;
clrscr();
printf("Enter a string: ");
gets(s);
while(s[len]!=\0)
{
len++;
}
printf("\nLength of string: %d",len);
return 0;
}
Enter a string: Piit
Length of string:4
[190]

Structured Programming Approach

Prof: S. Rathod

Write a program to implement string functions.


#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{ int len;
char a[100],b[100],c[100];
clrscr();
printf("Enter first string : ");
gets(a);
printf("\nEnter second string : ");
gets(b);
printf("\nSTRLEN function ");
len=strlen(a);
printf("\nThe length of the First string(%s) is : %d \n",a,len);
printf("\nSTRCPY function");
strcpy(c,a);
printf("\nThe new copied string is : %s \n",c);
printf("\nSTRCMP function\n ");
if(strcmp(a,b)==0)
printf("The strings are equal\n ");
else if(strcmp(a,b)>0)
printf("'%s' string is greater\n",a);
else printf("'%s' string is greater\n",b);
printf("\nSTRCAT function\n");
strcat(a,b);
printf("The concatenated string is %s",a);
getch();
}
OUTPUT :
Enter first string : COMPUTER
Enter second string : components
STRLEN function
The length of the First string(COMPUTER) is : 8
STRCPY function
[191]

Structured Programming Approach

Prof: S. Rathod

The new copied string is : COMPUTER


STRCMP function
'components' string is greater
STRCAT function
The concatenated string is COMPUTERcomponents

Write a program to compute total vowels present in the string entered by user.
#include<conio.h>
#include<stdio.h>
void main()
{
char a[100];
int i,len=0,count=0;
clrscr();
printf("Enter a string:\n");
gets(a);
while(a[len]!=0)
{
len++;
}
for(i=0;i<=len-1;i++)
{
if(a[i]=='a' ||a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u' ||a[i]=='A' || a[i]=='E' ||
a[i]=='I' || a[i]=='O' || a[i]=='U')
count++;
}
printf("The total number of vowels are: %d",count);
getch();
}
Write a program to find total number of vowels, total number of spaces, total
number of digits and total number of consonants present in the string.
#include<conio.h>
#include<stdio.h>
void main()
{
char a[100];
[192]

Structured Programming Approach

Prof: S. Rathod

int i,len=0,vowels=0,spaces=0,digits=0,consonants=0;
clrscr();
printf("Enter a string:\n");
gets(a);
while(a[len]!=0)
{
len++;
}
for(i=0;i<=len-1;i++)
{
if(a[i]=='a' ||a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u' ||a[i]=='A' || a[i]=='E' ||
a[i]=='I' || a[i]=='O' || a[i]=='U')
Vowels++;
Else
{
if((a[i]>='a' && a[i]<='z') || (a[i]>='A' && a[i]<='Z'))
Consonants++;
Else
{
if(a[i]>='0' &&a[i]<='9')
Digits++;
Else
{
if(a[i]==' ')
Spaces++;
}
}
}
}
printf("The total number of vowels are: %d\nThe total number of spaces
are:%d\nThe total number of digits are: %d\nThe total number of consonants are:
%d", vowels,spaces,digits,consonants);
getch();
}

[193]

Structured Programming Approach

Prof: S. Rathod

WAp for Reverse of given string without using function


#include <stdio.h>
int main()
{
char s[100],temp;
int n,i;
clrscr();
printf("Enter a string: ");
gets(s);
while(s[n]!=\0)
{
n++;
}
for(i=0;i<n/2;i++)
{
temp=s[n-1-i];
s[n-1-i]=s[i];
s[i]=temp;
}
printf("\nreverse of string: %s",s);
return 0;
}

[194]

Structured Programming Approach

Prof: S. Rathod

OR
WAp for Reverse of given string
#include<stdio.h>
#include<string.h>
void main()
{
char str[100],temp;
int i,j=0;
clrscr();
printf("nEnter the string :");
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("nReverse string is :%s",str);
getch();
}
OUTPUT
nEnter the string :hello all
nReverse string is :lla olleh
WAP to count no of word in given string
#include<stdio.h>
#include<string.h>
void main()
[195]

Structured Programming Approach

Prof: S. Rathod

{
Char str[50];
Int i,word=0;
printf(enter string:);
gets(str);
for(i=0; str[i]!=\0; i++)
{
if(str[i]== )
Word++;
}
printf(\n no of word=%d,word+1);
getch();
}
OUTPUT:
enter string:This is test string
no of word=4

WAp for Palindrome using string function and without using string function
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50],temp[50];
int n=0,i,j;
clrscr();
printf("\n enter string:");
gets(str);
[196]

Structured Programming Approach

Prof: S. Rathod

printf("\n USING STRING FUNCTION\n");


strcpy(temp,str);
strrev(temp);
if(strcmp(temp,str)==0)
printf("\n string %s is in palindrome",str);
else
printf("\n string %s is not in palindrome",str);
printf("\nWITHOUT STRING FUNCTION");
while(str[n]!='\0')
{
n++;
}
for(i=0,j=n-1;i<n/2;i++,j--)
{
if(str[i]!=str[j])
{
printf("\n string %s is not in palindrome",str);
break;
}
}
if(i==n/2)
printf("\n string %s is in palindrome",str);
getch();
}
[197]

Structured Programming Approach

Prof: S. Rathod

OUTPUT:
enter string:madam
USING STRING FUNCTION
string madam is in palindrome
WITHOUT STRING FUNCTION
string madam is in palindrome

WAP to convert the given string into uppercase if it is in lowercase without


using predefined functions.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
int i;
clrscr();
printf("Enter any string->");
scanf("%s",str);
printf("The string is->%s",str);
for(i=0;i<=20;i++)
{
if(str[i]>=97&&str[i]<=122)
str[i]=str[i]-32;
}
[198]

Structured Programming Approach

Prof: S. Rathod

printf("\nThe string in uppercase is->%s",str);


getch();
}
Output:
The string is->abcd
The string in lowercase is->ABCD

Write a user defined function to copy one string into another. [ Hint: Dont
use string header file ]
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100], s2[100];
int i;
clrscr();
printf("\nEnter the string :");
gets(s1);
i = 0;
while (s1[i] != '\0')
{
s2[i] = s1[i];
i++;
}
[199]

Structured Programming Approach

Prof: S. Rathod

s2[i] = '\0';
printf("\nCopied String is %s ", s2);
getch();
}
OUTPUT:
Enter the string : main
Copied String is main

WAP to replace a character in the given string using another character.


#include<stdio.h>
#include<conio.h>
void main()
{
int n=0,i;
char a[10],m,rep='y';
clrscr();
printf("\nEnter a string: ");
gets(a);
printf("\nEnter character to be replaced: ");
scanf("%c",&m);
while(a[n]!='\0')
{
n++;
[200]

Structured Programming Approach

Prof: S. Rathod

}
for(i=0;i<n;i++)
{
if(a[i]==m)
{
a[i]=rep;
}
}
printf("after replacement %s",a);
getch();
}
OUTPUT
Enter a string: hello
Enter character to be replaced: l
after replacement heyyo

[201]

Structured Programming Approach

Prof: S. Rathod

C Programming Functions
In programming, a function is a segment that groups code to perform a specific
task. A C program has at least one function main( ). Without main() function, there
is technically no C program.

Function and looping difference


Loop are used when we need to repeat group of instructions where as function is
contrast (which may consist loops used for evaluating tasks) can be called more
than once at a any part of program wherever required
Types of C functions
There are two types of functions in C programming:
Library function
User defined function
Library function
Library functions are the in-built function in C programming system.
For example:
main() The execution of every C program starts from this main() function.
printf() prinf() is used for displaying output in C.
scanf() scanf() is used for taking input in C.

User defined function


C allows programmer to define their own function according to their requirement.
These types of functions are known as user-defined functions. Suppose, a
programmer wants to find factorial of a number and check whether it is prime or
not in same program. Then, he/she can create two separate user-defined functions
[202]

Structured Programming Approach

Prof: S. Rathod

in that program: one for finding factorial and other for checking whether it is prime
or not.
Advantages of user defined functions
1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those
codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by
making different functions.

I. Function prototype (declaration):


Every function in C programming should be declared before they are used. These
type of declaration are also called function prototype. Function prototype gives
compiler information about function name, type of arguments to be passed and
return type.
Syntax of function prototype:
return_type function_name(type(1) argument(1),....,type(n) argument(n));
In the following example,int add(int a, int b); is a function prototype which
provides following information to the compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.

Function prototype are not needed if user-definition function is written before


main() function.
[203]

Structured Programming Approach

Prof: S. Rathod

II. Function call:


Control of the program cannot be transferred to user-defined function unless it is
called invoked.
Syntax of function call
function_name(argument(1),....argument(n));
In the a following example, function call is made using statement
add(num1,num2); from main(). This make the control of program jump from that
statement to function definition and executes the codes inside that function.

III. Function definition:


Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
Function definition has two major components:
1. Function declarator:
Function declarator is the first line of function definition. When a function is
called, control of the program is transferred to function declarator.
Syntax of function declaratory
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and declarator are almost same except, there is no
semicolon at the end of declarator and function declarator is followed by
function body.
[204]

Structured Programming Approach

Prof: S. Rathod

2. Function body
Function declarator is followed by body of function inside braces.
Passing arguments to functions
In programming, argument(parameter) refers to data this is passed to
function(function definition) while calling function. In above example two
variable, num1 and num2 are passed to
function during function call and these arguments are accepted by arguments a and
b in function definition.

Arguments that are passed in function call and arguments that are accepted in
function definition should have same data type.
For example:
If argument num1 was of int type and num2 was of float type then, argument
variable a should be of type int and b should be of type float,i.e., type of argument
during function call and function definition should be same.
A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function definition to calling
function.
[205]

Structured Programming Approach

Prof: S. Rathod

Syntax of return statement


return (expression);
For example:
return a;
return (a+b);

In above example, value of variable add in add() function is returned and that value
is stored in variable sum in main() function. The data type of expression in return
statement should also match the return type of function
C Programming User-defined functions
Write a C program to add two integers. Make a function add to add integers and
display sum in main() function.
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
[206]

Structured Programming Approach

Prof: S. Rathod

printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{ /* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}

Types of User-defined Functions in C Programming


For better understanding of arguments and return type in functions, user-defined
functions can be categorized as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
[207]

Structured Programming Approach

Prof: S. Rathod

4. Function with arguments and return value.

1) Function with no arguments and no return value.


#include<stdio.h>
#include<conio.h>
void add();
int main()
{
add();
getch();
return 0;
}
void add() ///no parameter
{
int a,b,sum;
printf(enter two integer);
scanf(%d%d,&a,&b);
sum=a+b;
printf(sum=%d,sum);
}

[208]

Structured Programming Approach

Prof: S. Rathod

2) Function with no arguments but return value


#include<stdio.h>
#include<conio.h>
int add();
int main()
{
int sum;
sum=add();
printf(Sum is %d,sum);
getch();
return 0;
}
int add()

//no parameter

{
int a,b,c;
printf(enter two integer);
scanf(%d%d,&a,&b);
c=a+b;
return c;

//value is written

[209]

Structured Programming Approach

Prof: S. Rathod

3) Function with arguments but no return value


#include<stdio.h>
#include<conio.h>
void add(int,int);

///function with parameter

int main()
{
int a,b;
printf(enter two integer);
scanf(%d%d,&a,&b);
add(a,b);

//parameter passed to function

getch();
return 0;
}
void add(int x,int y)

//parameter

{
int sum;
sum=x+y;
printf(sum is=%d,sum);
}

[210]

Structured Programming Approach

Prof: S. Rathod

4) Function with arguments and return value.


#include<stdio.h>
#include<conio.h>
int add(int,int);

//with parameter and return value

int main()
{
int a,b,sum;
printf(enter two integer);
scanf(%d%d,&a,&b);
sum=add(a,b);
printf(Sum is %d,sum);
getch();
return 0;
}
int add(int x,int y)

// parameter

{
int z;
z=x+y;
return z;

//value is written

[211]

Structured Programming Approach

Prof: S. Rathod

WAP to accept nos and display same.


#include<conio.h>
void main()
{
int n;
void display (int n);
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
display(n);
getch();
}
void display (int n)
{
int i;
for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
}

[212]

Structured Programming Approach

Prof: S. Rathod

Write a program to calculate average of three numbers using function.


#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,n3;
void avg (int a, int b, int c);
clrscr();
printf("Enter three numbers:");
scanf("%d %d %d",&n1,&n2,&n3);
avg(n1,n2,n3);
getch();
}
void avg (int a, int b, int c)
{
float average;
average=(a+b+c)/3.0;
printf("Average=%f",average);
}

[213]

Structured Programming Approach

Prof: S. Rathod

Write a program to find factorial of a number using user defined function.


#include<stdio.h>
#include<conio.h>
void main()
{
int no,factorial;
int fact (int no);
clrscr();
printf("Enter a number:");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial=%d",factorial);
getch();
}
int fact (int no)
{
int i,ans;
for(i=1,ans=1;i<=no;i++)
{
ans=ans*i;
}
return ans;
[214]

Structured Programming Approach

Prof: S. Rathod

Write a program to generate multiplication table of N number when value of


N is given by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
void mul(int n);
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
mul(n);
getch();
}
void mul(int n)
{
int i;
for(i=1;i<=10;i++)
{
printf("%d X %d = %d\n",n,i,(n*i));
[215]

Structured Programming Approach

Prof: S. Rathod

}
}

Write a program which displays all ODD numbers up to N when value of N is


entered by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
void odd(int n);
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
odd(n);
getch();
}
void odd(int n)
{
int i;
for(i=0;i<=n-1;i++)
{
[216]

Structured Programming Approach

Prof: S. Rathod

printf("%d\n",2*i+1);
}
}

Write a program to check whether the entered number is prime or not Using
Function.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
void prime(int n);
clrscr();
printf("Enter a number:");
scanf("%d",&n);
prime(n);
getch();
}
void prime(int n)
{
int i=2;
while(n%i!=0)
[217]

Structured Programming Approach

Prof: S. Rathod

{
i++;
}
if(n==i)
{
printf("Prime Number");
}
else
{
printf("Not a prime number");
}
}
/* Program for GCD and LCM using functions. */
#include<stdio.h>
#include<conio.h>
int GCD (int no1, int no2);
int LCM (int no1, int no2);
void main()
{
int no1,no2,gcd,lcm;
clrscr();
printf("Enter two numbers : ");
scanf("%d%d",&no1,&no2);
gcd = GCD(no1,no2);
if(gcd==1)
[218]

Structured Programming Approach

Prof: S. Rathod

printf("\nGCD doesnt exist");


else
printf("\nGCD = %d",gcd);
lcm = LCM(no1,no2);
printf("\nLCM = %d",lcm);
getch();
}
int GCD (int no1, int no2)
{
int gcd;
if(no1<no2)
gcd=no1;
else
gcd=no2;
while(no1%gcd!=0 || no2%gcd!=0)
{
gcd--;
}
return gcd;
}
int LCM (int no1, int no2)
{
int lcm;
if(no1>no2)
lcm=no1;
else
lcm=no2;
while(lcm%no1!=0 || lcm%no2!=0)
{
lcm++;
}
return lcm;
[219]

Structured Programming Approach

Prof: S. Rathod

}
/* OUTPUT :
Enter two numbers : 16 24
GCD = 8
LCM = 48
*/
Program for nPr and nCr.
#include<stdio.h>
#include<conio.h>
int fact (int no);
void main()
{
int n, r, ncr, npr;
clrscr();
printf("Enter the values of n and r : ");
scanf("%d%d", &n, &r);
ncr = fact(n) / (fact(r) * fact(n-r));
printf("\n nCr = %d", ncr);
npr = fact(n) / fact(n-r);
printf("\n nPr = %d", npr);
getch();
}
int fact (int no)
{
int i,ans;
for(i=1,ans=1;i<=no;i++)
[220]

Structured Programming Approach

Prof: S. Rathod

{
ans=ans*i;
}
return ans;
}
/* OUTPUT :
Enter the values of n and r : 8 2
nCr = 28
nPr = 56
Call by value and reference
Call by value
1) While Passing Parameters using call by value , xerox copy of original
parameter is created and passed to the called function.
2) Any update made inside user defined function will not affect the original value
of variable in calling function.
3) As their scope is limited to only function so they cannot alter the values inside
main function.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int,int); //prototype
int main()
{
[221]

Structured Programming Approach

Prof: S. Rathod

int a=5,b=7;
printf(value before call a=%d and b=%d\n,a,b);
swap(a,b);

//calling a and b are actual parameter

printf(value after call a=%d and b=%d\n,a,b);


getch()
return 0;
}
void swap(int p,int q)
{
int temp;
temp=p;
p=q;
q=temp;
printf(value after swapping p=%d and q=%d\n,p,q);
}

OUTPUT:
Value before call a=5 and b=7
Value after swapping p=7 and q=5
Value after a call a=5 and b=7

[222]

Structured Programming Approach

Prof: S. Rathod

Call by reference
1) While passing parameter using call by address scheme , we are passing the
actual address of the variable to the called function.
2) Any updates made inside the called function will modify the original copy
since we are directly modifying the content of the exact memory location.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *,int *); //prototype
int main()
{
int a=5,b=7;
printf(value before call a=%d and b=%d\n,a,b);
swap(&a,&b);

//calling a and b with address passed

printf(value after call a=%d and b=%d\n,a,b);


getch()
return 0;
}
void swap(int *p,int *q)
{
int temp;
temp=*p;
*p=*q;
[223]

Structured Programming Approach

Prof: S. Rathod

*q=temp;
}
OUTPUT:
Value before call a=5 and b=7
Value after a call a=7 and b=5
MORE ADVANCE FEATURE:
1) Passing array as a parameter
Like an variable an entire array can be passed as parameter in same
manner,but we must have to understand some hidden fact collectively about
function,array and pointer.
The name of array in fact itself is a pointer which holds the address of
first location of an array. This is base address

Example:int x[5];
x is name of array it hold first address called base address i.e x[0]
x=&x[0];

WAP to find sum of the elements of array.Define function for summation.


#include<stdio.h>
#include<conio.h>
int sum(int []); //equivalent to int sum(int *);
int main()
{
[224]

Structured Programming Approach

Prof: S. Rathod

int a[]={3,9,6,12,10};
int result;
clrscr();
result=sum(a); //passing array as a parameter equivalent to result=sum(&a[0])
printf(Sum of elements is =%d,result);
getch();
return 0;
}
int sum(int x[5])

//equivalent to int sum(int *x)

{
int c=0,i;
for(i=0;i<5;i++)
{
c=c+x[i];
}
return c;
}
OUTPUT:
Sum of element=40

[225]

Structured Programming Approach

Prof: S. Rathod

2) Function as a parameter to function:


#include<stdio.h>
#include<conio.h>
int max(int,int);
int main()
{
int a,b,c,d,g;
clrscr();
printf(enter four unequal no);
scanf(%d%d%d%d,&a,&b,&c,&d);
g=max(max(a,b),max(c,d));
printf(largest number is %d,g);
getch();
return 0;
}
int max(int m,int n)
{
return (m>n)?m:n;
}
enter four unequal no
7,9,15,12
Largest number is 15
[226]

Structured Programming Approach

Prof: S. Rathod

C Programming Recursion
A function that calls itself is known as recursive function and this technique is
known as recursion in C programming.

Write a C program to find sum of first n natural numbers using recursion.


Note: Positive integers are known as natural number i.e. 1,2, 3....n
#include <stdio.h>
int sum(int n);
int main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}

int sum(int n)
{
if(n==0)
return n
else
[227]

Structured Programming Approach

return n+sum(n-1);

Prof: S. Rathod

/*self call to function sum() */

}
Output
Enter a positive integer: 5
15

In, this simple C program, sum() function is invoked from the same function. If n
is not equal to 0 then, the function calls itself passing argument 1 less than the
previous argument it was called with. Suppose, n is 5 initially. Then, during next
function calls, 4 is passed to function and the value of argument decreases by 1 in
each recursive call. When, n becomes equal to 0, the value of n is returned

which is the sum numbers from 5 to 1.


For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
[228]

Structured Programming Approach

Prof: S. Rathod

=5+4+6
=5+10
=15

Every recursive function must be provided with a way to end the recursion. In this
example when, n is equal to 0, there is no recursive call and recursion ends.

Advantages and Disadvantages of Recursion


Recursion is more elegant and requires few variables which make program clean.
Recursion can be used to replace complex nesting code by dividing the problem
into same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult
to debug the code containing recursion.

C program to Calculate Factorial of a Number Using Recursion

#include<stdio.h>
#include<conio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
[229]

Structured Programming Approach

Prof: S. Rathod

scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}
Output:
Enter an positive integer: 6
Factorial of 6 = 72

Write a Program for Fibonacci series using recursive function.


Algorithm:

main()
Step 1: START
Step 2: PRINT Enter no. of elements :
Step 3: INPUT n
Step 4: PRINT Fibonacci Series :
Step 5: INITIALIZE i = 1
[230]

Structured Programming Approach

Prof: S. Rathod

Step 6: IF i <= n, THEN GOTO Step 7, ELSE GOTO Step 10.


Step 7: term = CALL fibo(i)
Step 8: PRINT term
Step 9: INCREMENT i by 1, AND GOTO Step 6.
Step 10: STOP

fibo(int f)
Step 1: START
Step 2: IF f == 1, GOTO Step 3, ELSE GOTO Step 4.
Step 3: RETURN 0.
Step 4: IF f == 2, GOTO Step 5, ELSE GOTO Step 6.
Step 5: RETURN 1.
Step 6: next = (fibo(f-1) + fibo(f-2))
Step 7: RETURN next.
main()

[231]

Structured Programming Approach

Prof: S. Rathod

fibo (int f)

[232]

Structured Programming Approach

Prof: S. Rathod

Program for Fibonacci series using recursive function.


#include<stdio.h>
#include<conio.h>
int fibo (int);
void main()
{ int n, i, term;
clrscr();
printf("Enter the number of elements : ");
scanf("%d",&n);
printf("\nFibonacci Series");
for(i=1; i<=n; i++)
{ term = fibo(i);
printf("\n %d", term);
[233]

Structured Programming Approach

Prof: S. Rathod

}
getch();
}
int fibo (int f)
{
int next = 0 ;
if(f == 1)
return 0;
else if(f == 2)
return 1;
else
{
next = fibo(f-1) + fibo(f-2);
return next;
}
}

OUTPUT:
Enter the number of elements : 6
Fibonacci Series:
011235

[234]

Structured Programming Approach

Prof: S. Rathod

Program for x^y using recursive function.


#include<stdio.h>
#include<conio.h>
int power(int x,int y);
void main()
{
int p,x,y;
clrscr();
printf(enter x and y);
scanf(%d%d,&x,&y);
p=power(x,y);
printf(\n the value x raised to y is=%d,p);
getch();
}
int power(int x,int y)
{
if(y==0)
return 1;
else if(y==1)
return x;
else
return (x* power(x,y-1));
[235]

Structured Programming Approach

Prof: S. Rathod

}
OUTPUT:
enter x and y 3 4
the value x raised to y is =81

TYPES OF VARIABLE:
variable is just a named area of storage that can hold a single value (numeric or
character). The C language demands that you declare the name of each variable
that you are going to use and its type, or class, before you actually try to do
anything with it.
The Programming language C has two main variable types

Local Variables
Global Variables

Local Variables:

Local variables scope is confined within the block or function where it is


defined. Local variables must always be defined at the top of a block.
When a local variable is defined - it is not initialized by the system, you
must initialize it yourself.
When execution of the block starts the variable is available, and when the
block ends the variable 'dies'.

Global variable :

Global variable is defined at the top of the program file and it can be visible
and modified by any function that may reference it.
Global variables are initialized automatically by the system when you define
them!

[236]

Structured Programming Approach

Data Type

Initialser

int

char

'\0'

float

pointer

NULL

Prof: S. Rathod

STORAGE CLASSES
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have
four different storage classes in a C program
Auto
Register
Static
extern
Automatic variables:
A variable declared inside a function without any storage class
specification, is by default an automatic variable.
They are created when a function is called and are destroyed automatically
when the function exits.
Automatic variables can also be called local variables because they are local
to a function.
By default they are assigned garbage value by the compiler.Since, variable
inside a function is automatic by default, keyword auto are rarely used.

[237]

Structured Programming Approach

Prof: S. Rathod

Example:
void main()
{
int detail;
or
auto int detail;
}

//Both are same

Register variables:
Keyword to declare register variable
register
Example
register int a;
Register variables are similar to automatic variable and exists inside that
particular function only.
If the compiler encounters register variable, it tries to store variable in
microprocessor's register rather than memory.
Value stored in register are much faster than that of memory.
Register variable not store the address of variable
Static variables:
A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and
goes out of scope, static is initialized only once and remains into existence till the
end of program. A static variable can either be internal or external depending upon
the place of declaration. Scope of internal static variable remains inside the
function in which it is defined. External static variables remain restricted to scope
of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.

[238]

Structured Programming Approach

Prof: S. Rathod

void test(); //Function declaration (discussed in next topic)


main()
{
test();
test();
test();
}
void test()
{
static int a = 0;
a = a+1;
printf("%d\t",a);
}
output :
1
2
3

//Static variable

extern variables:
External variable can be accessed by any function. They are also known as
global variables. Variables declared outside every function are external
variables.
In case of large program, containing more than one file, if the global variable
is declared in file 1 and that variable is used in file 2 then, compiler will
show error. To solve this problem, keyword extern is used in file 2 to
indicate that, the variable specified is global variable and declared in another
file.
#include<stdio.h>
void Check();
int a=5; /* a is global variable because it is outside every function */
int main()
{
a+=4;
Check();
[239]

Structured Programming Approach

Prof: S. Rathod

return 0;
}
void Check()
{
++a;
printf("a=%d\n",a);
}
Output:
a=10

[240]

Structured Programming Approach

Prof: S. Rathod

STRUCTURE
Structure is a collection of the data of different data types. A structure is used for
handling a group of related data items of different data types.
Declaring a Structure
The general form of a structure declaration statement is given below:
Syntax:
struct structure_name
{
Data-type structure_element_1;
Data-type structure_element_2;
Data-type structure_element_3;
......
};
Once the new structure data type has been defined one or more variables can be
declared to be of that type. The general format is given as
struct structure_name varible1,varible2, varible3;
EX:
struct book
{
char name ;
float price ;
int pages ;
};
[241]

Structured Programming Approach

Prof: S. Rathod

struct book b1, b2, b3 ;

is same as...
struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

The example above defines a new data type called struct book. Here the
keyword struct hold the details of data field, namely, name, price, pages. These
fields are called as structure elements or members. Structure elements can be of
different data types . book is the name of the structure and is called structure
tag.b1,b2,b3 are the structure variables.
Note the following points while declaring a structure type:
The closing brace in the structure type declaration must be followed by a
semicolon.
It is important to understand that a structure type declaration does not tell the
compiler to reserve any space in memory. All a structure declaration does is, it
defines the form of the structure.
Usually structure type declaration appears at the top of the source code file,
before any variables or functions are defined.

[242]

Structured Programming Approach

Prof: S. Rathod

Accessing Structure Elements


In arrays we can access individual elements of an array using a subscript.
Structures use a different scheme. They use a dot (.) operator.

Syntax:
structure variable . structure element;

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

Ex: to refer to price of b1 we would use,


b1.price
Structure elements can be accessed through a pointer to a structure using the arrow
(->) operator.
b1->price

Program to display information of three books


main( )
{
struct book
{
char name ;
float price ;
[243]

Structured Programming Approach

Prof: S. Rathod

int pages ;
};
struct book b1, b2, b3 ;
printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ;
printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;
}
output...
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512

Array of Structures
It is possible to define a array of structures for example if we are maintaining
information of all the students in the college and if 100 students are studying in the
college. We need to use an array than single variables. We can define an array of
structures as shown in the following example:
[244]

Structured Programming Approach

Prof: S. Rathod

An array of structures can be assigned initial values just as any other array can.
Remember that each element is a structure that must be assigned corresponding
initial values as illustrated below.
#include< stdio.h >
main()
{
struct info
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
struct info std[100];
int I,n;
printf(Enter the number of students);
scanf(%d,&n);
printf( Enter Id_no,name address combination age\n);
for(I=0;I < n;I++)
scanf(%d%s%s%s%d,&std[I].id_no,&std[I].name,&std[I].address,
&std[I].combination,&std[I].age);
printf(\n Student information);
for (I=0;I< n;I++)
printf(%d%s%s%s%d\n,
,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);
}
Structure within a structure:
A structure may be defined as a member of another structure. In such structures the
declaration of the embedded structure must appear before the declarations of other
structures.
[245]

Structured Programming Approach

Prof: S. Rathod

Program using Structure to accept student name, roll number, date of birth
and marks in three subject. Calculate total and display result in descending
order of total marks.
#include<conio.h>
#include<stdio.h>
struct student
{
char name[20];
int roll_no;
struct DOB
{
int day;
int month;
int year;
}dob;
int physics,chem,maths,total;
};
void main()
{
struct student s[100],temp;
int n,i,j;
clrscr();
printf("Enter the number of students : ");
scanf("%d", &n);
for(i=0; i<=n-1; i++)
{
printf("\nEnter the student's name : ");
scanf("%s", s[i].name);
printf("Enter roll number
: ");
scanf("%d", &s[i].roll_no);
printf("Enter date of birth
: ");
[246]

Structured Programming Approach

Prof: S. Rathod

scanf("%d-%d-%d", &s[i].dob.day, &s[i].dob.month, &s[i].dob.year);


printf("Enter marks in 3 subjects : ");
scanf("%d%d%d", &s[i].physics, &s[i].chem, &s[i].maths);
s[i].total = s[i].physics + s[i].chem + s[i].maths;
}
for(i=0; i<n; i++)
{
for(j=0; j<n-1-i ; j++)
{
if(s[j].total < s[j+1].total)
{
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
printf("\nName\t RNo.\t DOB\t Phy\t Chem\t Maths\t Total\n");
printf("-------------------------------------------------------\n");
for(i=0; i<=n-1; i++)
{
printf(" %s\t %d\t %d-%d-%d\t ", s[i].name, s[i].roll_no,
s[i].dob.day, s[i].dob.month, s[i].dob.year);
printf("%d\t %d\t %d\t %d\n", s[i].physics, s[i].chem, s[i].maths,
s[i].total);
}
getch();
}
/* OUTPUT :
Enter the number of students : 3
Enter the student's name : abc
Enter roll number
: 01
[247]

Structured Programming Approach

Prof: S. Rathod

Enter date of birth


: 3-2-95
Enter marks in 3 subjects : 23 34 21
Enter the student's name : xyz
Enter roll number
: 02
Enter date of birth
: 4-6-94
Enter marks in 3 subjects : 32
21 31
Enter the student's name : pqr
Enter roll number
: 03
Enter date of birth
: 6-1-95
Enter marks in 3 subjects : 32 43 26
Name RNo. DOB Phy Chem Maths Total
-------------------------------------------------------pqr
3 6-1-95
32 43
26
101
xyz
2 4-6-94
32 21
31
84
abc
1 3-2-95
23 34
21
78
*/
UNION
Unions are quite similar to the structures in C. Union is also a derived type as
structure. Union can be defined in same manner as structures just the keyword used
in defining union in union where keyword used in defining structure was struct. A
union is a special data type available in C that allows to store different data types
in the same memory location.
EX:
union car

[248]

Structured Programming Approach

Prof: S. Rathod

{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.
Difference between union and structure:
Though unions are similar to structure in so many ways, the difference between
them is crucial to understand. This can be demonstrated by this example:
#include <stdio.h>
union job
{

//defining a union
char name[32];
float salary;
int worker_no;

}u;
struct job1
{
char name[32];
float salary;
int worker_no;
}s;
int main()
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));

[249]

Structured Programming Approach

Prof: S. Rathod

return 0;
}
Output:
size of union = 32
size of structure = 38
There is difference in memory allocation between union and structure as suggested
in above example. The amount of memory required to store a structure variables is
the sum of memory size of all members

.
But, the memory required to store a union variable is the memory required for
largest element of an union.

[250]

Structured Programming Approach

Prof: S. Rathod

POINTER
Pointer are a fundamental part of C. If you cannot use pointers properly then you
have basically lost all the power and flexibility that C allows. The secret to C is in
its use of pointers.
C uses pointers a lot. Why?:
It is the only way to express some computations.
It produces compact and efficient code.
It provides a very powerful tool.
C uses pointers explicitly with:
Arrays,
Structures,
Functions.
What is a Pointer?
A pointer is a variable which contains the address in memory of another
variable. We can have a pointer to any variable type.
The unary operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object
pointed to by a pointer''.
pointer declaration :
<variable_type> *<name>;
//Valid pointer declaration
int *pointer;
float *fptr;
char *chptr
[251]

Structured Programming Approach

Prof: S. Rathod

For example:
#include <stdio.h>
int main()
{
int x;
/* A normal integer*/
int *p;
/* A pointer to an integer
p = &x;
/* Read it, "assign the address of x to p" */
scanf( "%d", &x );
/* Put a value in x, we could also use p here */
printf( "%d\n", *p );
/* Note the use of the * to get the value */
getch();
return 0;
}
Consider the effect of the following code:
int x = 1, y = 2;
int *ip;
ip = &x;
y = *ip;
x = ip;
*ip
=

3;

Assume for the sake of this discussion that variable x resides at memory location
100, y at 200 and ip at 1000.
Note A pointer is a variable and thus its values need to be stored somewhere. It is
the nature of the pointer's value that is new.

[252]

Structured Programming Approach

Prof: S. Rathod

//Program to demonstrate the pointer


#include <stdio.h>
int main()
{
int a,*ptr;
a=10;
ptr=&a;

//assign address of a to ptr,ptr pointing this location

printf(a=%d,a);
*ptr=*ptr+5;

//*ptr read value at that address

printf(a=%d,*ptr=%d\n,a,*ptr);
getch();
return 0;
}
[253]

Structured Programming Approach

Prof: S. Rathod

OUTPUT:
a=10
a=15 *ptr=15

//Program to demonstrate use of pointer

#include <stdio.h>
#include<conio.h>
int main()
{
int a,b;
int *ptr;
ptr=&a;

//assign address of a to ptr,ptr pointing this location

*ptr=10;
[254]

Structured Programming Approach

ptr=&b;

Prof: S. Rathod

//assign address of b to ptr,ptr pointing this location

*ptr=20;
printf(value of a=%d\n,a);
printf(value of b=%d\n,b);
getch();
return 0;
}
OUTPUT:
value of a=10
value of b=20

The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program
#include <stdio.h>

[255]

Structured Programming Approach

Prof: S. Rathod

#include<conio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
Output:
The value of ptr is 0
Value Assignment and address Assignment
Value assignment:
Assign value of variable using pointer and assigning its location pointed to by the
same or another pointer
*p+3;

*p=*q :

//value assignment

// value pointed by q assign to memory cell pointed by p

Address assignment:
p=q
The pointer p also pointed the same memory location pointed by q such kind of
assignment called address assignment
p=q

// content(address) of q assign to p

//WAP for value assignment and address assignment with pointer


#include <stdio.h>
[256]

Structured Programming Approach

Prof: S. Rathod

#include<conio.h>
int main()
{
int a=5,b=10;
int *p,*q; //pointer to integer
p=&a;
q=&b;
printf(a=%d,b=%d\n,a,b);

//5

10

printf(*p=%d,*q=%d\n,*p,*q);

//5

10

*p=*p+3; //value assignment


*p=*q;

//8

// value assignment

//10

printf(*p=%d,*q=%d\n,*p,*q);

//10

10

*q=*q+3; //13
p=q

//Address assignment here value of p=value of q due to address //13

printf(*p=%d,*q=%d\n,*p,*q); //13
printf(a=%d,b=%d\n,a,b); //10

13

13

getch();
return 0;
}

OUTPUT:
a=5 , b=10
*p=5 , *q=10
[257]

Structured Programming Approach

Prof: S. Rathod

*p=10 , *q=10
*p=13 , *q=13
a=10 , b=21

POINTER ARITHMETIC:
/* Program to accept 10 integers & print them using pointers. Find the average of
the integers.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int *p, a[10], i, sum=0;
float avg;
clrscr();
p=a;
printf("Enter 10 numbers : \n");
for(i=0; i<10; i++)
{
scanf("%d",(p+i));
}
for(i=0; i<10; i++)
{
sum = sum + *(p+i);
}
avg = sum/10.0;
printf("\nArray is : ");
for(i=0; i<10; i++)
{
printf(" %d ",*(p+i));
[258]

Structured Programming Approach

Prof: S. Rathod

}
printf("\nAverage = %f",avg);
getch();
}
/* OUTPUT :
Enter 10 numbers :
1
2
3
4
5
6
7
8
9
10
Array is : 1 2 3 4 5 6 7 8 9 10
Average = 5.500000
*/
POINTER and ARRAY()
Pointer and array are closely linked together
Name of array itself represent a pointer and hold address of first location
Array is a sequential data structure where element are stored in consecutive
memory location

[259]

Structured Programming Approach

Prof: S. Rathod

x=&x[0];
p=&x[0];
p = x instead of p=&x[0];
Array print data using x[i]
Using pointer it will print p[i]

X[i] can be written as *(x+i) is nothing but x+i with reference


X[i] = *(x+i)

for i=0,1,2,3,4

For i=0:x[0]=*(x+i)=*(100+0) 100 as value 10


For i=1:x[1]=*(x+i)=*(100+1) 102 (int req 2 byte)102 20
For i=1:x[2]=*(x+i)=*(100+2) 104 (int req 2 byte)104 30
For i=1:x[3]=*(x+i)=*(100+3) 106 (int req 2 byte)106 40
For i=1:x[4]=*(x+i)=*(100+4) 108 (int req 2 byte)108 50

WAP to find sum of the elements of array.Define function for summation.


#include<stdio.h>
[260]

Structured Programming Approach

Prof: S. Rathod

#include<conio.h>
int sum(int []);

//equivalent to int sum(int *);

int main()
{
int a[]={3,9,6,12,10};
int result;
clrscr();
result=sum(a);

//passing array as a parameter equivalent to result=sum(&a[0])

printf(Sum of elements is =%d,result);


getch();
return 0;
}
int sum(int x[5])

//equivalent to int sum(int *x)

{
int c=0,i;
for(i=0;i<5;i++)
{
c=c+x[i];
}
return c;
}

[261]

Structured Programming Approach

Prof: S. Rathod

OUTPUT:
Sum of element=40

//program to pass array to a function using pointers and calculate average.


#include<stdio.h>
#include<conio.h>
float func_avg(int *a,int n) //pointer as reference OR (int a[],int n)
{
int i;
float sum = 0.0, avg=0.0;
for(i=0; i<n; i++)
{
printf("Value of arr[%d] is: %d \n", i, *(a+i));
sum = sum + *(a+i);
}
avg = sum/n;
return avg;
}

[262]

Structured Programming Approach

Prof: S. Rathod

void main()
{

int arr[100], N, i;
float average;
clrscr();
printf("Enter no. of elements : ");
scanf("%d", &N);
printf("Enter array elements : \n");
for(i=0;i<N;i++)
scanf("%d", &arr[i]);
average = func_avg(arr, N);

//(&arr[0],N); passing array

printf("Average of array elements : %f\n", average);


getch();
}

/* OUTPUT :

Enter no. of elements : 6


Enter array elements :
[263]

Structured Programming Approach

Prof: S. Rathod

1
2
1
2
3
4
Value of arr[0] is: 1
Value of arr[1] is: 2
Value of arr[2] is: 1
Value of arr[3] is: 2
Value of arr[4] is: 3
Value of arr[5] is: 4
Average of array elements : 2.166667

[264]

Structured Programming Approach

Prof: S. Rathod

POINTER and FUNCTION (call by reference)

Call by reference
1) While passing parameter using call by address scheme , we are passing the
actual address of the variable to the called function.
2) Any updates made inside the called function will modify the original copy
since we are directly modifying the content of the exact memory location.

Example:
#include<stdio.h>
#include<conio.h>
void swap(int *,int *); //prototype
int main()
{
int a=5,b=7;
printf(value before call a=%d and b=%d\n,a,b);
swap(&a,&b);

//calling a and b with address passed

printf(value after call a=%d and b=%d\n,a,b);


getch()
return 0;
}
void swap(int *p,int *q)
{
[265]

Structured Programming Approach

Prof: S. Rathod

int temp;
temp=*p;
*p=*q;
*q=temp;
}

OUTPUT:
Value before call a=5 and b=7
Value after a call a=7 and b=5

POINTER TO POINTER
C allow us to use pointer that point another point. A pointer to a pointer is a form
of multiple indirection, or a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that
contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name.
Declaration:
int **dptr;

[266]

Structured Programming Approach

Prof: S. Rathod

Lets suppose we have a pointer dptr that points to yet another pointer ptr In
memory, the three variables can be visualized as :

So we can see that in memory, pointer dptr holds the address of pointer ptr. Pointer
ptr holds the address of a.
So ptr is pointer to int a, while dptr is pointer to ptr or we can also say that
ptr is a pointer to pointer to int a.

Now, in code ptr can be declared as :


char *ptr = &a;
But dptr is declared as :
char **dptr = &ptr;

//EXAMPLE
int a;
int *ptr;
int **dptr;
printf(value of a =%d\n,a);
printf(Address of a=%X\n\n,&a);
[267]

Structured Programming Approach

Prof: S. Rathod

printf(value of ptr=%x\n,ptr);
printf(value pointed to by ptr=%d\n,*ptr);
printf(Address of ptr =%x\n\n,&ptr);
printf(Value of dptr =%x\n\n,dptr);
printf(value pointed to by dptr=%x\n,*dptr);
printf(value at value pointed to by dptr=%d\n,**dptr);
printf(Address of dptr=%x\n,&dptr);

Output:
value of a 5
Address of a 100

value of ptr 100


value pointed to by ptr 5
Address of ptr 200

Value of dptr 200


value pointed to by dptr 100
value at value pointed to by dptr 5
Address of dptr 300

[268]

Structured Programming Approach

Prof: S. Rathod

FILE
file is a place on disk where a group of related data is stored.
Why files are needed?
When the program is terminated, the entire data is lost in C programming. If you
want to keep large volume of data, it is time consuming to enter the entire data.
But, if file is created, these information can be accessed using few
commands.There are large numbers of functions to handle file I/O in C language.
file I/O functions can be categorized as:
Text file
Binary file
File Operations

Creating a new file


Opening an existing file
Reading from and writing information to a file
Closing a file

File I/O operation

Operation

Read Operation

Function

purpose

getc()

To read a character from a file

fgetc()

To read a character from a file

fscanf()

To read primitive value from a file

fread()

To read a structure from from a file


[269]

Structured Programming Approach

Prof: S. Rathod

putc()

To write a character into a file

fputc()

To write a character into a file

fprintf()

To write primitive value into a file

fwrite()

To write a structure from into a file

Write Operation

Opening Modes in Standard I/O

File Mode Meaning of Mode

During Inexistence of file

Open for reading

If the file does not exist, fopen() returns


NULL.

Open for writing.

If the file exists, its contents are overwritten.


If the file does not exist, it will be created.

Open for append. If the file does not exists, it will be created.
i.e, Data is added to
end of file.

r+

Open for both If the file does not exist, fopen() returns
reading and writing. NULL.

w+

Open for both If the file exists, its contents are overwritten.
reading and writing. If the file does not exist, it will be created.

a+

Open for
reading
appending.

both If the file does not exists, it will be created.


and

[270]

Structured Programming Approach

Prof: S. Rathod

Working with file


While working with file, you need to declare a pointer of type file. This declaration
is needed for communication between file and program.

Declaration:

Syntax:

FILE filepointer;
Ex: FILE *ptr;
Opening a file:
Opening a file is performed using library function fopen().
Syntax:
file-pointer=fopen(filename,filemode);
Ex:
ptr=fopen("fileopen","mode")
ptr=fopen("E:\\cprogram\program.txt","w");
/* --------------------------------------------------------- */
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.
/* --------------------------------------------------------- */
[271]

Structured Programming Approach

Prof: S. Rathod

Closing a File:
The file should be closed after reading/writing of a file. Closing a file is performed
using library function fclose().
Syntax:
fclose(filepointer);

Ex: fclose(ptr);

//ptr is the file pointer associated with file to be closed.

Reading from file:

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("sample.txt","r");

//open existing file

ch=getc(fp);

//initialization by reading character of file

while(ch!=EOF)

//check condition

{
printf(%c,ch);

//display character on console or putchar() also use

ch=getc(fp);

//increment file pointer


[272]

Structured Programming Approach

Prof: S. Rathod

}
fclose(fp);
getch();
}

Writing to a file:
Copying the content from old to new text file and display new file
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("old.txt","r");
//open existing file
fp2=fopen("new.txt","w");
//create new file for copy
if(fp1==NULL)
//check file is exist or not
{
printf("\nUnable to open old file");
exit(1);
}
else
{
ch=getc(fp1);
while(ch!=EOF)
{
putc(ch,fp2);
ch=getc(fp1);
}
fclose(fp1);
fclose(fp2);
}
fp1=fopen("new.txt","r");

//initialization by reading character of file


//check condition
//write content to new file
//increment file pointer

//display content of copied file


[273]

Structured Programming Approach

Prof: S. Rathod

if(fp1==NULL)
{
printf("unable to open new file");
exit(1);
}
ch=getc(fp1);
//reading character of file by initialization
while(ch!=EOF)
//check condition
{
printf("%c",ch);
//display content on console
ch=getc(fp1);
//increment file pointer
}
fclose(fp1);
getch();
}
Write a program to accept a set of characters from user until the user presses
the full stop (.) and store it in a text file. Read from the file and display the
contents of the file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
//To write data into file
fp = fopen("test.txt", "w");
printf("Write data to be stored in the file and \n once completed press the full stop
(.):\n\n");
[274]

Structured Programming Approach

Prof: S. Rathod

while(c != '.')
{
scanf("%c", &c); //Input character from user or getchar() also use
}
fclose(fp);
//To read data from file
printf("\n \Contents of the file are \n \n");
fp = fopen("test.txt", "r");
while(c != EOF)

//check condition

{
c = getc(fp);

//Read character from file

printf("%c", c);

//display character on console for user or putchar()

}
fclose(fp);
getch();
}
OUTPUT :
Write data to be stored in the file and once completed press the full
stop (.): This is SPA practical
This is program for file handling.
Contents of the file are : This is SPA practical
This is program for file handling.
[275]

Structured Programming Approach

Prof: S. Rathod

enumeration data type:


An enumeration is a user-defined data type consists of integral constants and each
integral constant is give a name. Keyword enum is used to defined enumerated
data type.
enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag. And value1,
value2,....,valueN are values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the
programmer can change the default value.
Declaration of enumerated variable
// Changing the default value of enum elements
enum suit
{
club=0;
diamonds=10;
hearts=20;
spades=3;
};
Above code defines the type of the data but, no any variable is created.
Variable of type enum can be created as:
enum boolean
{
false;
true;
};
enum boolean check;
Here, a variable check is declared which is of type enum boolean.

[276]

Structured Programming Approach

Prof: S. Rathod

Example of enumerated type


#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output:
4 day

[277]

Você também pode gostar