Professional Documents
Culture Documents
SPAnotes 2015 16 PDF
SPAnotes 2015 16 PDF
Rathod
Structured
Programming
Approach
[0]
Structured Programming Approach Prof: S. Rathod
Software:
Types:
PROGRAMMING LANGUAGE:
A set of rules that provide a way of telling a computer what operation to perform is
called computer programming language.
Types:
Example: C
[1]
Structured Programming Approach Prof: S. Rathod
COMPILER:
INTERPRETER:
Computer language processor that translates a program line-by-line
(statement-by-statement) and carries out the specified actions in sequence.
[2]
Structured Programming Approach Prof: S. Rathod
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
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
ALGORITHM
Program=algorithm+data
[4]
Structured Programming Approach Prof: S. Rathod
PROPERTIES:
EFFICIENCY:
Time efficiency - a measure of amount of time for an algorithm to execute.
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:
FEATURES:
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
[7]
Structured Programming Approach Prof: S. Rathod
[8]
Structured Programming Approach Prof: S. Rathod
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
THEN
ELSE
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.
2) Flow Chart: (Calculate the gross salary that includes basic salary, 50%DA,
40%HRA)
[11]
Structured Programming Approach Prof: S. Rathod
[12]
Structured Programming Approach Prof: S. Rathod
[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.
[14]
Structured Programming Approach Prof: S. Rathod
A Simple Program
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
}
A NOTE ABOUT C PROGRAMS
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");
Programming in C is easy.
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:
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:
4. Valueless
[18]
Structured Programming Approach Prof: S. Rathod
1. Int
2. Char
3. Float
4. Double
5. void
Character Type:
char
char 'A';
[19]
Structured Programming Approach Prof: S. Rathod
Integer Type:
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.
int sum;
[20]
Structured Programming Approach Prof: S. Rathod
❖ 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.
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
[22]
Structured Programming Approach Prof: S. Rathod
Real Constants
1) Real constants are often called Floating Point constants.
Character Constants
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:
Assignment:
For example:
Initialization :
[24]
Structured Programming Approach Prof: S. Rathod
DECIMAL NUMBERS
[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.
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.
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 ….
❖ 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
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
[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.
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
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
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
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
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
a is an integer variable.
Ex.: int i, j;
i = 20;
j = i * 20 + 5;
j = 12.5;
int a, b, num ;
[33]
Structured Programming Approach Prof: S. Rathod
avg = ( a + b + i + num ) / 4 ;
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
types—Left to Right or 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 operation: /
i=2+8-2+0 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.
axb–cxd a*b–c*d
(x + y) (a - b) (m + n) * (a + b)
7y3+y2 + 2y + 9 7*y*y*y+y*y+2*y
+9
#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;
return 0;
Output:
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.
a) x=a++;
x=a ------> store value of a in memory for variable x
b) y=b--;
y=b ------> store value of b in memory for variable y
PREFIX:
a) x=++a;
a=a+1 ------> increment value by 1 and store in memory for variable a
b) y=--b;
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
10 = 2 + 2+ 2 + 4
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
1 < Less Ex: a<b Check whether the value a is less than
than stored in a is less than b. b
3 <= 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.
[39]
Structured Programming Approach Prof: S. Rathod
Logical Operators:
C allows usage of three logical operators, namely, ‘AND’ ‘OR’ and ‘NOT’.
Assignment Operators
S.N. Operator Meaning Explanation Example
operand
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:
& Binary AND Operator copies a bit to the (A & B) will give 12
result if it exists in both operands. which is 0000 1100
[41]
Structured Programming Approach Prof: S. Rathod
<< 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.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Conditional Operators:
Syntax:
[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”.
Special Operators
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 Prof: S. Rathod
sizeof(float) 4
sizeof(double) 8
Operator priority:
Operato
Order Category Operation Associativity
r
()
[]
Highest L→ R Left
1 → Function call
precedence to Right
::
Logical
!
negation (NOT)
R → L
2 Unary Bitwise 1’s
~
complement Right -> Left
+ Unary plus
[44]
Structured Programming Approach Prof: S. Rathod
- Unary minus
Pre or post
++
increment
Pre or post
--
decrement
& Address
* Indirection
Size of operant
Size of
in bytes
.* Dereference
Member
3 L→R
Access
→* Dereference
* Multiply
Multiplicati
4 / Divide L→R
on
% Modulus
+ Binary Plus
5 Additive L→R
- Binary Minus
[45]
Structured Programming Approach Prof: S. Rathod
Less than or
<=
equal to
7 Relational L→R
> Greater than
Greater than or
>=
equal to
== Equal to
8 Equality L→R
!= Not Equal to
Bitwise
9 & Bitwise AND L→R
AAND
Bitwise
10 ^ Bitwise XOR L→R
XOR
Logical
12 && Logical AND L→R
AND
Ternary
14 Conditional ?: R→L
Operator
[46]
Structured Programming Approach Prof: S. Rathod
= Assignment
*= Assign product
Assign
%=
reminder
/= Assign quotient
+= Assign sum
Assign
-=
difference
15 Assignment R→L
Assign bitwise
&=
AND
Assign bitwise
^=
XOR
Assign bitwise
|=
OR
Assign right
>>=
shift
[47]
Structured Programming Approach Prof: S. Rathod
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:
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 :
➢ Input Functions
getch(),
getche(),
getchar(),
gets().
[48]
Structured Programming Approach Prof: S. Rathod
➢ output Function
putch()
putchar()
puts()
➢ Input function
scanf()
Format Specifiers:
Following is the list of most commonly used format specifiers that can be used
with the printf( ) function.
[49]
Structured Programming Approach Prof: S. Rathod
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:
[50]
Structured Programming Approach Prof: S. Rathod
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.
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.
[52]
Structured Programming Approach Prof: S. Rathod
O/P: y = 1
O/P: y= 0.500008
BASIC PROGRAM:
int main()
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.
#include <stdio.h>
#include <conio.h>
void main()
int num;
getch();
Output:
#include<stdio.h>
#include<conio.h>
void main()
{
[54]
Structured Programming Approach Prof: S. Rathod
int num1;
float num2,result;
clrscr();
scanf("%d%f",&num1,&num2);
result=num1+num2;
getch();
OUTPUT :
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( )
scanf("%f %f",&num1,&num2);
[55]
Structured Programming Approach Prof: S. Rathod
printf("Product: %f",product);
getch();
Output:
Program:
#include<stdio.h>
#include<conio.h>
void main ()
clrscr();
int x, y;
printf("Enter a number:");
scanf("%d",&x);
y=x*x;
getch();
[56]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
void main ()
clrscr();
getch();
#include<stdio.h>
#include<conio.h>
void main ()
clrscr();
scanf("%f%f",&length,&breadth);
getch();
#include<stdio.h>
#include<conio.h>
void main ()
float r, area;
clrscr();
scanf("%f",&r);
area=3.14 *r*r;
getch();
[58]
Structured Programming Approach Prof: S. Rathod
#include <stdio.h>
#include <conio.h>
void main()
char ch;
getch();
#include <stdio.h>
#include <conio.h>
void main()
scanf("%d",÷nd);
scanf("%d",&divisor);
printf("Quotient = %d\n",quotient);
printf("Remainder = %d",remainder);
getch();
Output:
Quotient = 6 Remainder = 1
#include <stdio.h>
#include <conio.h>
void main()
int a;
float b;
double c;
char d;
getch();
Output:
#include<stdio.h>
#include<conio.h>
void main()
int a,b,c,maxT;
clrscr();
scanf("%d%d%d",&a,&b,&c);
maxT=a>b?(a>c?a:c):(b>c?b:c);
getch();
OUTPUT :
First No. is : 20
Second No. is : 40
Third No. is : 10
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();
[62]
Structured Programming Approach Prof: S. Rathod
temp = num1;
num1 = num2;
num2 = temp;
getch();
OUTPUT :
[63]
Structured Programming Approach Prof: S. Rathod
#include <stdio.h>
#include <conio.h>
void main()
int num;
scanf("%d",&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();
scanf("%f", &basic_salary);
[64]
Structured Programming Approach Prof: S. Rathod
DA = 0.5 * basic_salary;
Gross_Salary=basic_salary + DA + HRA;
getch();
OUTPUT :
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
int a,b,c;
float x1,x2;
clrscr();
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);
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
SELECTION
The statement in the program executed in order in which they appear is called
sequential execution.but sometime,
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
[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)
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;
scanf("%d",&num);
if(num<0)
printf("Number = %d\n",num);
getch();
Output1:
Number = -2
Output2:
[69]
Structured Programming Approach Prof: S. Rathod
#include <stdio.h>
void main()
while( valid == 0 )
valid = 1;
valid = 0;
valid = 0;
[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)
else
[71]
Structured Programming Approach Prof: S. Rathod
#include <stdio.h>
int main()
int num;
scanf("%d",&num);
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
Output1:
Output2:
#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);
printf("Leap Year");
else
getch();
#include <stdio.h>
#include <conio.h>
int main()
char c;
scanf("%c",&c);
printf("%c is an alphabet.",c);
else
return 0;
* is not an alphabet
K is an alphabet
#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
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:
}
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.
#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
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.
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
FLOWCHART:
PROGRAM
#include<stdio h>
#include<conio h>
[80]
Structured Programming Approach Prof: S. Rathod
void main()
float avg;
clrscr();
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)
else if(avg>40)
printf("\n\tjust pass");
else
printf("\nfail");
else
getch();
[81]
Structured Programming Approach Prof: S. Rathod
OUTPUT:
Enter percentage scored (0-100) : 65
First Class
#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
#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.
[83]
Structured Programming Approach Prof: S. Rathod
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;
}
[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
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
#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");
scanf("%d",&choice);
scanf("%d%f",&a,&b);
switch(choice)
case 1:c=a+b;
break;
case 2:c=a-b;
break;
case 3:c=a*b;
[90]
Structured Programming Approach Prof: S. Rathod
break;
case 4: if(b==0)
printf("Invalid operation");
else
d=a/b;
break;
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
20 10
: 30
Do you want to
continue???y
****MENU****
1.ADDITION
2.SUBTRACTION
3.MULTIPLICATION
4.DIVISION
22 0
Invalid operation
Do you want to
continue???y
[92]
Structured Programming Approach Prof: S. Rathod
ITERATION:
LOOPING:
Why looping:
It is require to execute one or more statement of program for more than once.
LOOP:
a) control statement
b) body of loop
Control statements:
Looping Mechanism:
[93]
Structured Programming Approach Prof: S. Rathod
TYPES:
1) while
2) do while
3) for
while:
Syntax:
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
#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:
sum of digit=6
#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:
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)
else
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();
while(x<=400)
i=2;
while(x%i!=0)
i++;
if(x==i)
printf(“%d\t”,x);
x++;
getch();
#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++;
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
else
getch();
OUTPUT:
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 :
Where:
For -----> keyword
initialization_statement -----> initialize the loop index
[102]
Structured Programming Approach Prof: S. Rathod
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.
[103]
Structured Programming Approach Prof: S. Rathod
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
#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
#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
#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
#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
#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
#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);
getch();
#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);
getch();
#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);
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;
getch();
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
[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
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
}
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
*
***
*****
***
*
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
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;
[136]
Structured Programming Approach Prof: S. Rathod
goto Statement
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.
{ { lbl:
{ { {
} } i++;
} } }
12345
[138]
Structured Programming Approach Prof: S. Rathod
ARRAY
Definition
Types of Arrays:
[139]
Structured Programming Approach Prof: S. Rathod
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 } ;
[141]
Structured Programming Approach Prof: S. Rathod
{
a[i] = 0;
}
This loop sets all ten elements of the array a to 0.
[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
[144]
Structured Programming Approach Prof: S. Rathod
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,(n-
even));
getch();
}
[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();
}
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();
}
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
50
32
25
14
{
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();
}
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
#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
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
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];
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
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();
}
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();
}
{
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
{
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
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
46 53 60
74 85 96
MATRIX FORM
Symmetric AT=A
Skew Symmetric AT=-A
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 2 3
2 4 5
[178]
Structured Programming Approach Prof: S. Rathod
3 5 8
Your Matrix is Symmetric Matrix
*/
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 2
3 0 -5
-2 5 0
Your Matrix is Symmetric skew Matrix
[181]
Structured Programming Approach Prof: S. Rathod
#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
T1 T2 T3 T4 T5 T6 avg
[183]
Structured Programming Approach Prof: S. Rathod
[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
char s[5];
Initialization of strings:
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";
char c[20];
scanf("%s",c);
void main( )
int i = 0 ;
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.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s",name);
return 0;
}
Output:
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();
}
[188]
Structured Programming Approach Prof: S. Rathod
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();
}
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
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
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
[194]
Structured Programming Approach Prof: S. Rathod
OR
#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--;
}
OUTPUT
nEnter the string :hello all
nReverse string is :lla olleh
#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
OUTPUT:
enter string:madam
USING STRING FUNCTION
string madam is in palindrome
WITHOUT STRING FUNCTION
string madam is in palindrome
[198]
Structured Programming Approach Prof: S. Rathod
Write a user defined function to copy one string into another. [ Hint: Don’t
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
#include<conio.h>
void main()
int n=0,i;
char a[10],m,rep='y';
clrscr();
gets(a);
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;
getch();
OUTPUT
[201]
Structured Programming Approach Prof: S. Rathod
C Programming Functions
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
• Library function
Library function
For example:
main() The execution of every C program starts from this main() function.
in that program: one for finding factorial and other for checking whether it is prime
or not.
1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and debug.
function_name(argument(1),....argument(n));
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 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.
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
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
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 main(){
int num1,num2,sum;
scanf("%d %d",&num1,&num2);
printf("sum=%d",sum);
return 0;
int add;
add=a+b;
#include<stdio.h>
#include<conio.h>
void add();
int main()
add();
getch();
return 0;
int a,b,sum;
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum=%d”,sum);
[208]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
int add();
int main()
int sum;
sum=add();
printf(“Sum is %d”,sum);
getch();
return 0;
int a,b,c;
scanf(“%d%d”,&a,&b);
c=a+b;
[209]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
int main()
int a,b;
scanf(“%d%d”,&a,&b);
getch();
return 0;
int sum;
sum=x+y;
printf(“sum is=%d”,sum);
[210]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
int main()
int a,b,sum;
scanf(“%d%d”,&a,&b);
sum=add(a,b);
printf(“Sum is %d”,sum);
getch();
return 0;
int z;
z=x+y;
[211]
Structured Programming Approach Prof: S. Rathod
#include<conio.h>
void main()
int n;
clrscr();
scanf("%d",&n);
display(n);
getch();
int i;
for(i=1;i<=n;i++)
printf("%d\n",i);
[212]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
void main()
int n1,n2,n3;
clrscr();
scanf("%d %d %d",&n1,&n2,&n3);
avg(n1,n2,n3);
getch();
float average;
average=(a+b+c)/3.0;
printf("Average=%f",average);
[213]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
void main()
int no,factorial;
clrscr();
printf("Enter a number:");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial=%d",factorial);
getch();
int i,ans;
for(i=1,ans=1;i<=no;i++)
ans=ans*i;
return ans;
[214]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
void main()
int i,n;
clrscr();
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
#include<stdio.h>
#include<conio.h>
void main()
int n;
clrscr();
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;
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
gcd = GCD(no1,no2);
if(gcd==1)
[218]
Structured Programming Approach Prof: S. Rathod
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
*/
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
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
[221]
Structured Programming Approach Prof: S. Rathod
int a=5,b=7;
getch()
return 0;
int temp;
temp=p;
p=q;
q=temp;
OUTPUT:
[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>
int main()
int a=5,b=7;
getch()
return 0;
int temp;
temp=*p;
*p=*q;
[223]
Structured Programming Approach Prof: S. Rathod
*q=temp;
OUTPUT:
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];
#include<stdio.h>
#include<conio.h>
int main()
{
[224]
Structured Programming Approach Prof: S. Rathod
int a[]={3,9,6,12,10};
int result;
clrscr();
getch();
return 0;
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
#include<stdio.h>
#include<conio.h>
int max(int,int);
int main()
int a,b,c,d,g;
clrscr();
scanf(“%d%d%d%d”,&a,&b,&c,&d);
g=max(max(a,b),max(c,d));
getch();
return 0;
return (m>n)?m:n;
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.
Note: Positive integers are known as natural number i.e. 1,2, 3....n
#include <stdio.h>
int main()
int num,add;
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
int sum(int n)
if(n==0)
return n
else
[227]
Structured Programming Approach Prof: S. Rathod
Output
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
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.
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.
#include<stdio.h>
#include<conio.h>
int main()
int n;
[229]
Structured Programming Approach Prof: S. Rathod
scanf("%d",&n);
return 0;
int factorial(int n)
if(n!=1)
return n*factorial(n-1);
Output:
Factorial of 6 = 72
Algorithm:
main()
Step 1: START
Step 3: INPUT n
Step 5: INITIALIZE i = 1
[230]
Structured Programming Approach Prof: S. Rathod
fibo(int f)
Step 1: START
Step 3: RETURN 0.
Step 5: RETURN 1.
main()
[231]
Structured Programming Approach Prof: S. Rathod
fibo (int f)
[232]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
void main()
{ int n, i, term;
clrscr();
scanf("%d",&n);
printf("\nFibonacci Series");
{ term = fibo(i);
getch();
int next = 0 ;
if(f == 1)
return 0;
else if(f == 2)
return 1;
else
return next;
OUTPUT:
Fibonacci Series:
011235
[234]
Structured Programming Approach Prof: S. Rathod
#include<stdio.h>
#include<conio.h>
void main()
int p,x,y;
clrscr();
scanf(“%d%d”,&x,&y);
p=power(x,y);
getch();
if(y==0)
return 1;
else if(y==1)
return x;
else
OUTPUT:
enter x and y 3 4
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:
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 Prof: S. Rathod
int 0
char '\0'
float 0
pointer NULL
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:
[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
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
1 2 3
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
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
EX:
struct book
char name ;
float price ;
int pages ;
};
[241]
Structured Programming Approach Prof: S. Rathod
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.
· 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
Syntax:
Note that before the dot there must always be a structure variable and after the dot
there must always be a structure element.
b1.price
Structure elements can be accessed through a pointer to a structure using the arrow
(->) operator.
b1->price
main( )
struct book
char name ;
float price ;
[243]
Structured Programming Approach Prof: S. Rathod
int pages ;
};
output...
A 100.00 354
C 256.50 682
F 233.70 512
Array of Structures
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.
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();
[246]
Structured Programming Approach Prof: S. Rathod
/* OUTPUT :
Enter the number of students : 3
[247]
Structured Programming Approach Prof: S. Rathod
*/
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.
#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
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.
● Arrays,
● Structures,
● Functions.
What is a Pointer?
pointer declaration :
<variable_type> *<name>;
[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;
}
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
#include <stdio.h>
int main()
{
int a,*ptr;
a=10;
printf(“a=%d”,a);
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
#include <stdio.h>
#include<conio.h>
int main()
{
int a,b;
int *ptr;
*ptr=10;
[254]
Structured Programming Approach Prof: S. Rathod
*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()
{
Assign value of variable using pointer and assigning its location pointed to by the
same or another pointer
Address assignment:
p=q
The pointer p also pointed the same memory location pointed by q such kind of
assignment called address assignment
#include<conio.h>
int main()
{
int a=5,b=10;
p=&a;
q=&b;
printf(“a=%d,b=%d\n”,a,b); //5 10
printf(“*p=%d,*q=%d\n”,*p,*q); //5 10
printf(“*p=%d,*q=%d\n”,*p,*q); //10 10
*q=*q+3; //13
printf(“*p=%d,*q=%d\n”,*p,*q); //13 13
printf(“a=%d,b=%d\n”,a,b); //10 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
*/
[259]
Structured Programming Approach Prof: S. Rathod
x=&x[0];
p=&x[0];
p = x instead of p=&x[0];
#include<stdio.h>
[260]
Structured Programming Approach Prof: S. Rathod
#include<conio.h>
int main()
int a[]={3,9,6,12,10};
int result;
clrscr();
getch();
return 0;
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
#include<stdio.h>
#include<conio.h>
int i;
avg = sum/n;
return avg;
[262]
Structured Programming Approach Prof: S. Rathod
void main()
{ int arr[100], N, i;
float average;
clrscr();
scanf("%d", &N);
for(i=0;i<N;i++)
scanf("%d", &arr[i]);
getch();
/* OUTPUT :
[263]
Structured Programming Approach Prof: S. Rathod
[264]
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>
int main()
int a=5,b=7;
getch()
return 0;
{
[265]
Structured Programming Approach Prof: S. Rathod
int temp;
temp=*p;
*p=*q;
*q=temp;
OUTPUT:
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.
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
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.
//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
[268]
Structured Programming Approach Prof: S. Rathod
FILE
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.
● Text file
● Binary file
File Operations
[269]
Structured Programming Approach Prof: S. Rathod
[270]
Structured Programming Approach Prof: S. Rathod
Declaration:
Syntax:
FILE filepointer;
Opening a file:
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.
#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
{
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();
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 != '.')
fclose(fp);
fp = fopen("test.txt", "r");
fclose(fp);
getch();
OUTPUT :
Write data to be stored in the file and once completed press the full
Here, type_name is the name of enumerated data type or tag. And value1,
value2,....,valueN are values of type type_name.
[276]
Structured Programming Approach Prof: S. Rathod
Output:
4 day
[277]