Structured Programming Lecture Note
Structured Programming Lecture Note
Basics of C
1. Basic of C
CONTENTS
1.1 History of C
1.2 C character set, tokens, constants, variables, keywords , identifiers
1.3 C operators- arithmetic, Logical, assignment, relational, increment and
decrement, conditional, bit wise, special, operator precedence, C
expressions data types
1.4 Problem solving techniques : flowchart and algorithm
1.5 Formatted input, formatted output instructions.
Anuradha Bhatia
Structured Programming Approach 1. Basics of C
1.1 History of C
1. C is a general purpose structured programming language that is powerful, efficient
and compact.
2. C is an offspring of the basic combined programming language called B.
3. This was modified by Dennis Ritchie and was implemented in the Bell laboratories
in 1972.
4. C is a structured programming language. C combines the features of a high level
language with the elements of the assembler.
5. This flexibility allows C to be used for system programming.
6. A number of implementation of C, are available like Microsoft C, Quick C, Turbo C,
Lattice C, Aztec C.
7. C has large number of operators and relatively small instruction set.
8. It allows user to write library functions of its own.
C Language
Modularity
Anuradha Bhatia 2
Structured Programming Approach 1. Basics of C
Anuradha Bhatia 3
Structured Programming Approach 1. Basics of C
Anuradha Bhatia 4
Structured Programming Approach 1. Basics of C
int i;
do {
print("%d ",i);
i++;
}
while (i<10)
double and float: double and float are used for indicating floating type
variables. Keywords float and double represents single precision and
double precision floating point data respectively. For examp le:
float ans1;
double ans2;
Here, ans1 is single precision floating type variable whereas, ans2 is a
double precision floating type variable.
if and else: if and else are used in decision making in C.
if (i==1)
printf("i is 1.")
else
prinf("i is not 1.")
If value of i is other than 1, output will be: i is not 1
enum: enum is used to define enumerated type data type. Enumerated
data type creates a set of constant of type int. For example:
enum enum_var{
var1;
var2;
var3;
};
Here, a enumerated variable enum_var is created having tags: var1,
var2 and var3.
Anuradha Bhatia 5
Structured Programming Approach 1. Basics of C
extern
Keyword extern is used for indicating the variable is external and is
declared outside every function and can be accessed by any function.
For example:
#include <stdio.h>
extern i=5;
void print1(){
printf ("%d ",i);
}
int main() {
printf("%d ",i);
}
return 0;
}
Output of the given code is: 5 5
for: Keyword for is used for looping in C. For example:
for (i=0;i<9;++i){
printf("%d ",i);
}
Output of the code given: 0 1 2 3 4 5 6 7 8
goto : Keyword goto is used for unconditional jump to a labeled
statement inside that function. For example:
for(i=1;i<5;++i){
if (i==10)
goto error;
}
printf("i is not 10");
error:
printf("Error, count can't be 10");
Anuradha Bhatia 6
Structured Programming Approach 1. Basics of C
Anuradha Bhatia 7
Structured Programming Approach 1. Basics of C
}
Output of the given code:1 bytes.
Here, sizeof(...) is used to find the number of bytes of type char.
Register: Variable of storage class register are much faster than normal
variables.
register int var1;
Here, var1 is the variable of storage class register.
Static: static is used for indicating the variable is of storage class static.
The value of the static variables persists until the end of the program.
For example:
static int var;
Here, var is a variable of storage class static.
struct
struct is used in creating a structure which provide means to group
different types of variable under one name for easier handling.
struct student{
char name[80];
float marks;
int age;
}s1,s2;
Here, struct keyword is used in creating a structure of tag name student
and variables of type "struct student".
Typedef: Keyword typedef is used to explicitly associate a type with an
identifier.
typedef float kg;
kg bear,tiger;
Here, the use of typedef is to create a type kg and this kg type is used
in declaring variables bear and tiger.
Anuradha Bhatia 8
Structured Programming Approach 1. Basics of C
Anuradha Bhatia 9
Structured Programming Approach 1. Basics of C
1. Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20 then
2. Relational Operators
The following table shows all the relational operators supported by C. Assume variable
A holds 10 and variable B holds 20 then
Anuradha Bhatia 10
Structured Programming Approach 1. Basics of C
3. Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then
4. Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ is as follows
Anuradha Bhatia 11
Structured Programming Approach 1. Basics of C
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A'
holds 60 and variable 'B' holds 13, then
5. Assignment Operators
The following table lists the assignment operators supported by the C language
Anuradha Bhatia 12
Structured Programming Approach 1. Basics of C
6. Miscellaneous Operators
Besides the operators discussed above, there are a few other important operators
including sizeof and? : supported by the C Language.
Anuradha Bhatia 13
Structured Programming Approach 1. Basics of C
iii. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
iv. Operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
Anuradha Bhatia 14
Structured Programming Approach 1. Basics of C
Symbol Description
START /STOP of the program.
INPUT /OUTPUT BOX
ASSIGNMENT BOX
FUNCTION CALL
CONNECTOR
FLOW ARROW
Anuradha Bhatia 15
Structured Programming Approach 1. Basics of C
Explanation
i. # is a preprocessor directive which follows simple syntax rules.
ii. Preprocessor as the name implies is a program that processes the source code
before it passes through the compiler.
iii. It operates under the preprocessor command lines or directives.
iv. They all begin with the symbol # in the first column and does not end with a
semicolon.
v. The commonly used directives are # include and # define.
Directive Function
#include Specifies the file to be included.
#define Defines a macro substitution.
#undef Undefines a macro.
#ifdef Tests for a macro definition.
#endif Specifies the end of #if
Anuradha Bhatia 16
Structured Programming Approach 1. Basics of C
3. printf scanf in C
The printf() and scanf() functions are used for input and output in C language. Both
functions are inbuilt library functions, defined in stdio.h (header file).
i. printf() function
The printf() function is used for output. It prints the given statement to the
console.
The syntax of printf() function is given below:
printf("format string",argument_list);
Anuradha Bhatia 17
Structured Programming Approach 1. Basics of C
In this section, variables are defined and values are set to these
3 Definition Section
variables.
Global declaration Global variables are defined in this section. When a variable is to
4
section be used throughout the program, can be defined in this section.
Function prototype Function prototype gives many information about a function like
5
declaration section return type, parameter names used inside the function.
User defined User can define their own functions in this section which perform
7
function section particular task as per the user requirement.
Anuradha Bhatia 18
Structured Programming Approach 1. Basics of C
PROGRAM 1
#include<stdio.h>
#include<conio.h>
main( )
{
clrscr( );
printf(Welcome to C programming);
}
Explanation
i. Above written is a simple C program to print Welcome to C programming.
ii. Stdio.h is necessary as it has the functions printf in it.
iii. All the statements of C should end with a semicolon except #, main( ), { }, and
all the loops.
iv. The clrscr( ) is used to clear the screen before printing anything on it.
v. Whatever is written inside the printf statement is printed as it is on to the
output screen.
Welcome to C programming
Anuradha Bhatia 19
Structured Programming Approach 1. Basics of C
Start
Print Welcome to C
programming
Stop
PROGRAM 2
(Question: WAP to find the sum of two numbers with flowchart. 4 Marks)
Write a C program to find the sum of two numbers.
#include<stdio.h>
#include<conio.h>
main( )
{
int a = 10 , b = 20 , sum ; //assignment statement
sum = a + b ;
printf( the sum of two numbers is %d , sum);
getch( );
}
Explanation
i. In the above program a is assigned the value 10 and b is assigned the value 20.
ii. The sum is declared as an integer variable to hold integer value.
iii. Then we calculate sum by adding the two values.
iv. To print the value of sum we introduce a new term called format specifiers or
data qualifiers as %d for integer, %f for float, %c for character, %s for string,
%ld for long integer.
v. In this where %d is written the value of sum will be printed.
vi. getch( ) is used to accept a single character from the keyboard i.e. after
printing the output on the screen it will wait for the user to enter the value.
Anuradha Bhatia 20
Structured Programming Approach 1. Basics of C
The output is
Start
a= 10
b = 20
Sum = a + b
Stop
Note: In the above program we have introduced assignment statement, getch( ) and
comment statements i.e. anything which is written between the // or /*..*/ is an
comment.
The above program can be modified from the assignment statement to the users
choice program, i.e. the two numbers can be entered from the keyboard.
Anuradha Bhatia 21
Structured Programming Approach 1. Basics of C
PROGRAM 3
WAP to find the sum of two numbers.
#include<stdio.h>
#include<conio.h>
main( )
{
int a ,b, sum;
printf(Enter the first number);
scanf(%d,&a);
printf(\n Enter the second number );
scanf(%d,&b);
sum = a + b;
printf(\n The sum of two numbers %d and %d is %d ,a ,b, sum);
getch( );
}
Explanation
i. The general syntax of the scanf statement whish is known as an input
statement is
ii. scanf(control string , &variable 1, variable2);
iii. The control string contains the format of data being received.
iv. The symbol &known as an ampersand before each variable specifies the
variable names address.
v. We must used this before an input variable otherwise unexpected result
occur.
vi. The other new symbol introduced is \n which is a new line character. It
allows what ever written after it to move to the next new line.
vii. In the third printf statement the %d signs are replaced by their respective
values.
viii. Imp: Integer value has a limitation that is 32768 to +32767.
Anuradha Bhatia 22
Structured Programming Approach 1. Basics of C
PROGRAM 4
Write a program (WAP) to print cube of given number
#include<stdio.h>
#include<conio.h>
void main()
{
int number;
clrscr();
printf("Enter a number:");
scanf("%d",&number);
printf("Cube of number is:%d ",number*number*number);
getch();
}
The Output is
Enter a number: 5
Cube of number is: 125
Explanation
i. The scanf("%d",&number) statement reads integer number from the console
and stores the given value in number variable.
ii. The printf("cube of number is:%d ",number*number*number) statement
prints the cube of number on the console.
Practical problems
Anuradha Bhatia 23
Structured Programming Approach 1. Basics of C
Anuradha Bhatia 24
Structured Programming Approach
2. Decision Making
2.1 Decision making and branching if-statement if, if-else, else-if
ladder, nested if else, switch case statement, break statement
2.2 Decision making and looping - while, do, do- while statement, for
loop, continue statement
Anuradha Bhatia
Structured Programming Approach 2. Decision Making
Anuradha Bhatia 26
Structured Programming Approach 2. Decision Making
Anuradha Bhatia 27
Structured Programming Approach 2. Decision Making
PROGRAM 5
Write a program to add 10 to a number if its value is more than 0 and print it.
#include <stdio.h>
#include<conio.h>
main( )
{
int a ;
clrscr( );
printf(Enter a number ) ;
scanf (%d,&a);
if (a > 0 )
{ a = a + 10 ;
printf ( the value of a is %d , a);
}
getch( );
}
The output is :
Enter a number 45
the value of a is 55
Anuradha Bhatia 28
Structured Programming Approach 2. Decision Making
Start
Enter a
If
a >0
a=a+10
Stop
Explanation
i. In the above program we enter a number and store in the variable a, then
check whether a is greater than 0 , if the answer is yes than we add 10 to it
and print the result .
ii. But if it doesnt satisfy the condition than it terminates the program and come
out.
Anuradha Bhatia 29
Structured Programming Approach 2. Decision Making
if .else statement
if (condition)
{
true block statement;
}
else
{
false block statement ;
}
Anuradha Bhatia 30
Structured Programming Approach 2. Decision Making
PROGRAM 6
Explanation
i. In the above program we want to find the largest of two numbers.
ii. We input two numbers and store it in the variables a and b.
iii. Then with the, if loop we check that whether a > b if the answer is yes or true
than we print that a is large and if this statement is false than we print that the
other number in this case b is large.
The output is:
Enter the two numbers 34 56
b is large 56
Anuradha Bhatia 31
Structured Programming Approach 2. Decision Making
Start
Input a, b
If
Print b is large
a
Print a is large
Stop
Anuradha Bhatia 32
Structured Programming Approach 2. Decision Making
Anuradha Bhatia 33
Structured Programming Approach 2. Decision Making
PROGRAM 7
Write a program to find the largest of three numbers using if else.
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,c;
clrscr( );
printf( \
scanf(%d %d %d ,&a,&b,&c);
if ( a < b)
{
if( a > c)
{
printf(\na is largest of three numbers %d %d %d d,a,b,c,a);
}
else
{
printf(\nc is largest of three numbers %d %d %d %d,a,b,c,c);
}
else
{
if (b > c)
{
printf(\nb is largest of three numbers %d %d %d d,a,b,c,b);
}
else
printf(\nc is largest of three numbers %d %d %d %d,a,b,c,c);
}
Anuradha Bhatia 34
Structured Programming Approach 2. Decision Making
getch( )
}The flowchart is:
Start
Enter three
numbers a,b,c
No Yes
If If
a>b b>c
Yes No
No
If Print c is largest
a>c
Yes
Stop
Anuradha Bhatia 35
Structured Programming Approach 2. Decision Making
Explanation:
i. The above program finds the largest of three numbers. as we input three
numbers a , b, c and check whether a is larger than b
ii. if the answer is yes or true than if check whether a is larger than c than we
print that a is largest of three numbers
iii. otherwise the number which is stored in the variable c is largest of three
numbers
iv. But if the first condition fails than we check that if b is larger than c if yes than
we print that b is largest of the three numbers else c is the largest.
Anuradha Bhatia 36
Structured Programming Approach 2. Decision Making
PROGRAM 8
Write a program to print that if a student scores above 90 than he gets A++ grade
and if he gets between 80 to 89 than he gets A+ grade and if he gets between 70
to 79 than he gets A grade and if he gets between 60 to 69 than he gets B+ grade
and if he gets between 50 to 59 than he gets B grade else print C grade. (Program
uses logical &&) Also draw the flow chart for the same.
PROGRAM 9
Anuradha Bhatia 37
Structured Programming Approach 2. Decision Making
i. The use of if else becomes tedious if there are lot many comparisons, hence a new
statement called switch case came into picture.
ii. The syntax is
switch (expression)
{
case option 1 :
statements;
break;
case option 2 :
statements;
break;
default :
statements;
break;
}
Anuradha Bhatia 38
Structured Programming Approach 2. Decision Making
Program 10
Write a program to add, multiply, subtract and divides a number using a switch
case statement.
#include<stdio.h>
#include<conio.h>
main( )
{
int num1,num2,n=0;
float ans;
int choice ;
Anuradha Bhatia 39
Structured Programming Approach 2. Decision Making
scanf(%d %d,&num1,&num2);
printf(1:Add);
printf(2:Sub);
printf(3:Mul);
printf(4:Div);
scanf(%d,&choice);
switch (choice)
{
case 1: ans = num1+num2;
n=1;
break;
case 2: ans = num1-num2;
n=1;
break;
case 3: ans = num1*num2;
n=1;
break;
case 4: ans = num1/num2;
n=1;
break;
default: printf(u have entered wrong choice)
break;
}
if ( n==1)
getch( );
}
Anuradha Bhatia 40
Structured Programming Approach 2. Decision Making
Explanation:
i. In the above program instead of using if.else for the choices we use switch
case statement which reduces the ambiguity of looping continuously.
The output is:
Enter two numbers 45 67
1: Add
2: Sub
3: Mul
4: Div
Enter your choice 1
The result is 112
Anuradha Bhatia 41
Structured Programming Approach 2. Decision Making
start
Input two
numbers
Enter ur choice
ans= num1-num2
ans= num1*num2
ans= num1/num2
Entered wrong
choice
If n=1
n==
111
Stop
Anuradha Bhatia 42
Structured Programming Approach 2. Decision Making
PROGRAM 11
Write a program using switch case to print whether the given number is even or
odd, to print the factorial of a number and prime number.
#include<stdio.h>
main()
{
int choice, factorial, temp, number, i;
while (1)
{
printf("\n1. Factorial");
printf("\n2. Prime");
printf("\n3. Odd/ Even");
printf("\n4. Exit");
printf("\n\nYour Choice? : ");
scanf ("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter the Number:");
scanf ("%d", &number);
for (temp=1,factorial=1; temp<=number;temp++)
{
factorial=factorial*temp;
continue;
}
printf("Factorial=%d\n\n",factorial);
break;
case 2:
Anuradha Bhatia 43
Structured Programming Approach 2. Decision Making
Anuradha Bhatia 44
Structured Programming Approach 2. Decision Making
3. BREAK statement
i. The break statement is used anywhere in the program to break the flow of the
program and to come out of the particular loop.
ii. The break statement in C programming has the following two usages
iii. When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
iv. It can be used to terminate a case in the switch statement (covered in the next
chapter).
Anuradha Bhatia 45
Structured Programming Approach 2. Decision Making
Example
include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 ) {
printf("Value of a: %d\n", a);
a++;
if( a > 15) {
break;
}
}
return 0;
}
The output is
Value of a: 10
Value of a: 11
Value of a: 12
Anuradha Bhatia 46
Structured Programming Approach 2. Decision Making
Value of a: 13
Value of a: 14
Value of a: 15
ii. The? : operator
(Question: Explain conditional operator, with example. 4 Marks)
Anuradha Bhatia 47
Structured Programming Approach 2. Decision Making
6. goto Statement:
(Question: Explain goto statement, with example. 4 Marks)
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
Anuradha Bhatia 48
Structured Programming Approach 2. Decision Making
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Output
The goto statement can be replaced in most of C program with the use of break and
continue statements. In fact, any program in C programming can be perfectly written
without the use of goto statement. All programmer should try to avoid goto statement as
possible as they can.
Anuradha Bhatia 49
Structured Programming Approach 2. Decision Making
This is the simplest of all the loops in C language. The general format for the
while loop is .
while ( test condition )
{
body of the loop ;
}
The while loop is an entry controlled loop , which means that if the while loop
condition is true than only the control be transferred to the loop inside ,
otherwise it will terminate the loop or come out of the loop.
Anuradha Bhatia 50
Structured Programming Approach 2. Decision Making
If the condition is true than the control is transferred inside the body of the
loop, and after it is executed it once again check for the condition, this process
continues till the condition is not satisfied.
PROGRAM 12
#include<stdio.h>
#include<conio.h>
main( )
{ int num = 1, sum = 0;
clrscr( );
while ( num < = 10)
{
sum = sum + num ;
num = num + 1;
}
printf ( the sum of 10 numbers is %d , sum );
getch( );
}
Explanation:
i. The above program is used to find the sum of first 10 numbers.
ii. We first assign a variable called num the initial value of 1, we have to find the sum
from numbers 1 to 10.
iii. Another variable sum is initialized to 0 to store the sum of all the numbers.
iv. We than check the while loop that the statements inside the loop should be
executed till the value of num is more than 10.
v. As initially the value of num is 1 it enters the loop and adds up the num to the
variable sum and the value of num is incremented by one.
Anuradha Bhatia 51
Structured Programming Approach 2. Decision Making
vi. Once again the value of num is checked in the while loop and as num is less than
10 it again enters the loop , and this procedure continued till the value of num is
more than 10 .
vii. When the value of num is 11, it terminates the loop and print value of sum.
The output is
Start
num = 1
sum = 0
If num
<=10
num = num + 1
Stop
Anuradha Bhatia 52
Structured Programming Approach 2. Decision Making
Algorithm
1. Initialize the value of num to 1 and sum = 0.
2. Check while ( num <= 10 ) do the following
sum = sum + num
num = num + 1
3. Print the sum
Anuradha Bhatia 53
Structured Programming Approach 2. Decision Making
PROGRAM 13
Write a program to check whether the number is even or odd, the program should
continue till user choses to quit.
#include<stdio.h>
#include<conio.h>
main( )
{ int num ;
char ans;
do
{ printf(Enter the number to be checked );
scanf(%d,&num);
if (num % 2 == 0)
printf ( \nthe number %d is even,num);
else
printf( \nThe number %d is odd ,num);
printf( \nDo u want to continue );
scanf (%c , &ans);
}while (ans ==y);
getch( );
}
The output is
Enter the number to be checked 56
The number 56 is even
Do u want to continuey
Enter the number to be checked 73
The number 73 is odd
Do u want to continue n
Anuradha Bhatia 54
Structured Programming Approach 2. Decision Making
Explanation:
i. In the above program we want to find whether the number is even or odd , and
we want to check for the numbers till the user wants to quit the program for this
we use a do while loop .
ii. We enter the number to be checked and in the if loop we check if the number
divided by two the remainder is zero than the number is an even number else it is
an odd number .
iii. Then the user is asked whether the user wants to check for more numbers if the
answer is y, then the program continues, otherwise it comes out of the loop and
program ends.
IMP NOTE: The difference between the while loop and do..while loop is that in the while
loop it checks for the condition initially and if it is true than only the body of the loop is
executed whereas in the do.. while loop the body of the loop i.e the statements are
executed at least once and then the condition is checked and if the condition is true than
it re-enters the loop else comes out of it.
This is also an entry controlled loop. The general syntax for the for loop is
for(initial cond ; final condition ; increment operator)
{
body of loop;
}
Anuradha Bhatia 55
Structured Programming Approach 2. Decision Making
PROGRAM 14
(Question: WAP to find sum of first 10 numbers. 4 Marks)
#include<st dio.h>
#include<conio.h>
main( )
{
int i , sum = 0 ;
clrscr( );
for( i = 1 ; i < = 10 ; i++)
{
sum = sum + i ;
}
printf(\nthe sum of first 10 numbers is %d ,sum);
getch( );
}
The output is
The sum of first 10 numbers is 55
Explanation
i. As we want to find the sum of first 10 numbers, so we know that our starting
number is one and the last number is 10, and the number increase gradually with
one.
ii. Sum is initialized to zero as it may take the garbage value. So the initial condition
of for loop is 1 and the termination condition or the final condition of the for loop
will be 10 and the loop variable is incremented by 1.
Anuradha Bhatia 56
Structured Programming Approach 2. Decision Making
iii. The value of sum is added to the loop variable and saved back to sum.
Start
sum = 0
For i = 1 ; i < = 10
sum = sum + i
Next i
Stop
Anuradha Bhatia 57
Structured Programming Approach 2. Decision Making
PROGRAM 15
Write a program to input the10 numbers from the user and find its sum and
average.
PROGRAM 16
(Question: WAP to find largest of number from 10 numbers. 4 Marks)
WAP to enter 10 numbers and find the largest of the number.
PROGRAM 17
(Question: WAP to print the given pattern. 4 Marks)
Write a program to print the following pattern
1
22
333
4444
55555
Anuradha Bhatia 58
Structured Programming Approach 2. Decision Making
#include<stdio.h>
#include<conio.h>
main( )
{
int i , j ;
for( i = 1 ; i < = 5 ; i++)
{
for ( j = 1 ; j <= i ; j ++)
{ printf(%d\t ,j); }
printf(\n);
}
getch( );
}
Draw the flowchart for the above program.
Anuradha Bhatia 59
Structured Programming Approach 2. Decision Making
sum = sum + a ;
3. It is also permissible to use expressions in the initialization and increment part of
the loop
for ( a = (c+d) /2 ; a> 30 ; a = a/2)
4. A unique part of for loop is one or more sections can be omitted if needed
a= 5;
for( ; a != 100 ; )
{
printf(%d,a) ;
a = a+ 2 ;
}
The initial and the increment conditions are omitted, but the conditions
are given separately.
If the conditions are not given then it becomes an infinite loop and can be
terminated using a break or a goto statement.
5. A for loop can also be written to give a time delay and such kind of loops are
called as null loop.
for( a = 1000 ; a > 0 ; a --);
As this loop ends with a semicolon and does not have any statements in
it, it will be executed for 1000 times.
1. What is the purpose of the while statement? When is the logical expression
evaluated? What is the minimum number of times the while loop is evaluated.
2. What is the difference between the while loop and the do..while loop . Explain with
the syntax.
3. Explain for loop and how does it differ from a while loop.
4. Write a program to print the multiplication table for ten numbers.
5. Write a program to find the sum of marks of three subjects for five students.
6. Write a program to print the Fibonacci series.
Anuradha Bhatia 60
Structured Programming Approach 2. Decision Making
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Output
Enter a character: *
* is not an alphabet
Output
Enter a character: K
K is an alphabet
PROGRAM 19
WAP to Check Whether a Character is Vowel or consonant
#include <stdio.h>
int main(){
char c;
Anuradha Bhatia 61
Structured Programming Approach 2. Decision Making
if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U')
printf("%c is a vowel.",c);
else
printf("%c is a consonant.",c);
return 0;
}
Output
Enter an alphabet: i
i is a vowel.
Output
Enter an alphabet: G
G is a consonant.
PROGRAM 20
WAP to Reverse an Integer
#include <stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
Anuradha Bhatia 62
Structured Programming Approach 2. Decision Making
}
printf("Reversed Number = %d",reverse);
return 0;
}
Output
Enter an integer: 2345
Reversed Number = 5432
PROGRAM 21
WAP to Check Palindrome Number
#include <stdio.h>
int main()
{
int n, reverse=0, rem,temp;
printf("Enter an integer: ");
scanf("%d", &n);
temp=n;
while(temp!=0)
{
rem=temp%10;
reverse=reverse*10+rem;
temp/=10;
}
if(reverse==n)
printf("%d is a palindrome.",n);
else
printf("%d is not a palindrome.",n);
return 0;
}
Anuradha Bhatia 63
Structured Programming Approach 2. Decision Making
Output
Enter an integer: 12321
12321 is a palindrome.
PROGRAM 22
WAP to Check Prime Number
#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Output
Enter a positive integer: 29
29 is a prime number.
Anuradha Bhatia 64
Structured Programming Approach 2. Decision Making
PROGRAM 22
WAP to Check Armstrong Number
#include <stdio.h>
int main()
{
int n, n1, rem, num=0;
printf("Enter a positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{
rem=n1%10;
num+=rem*rem*rem;
n1/=10;
}
if(num==n)
printf("%d is an Armstrong number.",n);
else
printf("%d is not an Armstrong number.",n);
}
Output
Enter a positive integer: 371
371 is an Armstrong number.
PROGRAM 23
WAP to Make Simple Calculator in C programming
# include <stdio.h>
int main()
{
Anuradha Bhatia 65
Structured Programming Approach 2. Decision Making
char o;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}
Output
Enter operator either + or - or * or divide : -
Enter two operands: 3.4
Anuradha Bhatia 66
Structured Programming Approach 2. Decision Making
8.4
3.4 - 8.4 = -5.0
Anuradha Bhatia 67
Structured Programming Approach
Anuradha Bhatia
Structured Programming Approach 3. Arrays and String
1. An array is a group of data items belong to same type and same storage class that
share a common name.
2. An individual value in a group is called an element. The number of
subscripts/index determines the dimensionality i.e. the number of elements in an
array.
3. An array with one subscript is called as single dimension array.
4. Each subscript must be a non-negative integer.
5. If a programmer wants to find the sum of 10 numbers then it is very tedious to
declare 10 variables and then add them.
6. For this we declare an array which can store 10 numbers. The general syntax is :
datatype variable-name [size];
And for the above example it can be written as
int a[10];
For the above declaration the computer reserves 10 storage locations as shown
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Anuradha Bhatia 69
Structured Programming Approach 3. Arrays and String
PROGRAM 18
(Question: WAP to find the sum of 10 numbers using arrays. 4 Marks)
Write a program to find the sum of 10 numbers.
#include<stdio.h>
#include<conio.h>
main( )
{
int i ,a[10] , sum = 0;
clrscr( );
printf(Enter 10 numbers );
for( i = 0 ; i < 10 ; i++)
scanf (%d,&a[i]);
for( i = 0 ; i < 10 ; i++)
sum = sum + a[i] ;
for( i = 0 ; i < 10 ; i++)
printf (\nThe 10 numbers are %d , a[i]);
printf(\n the sum of 10 numbers is %d ,sum);
getch( );
}
Explanation
i. We use the first for loop to enter 10 numbers and store in an array.
ii. The second for loop is used to find the sum of 10 numbers which was entered and
stored in the array a[ ]. And the third for loop is used to printf the numbers.
Anuradha Bhatia 70
Structured Programming Approach 3. Arrays and String
Anuradha Bhatia 71
Structured Programming Approach 3. Arrays and String
Output
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
Sum=45
PROGRAM 19
(Question: WAP to sort the numbers in ascending order. 4 Marks)
Write a program to sort the numbers in ascending order.
#include<stdio.h>
#include<conio.h>
main( )
{
int i ,j ,num[5] ;
for( i = 0 ; i <5 ; i ++)
a[i] = 0;
printf(Enter the elements of the list );
for( i = 0 ; i <5 ; i ++)
scanf(%d,&a[i]);
for( i = 0 ; i <4 ; i ++)
{
for(j =i ; j <5 ; j ++)
{
if(a[i] > a[j])
{
temp = a[i] ;
a[i] = a[j];
a[j] = temp;
Anuradha Bhatia 72
Structured Programming Approach 3. Arrays and String
}
}
}
printf(\nThe sorted list is );
for( i = 0 ; i <5 ; i ++)
printf(%d ,a[i])
getch( );
}
NOTE: in the above program as we know the maximum size of the array, so rather than
writing it again and again in the loop we can put it in a single statement using #define as
#define max 5
int a[max];
So in the loop wherever we used five we can replace it with max.
The major advantage of it is that if we want to change the size of my array
than we have to just change it in the #define.
Anuradha Bhatia 73
Structured Programming Approach 3. Arrays and String
or
int a[2][2] = {{1,2},{3,4}};
or
int a[2][2] = {
{1,2},
{3,4}
};
If the values are missing they will be set to zero.
The number of elements it can take is 2*2 i.e 4
ii. The array with more than two dimensions is known as multi-dimension array.
Type array_name[ ][ ][ ].[ ];
int a[2][3][4];
iii. This is an array which can store 2*3*4 = 24 integer type element.
PROGRAM 20
(Question: WAP to print the reverse of an array. 4 Marks)
#include<stdio.h>
#include<conio.h>
main( )
{
int i , a[20],num;
printf(Total numbers in an array are );
scanf(%d, &num);
printf(\nEnter the numbers in an array );
Anuradha Bhatia 74
Structured Programming Approach 3. Arrays and String
for(i = 0 ;i <num;i++)
scanf(%d,&a[i]);
printf(\nThe reverse of an array is );
for(i = num-1 ; i > 0 ; i--)
printf(%d ,a[i]);
getch( );
}
Anuradha Bhatia 75
Structured Programming Approach 3. Arrays and String
PROGRAM 21
(Question: WAP to enter elements in a two dimension array and print. 4 Marks)
Anuradha Bhatia 76
Structured Programming Approach 3. Arrays and String
PROGRAM 22
WAP to Add Two Matrix in C programming
#include <stdio.h>
int main(){
int r,c,a[100][100],b[100][100],sum[100][100],i,j;
printf("Enter number of rows (between 1 and 100): ");
scanf("%d",&r);
printf("Enter number of columns (between 1 and 100): ");
scanf("%d",&c);
printf("\nEnter elements of 1st matrix:\n");
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&b[i][j]);
}
for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
printf("\nSum of two matrix is: \n\n");
for(i=0;i<r;++i)
Anuradha Bhatia 77
Structured Programming Approach 3. Arrays and String
for(j=0;j<c;++j)
{
printf("%d ",sum[i][j]);
if(j==c-1)
printf("\n\n");
}
return 0;
}
Output
Enter element a12: -4
Enter element a21: 8
Enter element a22: 5
Enter element a31: 1
Enter element a32: 0
Enter elements of 2nd matrix:
Enter element a11: 4
Enter element a12: -7
Enter element a21: 9
Enter element a22: 1
Enter element a31: 4
Enter element a32: 5
Anuradha Bhatia 78
Structured Programming Approach 3. Arrays and String
PROGRAM 23
WAP to find multiplication of two matrices.
#include <stdio.h>
int main()
{
int a[10][10], b[10][10], mult[10][10], row1, col1, row2, col2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &row1, &col1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d",&row2, &col2);
while (col1!=row2)
{
printf("Error! Column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &row1, &col1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d",&row2, &col2);
}
printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
/* Storing elements of second matrix. */
printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
Anuradha Bhatia 79
Structured Programming Approach 3. Arrays and String
{
printf("Enter elements b%d%d: ",i+1,j+1);
scanf("%d",&b[i][j]);
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
mult[i][j]=0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
mult[i][j]+=a[i][k]*b[k][j];
}
printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ",mult[i][j]);
if(j==c2-1)
printf("\n\n");
}
return 0;
}
Output
Anuradha Bhatia 80
Structured Programming Approach 3. Arrays and String
Output Matrix:
24 29
6 25
Anuradha Bhatia 81
Structured Programming Approach 3. Arrays and String
PROGRAM 23
WAP to Find Transpose of a Matrix
#include <stdio.h>
int main()
{
int a[10][10], trans[10][10], r, c, i, j;
printf("Enter rows and column of matrix: ");
scanf("%d %d", &r, &c);
Anuradha Bhatia 82
Structured Programming Approach 3. Arrays and String
}
printf("\nTranspose of Matrix:\n");
for(i=0; i<c; ++i)
for(j=0; j<r; ++j)
{
printf("%d ",trans[i][j]);
if(j==r-1)
printf("\n\n");
}
return 0;
}
Output
Enter rows and column of matrix: 2
3
Entered Matrix:
1 2 9
0 4 7
Transpose of Matrix:
1 0
Anuradha Bhatia 83
Structured Programming Approach 3. Arrays and String
2 4
9 7
PROGRAM 23
WAP to print the lower triangle of a matrix.
PROGRAM 24
WAP to print the diagonal of a matrix.
Anuradha Bhatia 84
Structured Programming Approach 3. Arrays and String
char string[size];
#include<stdio.h>
main( )
{
char name[12];
printf(Enter your name );
scanf(%s,name);
printf(\nThe name is , name);
getch( );
}
NOTE: Whatever is the size of the string available it takes one character less as the last
character is the null character i.e \0.
char jest[5] = { G,O,O,D,\0}
Reading a line of text from the keyboard we use getchar( ).
Anuradha Bhatia 85
Structured Programming Approach 3. Arrays and String
1. We can use this function to read successive single characters from the input and
place them into a character array.
2. So an entire line of text can be read and stored in an array.
3. The reading is terminated when the new line character \n is entered and the null
character is inserted at the end of the string.
PROGRAM 25
(Question: WAP to input a line of text from the keyboard. 4 Marks)
WAP to input a line of text from the keyboard.
#include<stdio.h>
#include<conio.h>
main( )
{
char text[81] , ch;
int num = 0;
printf(Enter ur text );
do
{
text[num] = getchar( );
num++;
}while(ch !=\n);
num = num-1;
text[num] = \0;
printf(\nThe output string is %s\n,text);
}
The output is:
Enter your text string handling in C
The output string is string handling in C
Anuradha Bhatia 86
Structured Programming Approach 3. Arrays and String
Explanation
i. In the above program a character array text with size 81 is declared which means
that it can take maximum up to 80 characters and 81 is the null character.
ii. ch is the variable which accepts and stores the single character from the getchar(
) function.
iii. This is than stored in the array text and each time the index gets incremented, till
a return is pressed.
iv. Here num 1 is given so the last character should be null.
Writing a line of text: Printf is used to print the line of text with an %s format, it uses an
array to print the line which is ended with a null character.
We can also specify the precision for the %s.
char state[15] = Andaman Nicobar
1. printf(%15s,state);
Andaman Nicobar
2. printf(%8s,state);
Andaman Nicobar
3. printf(%15.5s,state);
Andam
PROGRAM 26
WAP to print the following pattern
P
PR
PRO
PROG
PROGR
PROGRA
Anuradha Bhatia 87
Structured Programming Approach 3. Arrays and String
PROGRAM
#include<stdio.h>
#include<conio.h>
main( )
{
int loop1,loop2;
char str[] = PROGRAM;
for(loop1 = 0 ; loop1<=6;loop1++)
{
loop2 = loop1 + 1;
printf(%-7.*s\n , loop2 , str);
}
getch( );
}
Important
1. To print the ASCII value of a character we write it as
a =b;
printf(%d,a);
The above statement will print the number 98 on to the screen.
2. It also performs arithematic operations on the character constants and variables
like
a = z 1;
In ASCII the value of z is 122 and therefore the statement will assign the value
121 to a
3. We may also use character constants in relational expressions like
if ( ch >=A && ch <=H)
4. C library also supports a function which converts string constant to its integer
value.
Anuradha Bhatia 88
Structured Programming Approach 3. Arrays and String
x = atoi(string);
e.g x= atoi(1988);
COMPARISON OF TWO STRINGS
1. To compare two strings we have to use a while loop till we encounter a null
character in both the strings.
2. Each string has to be compared character by character to to equal to each other
the simple part of the code explains the same.
i = 0;
while(str1[i] == str2[i] && str1[i] != \0 && str2[1] != \0)
i = i + 1;
if (str1[i] == \0 && str2[i] == \0)
printf(strings are equal);
else
printf(strings are not equal );
STRING HANDLING FUNCTIONS OF C
(Question: Explain the string handling functions in C. 4 Marks)
1. C library supports large number of string functions and some of the commonly
used functions are:
i. strcat( ) concatenates two strings.
ii. strcmp( ) compares two strings.
iii. strcpy( ) copies one string over another .
iv. strlen( ) finds the length of the string .
i. strcat( ) Function
This function is used to join two strings together.
strcat (string1 , string 2);
It copies the content of string2 to string1 by removing the null character from
the end of string1 but the contents of string2 remains unchanged.
string1:
Anuradha Bhatia 89
Structured Programming Approach 3. Arrays and String
P R O G R A M \0
string2:
W R I T I N G \O
Anuradha Bhatia 90
Structured Programming Approach 3. Arrays and String
PROGRAM 27
WAP to find the length of a string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main( )
{
int len ;
char a[10];
printf(Enter the string );
scanf(%s , a);
len = strlen(a);
printf(\n The length of the string is %d ,len);
getch( );
}
Anuradha Bhatia 91
Structured Programming Approach 3. Arrays and String
#include <stdio.h>
#include <string.h>
int main () {
Anuradha Bhatia 92
Structured Programming Approach 3. Arrays and String
return 0;
}
Output
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
PROGRAM 28
PROGRAM 29
WAP to check whether the given string is a palindrome or not (madam is a
palindrome)
1. Enter the string.
2. Find the length of the string.
3. Copy the string in the reverse order to another string array.
4. Check whether both are same.
5. If yes print it as palindrome else print not a palindrome.
Anuradha Bhatia 93
Structured Programming Approach
4 Functions &
Structures
4.1 Functions: - Need of functions, scope and lifetime of variables,
defining functions, function call, call by value, call by reference,
return values, storage classes.
4.2 Category of function - No argument No return value, No argument
with return value, argument with return value, recursion,
command line arguments
4.3 Structures: - Defining structure, declaring and accessing structure
members, initialization of structure, arrays of structure.
Anuradha Bhatia
Structured Programming Approach 4. Functions & Structures
Anuradha Bhatia 95
Structured Programming Approach 4. Functions & Structures
MAIN PROGRAM
function-name(argument list)
argument declaration ;
{
local variable declaration ;
body of the function ;
________________;
________________;
return(expression);
}
Anuradha Bhatia 96
Structured Programming Approach 4. Functions & Structures
Anuradha Bhatia 97
Structured Programming Approach 4. Functions & Structures
Anuradha Bhatia 98
Structured Programming Approach 4. Functions & Structures
int main() {
recursion();
}
iv. Recursion is more elegant and requires few variables which make program
clean.
v. Recursion can be used to replace complex nesting code by dividing the
problem into same problem of its sub-type.
vi. It is hard to think the logic of a recursive function. It is also difficult to debug
the code containing recursion
Anuradha Bhatia 99
Structured Programming Approach 4. Functions & Structures
1. To access any member of a structure, we use the member access operator (.).
2. The member access operator is coded as a period between the structure variable
name and the structure member that we wish to access.
3. The keyword struct to define variables of structure type.
4. The following example shows how to use a structure in a program
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1;
The Output is
Book title : SPA
Book author : Anuradha Bhatia
Book subject : C programming
Book book_id : #120100
Book title : Object Oriented Programming
Book author : Yaswant Kanitkar
1. Structure as a function argument in the same way as you pass any other variable
or pointer.
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "SPA");
strcpy( Book1.author, "Anuradha Bhatia");
strcpy( Book1.subject, "C Programming ");
Book1.book_id = #120100;
strcpy( Book2.title, " Object Oriented Programming ");
strcpy( Book2.author, "Yaswant Kanitkar");
Anuradha Bhatia
Structured Programming Approach 5. Pointers and Files
3. A pointer is a group of cells (often two or four) that can hold an address.
4. So if c is a char and p is a pointer that points to it, we could represent the
situation this way:
5. The unary operator & gives the address of an object, so the statement p = &c;
assigns the address of c to the variable p, and p is said to ``point to'' c.
6. The & operator only applies to objects in memory: variables and array
elements.
7. It cannot be applied to expressions, constants, or register variables.
8. The unary operator * is the indirection or dereferencing operator; when
applied to a pointer, it accesses the object the pointer points to. Suppose that
x and y are integers and ip is a pointer to int.
9. This artificial sequence shows how to declare a pointer and how to use & and
*:
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to int */
ip = &x; /* ip now points to x */
y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
ip = &z[0]; /* ip now points to z[0] */
10 The declaration of x, y, and z are what we've seen all along. The declaration
of the pointer ip, int *ip; is intended as a mnemonic; it says that the
expression *ip is an int.
11 The syntax of the declaration for a variable the syntax of expressions in which
the variable might appear.
12. This reasoning applies to function declarations as well.
13. For example,
double *dp, atof(char *);
14. In an expression *dp and atof(s) have values of double, and that the argument
of atof is a pointer to char.
15. If ip points to the integer x, then *ip can occur in any context where x could,
so
*ip = *ip + 10;
increments *ip by 10.
16. The unary operators * and & bind more tightly than arithmetic operators, so
the assignment
y = *ip + 1
takes whatever ip points at, adds 1, and assigns the result to y, while
*ip += 1
increments what ip points to, as do
++*ip
And (*ip) ++
17. The parentheses are necessary in this last example; without them, the
expression would increment ip instead of what it points to, because unary
operators like * and ++ associate right to left.
18. Finally, since pointers are variables, they can be used without dereferencing.
For example, if iq is another pointer to int, iq = ip copies the contents of ip
into iq, thus making iq point to whatever ip pointed to.
x = y;
y = temp;
}
3. Because of call by value, swap can't affect the arguments a and b in the
routine that called it. The function above swaps copies of a and b.
4. The way to obtain the desired effect is for the calling program to pass pointers
to the values to be changed: swap(&a, &b);
5. Since the operator & produces the address of a variable, &a is a pointer to a.
In swap itself, the parameters are declared as pointers, and the operands are
accessed indirectly through them.
void swap(int *px, int *py) /* interchange *px and *py */
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
pointer argument to store the converted integer back in the calling function.
5. Sets pa to point to element zero of a; that is, pa contains the address of a[0].
Now the assignment x = *pa; will copy the contents of a[0] into x.
6. If pa points to a particular element of an array, then by definition pa+1 points
to the next element, pa+i points i elements after pa, and pa-i points i elements
before.
7. Thus, if pa points to a[0], *(pa+1) refers to the contents of a[1], pa+i is the
address of a[i], and *(pa+i) is the contents of a[i].
8. These remarks are true regardless of the type or size of the variables in the
array a.
9. The meaning of ``adding 1 to a pointer,'' and by extension, all pointer
arithmetic, is that pa+1 points to the next object, and pa+i points to the i-th
object beyond pa.
10. The correspondence between indexing and pointer arithmetic is very close.
By definition, the value of a variable or expression of type array is the address
of element zero of the array.
11. Thus after the assignment pa = &a[0]; pa and a have identical values. Since
the name of an array is a synonym for the location of the initial element, the
assignment pa=&a[0] can also be written as pa = a;
V. Pointers to Structures
1. Pointers to structures is declared in the same way as you define pointer to
any other variable
struct Books *struct_pointer;
2. The address of a structure variable is now stored in the above defined
pointer variable.
3. To find the address of a structure variable, place the '&'; operator before the
structure's name as follows
struct_pointer = &Book1;
4. To access the members of a structure using a pointer to that structure, you
must use the operator as follows
struct_pointer->title;
Example:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* book 2 specification */
strcpy( Book2.title, " Object Oriented Programming ");
strcpy( Book2.author, "Yaswant Kanetkar");
strcpy( Book2.subject, "C++");
Book2.book_id = #121100;
printBook( &Book1 );
printBook( &Book2 );
return 0;
}
The Output is
Book title : SPA
Book author : Anuradha Bhatia
Book subject : C programming
Book book_id : #120100
Book title : Object Oriented Programming
Book author : Yashwant kanetkar
Book subject : C++
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[10],str2[10],*ptr1,*ptr2;
clrscr();
printf(enter a string ");
scanf(%s,str1);
ptr1=str1;
ptr2=str2;
while(*ptr1!='\0')
{
*ptr2=*ptr1;
ptr2++;
ptr1++;
}
*ptr2='\0';
cout<<"string copied:"<<str2;
getch();
}
Program 31
WAP to find the number of vowels in a string
#include<iostream.h>
#include<conio.h>
void main()
{
char str[10],*ptr;
int count=0,i;
printf(enter a string ");
scanf(%s,str);
for(ptr=str;*ptr!='\0';ptr++)
{
if(*ptr=='a'||*ptr=='e'||*ptr=='i'||*ptr=='o'||*ptr=='u')
count++;
}
cout<<"mumber of vowels are:"<<count;
getch();
}
Program 32
WAP to find the length of the string
#include<iostream.h>
#include<conio.h>
void main()
{
char str[10],*ptr;
int i,count=0;
printf(enter a string ";
scanf(%s ,str) ;
for(ptr=str;*ptr!='\0';ptr++)
{
count++;
}
while(count>=0)
{
cout<<*ptr;
ptr--;
count--;
}
getch();
}
Program 33
WAP to find a character in a string
#include<iostream.h>
#include<conio.h>
void main()
{
char str1[10],ch,*p;
clrscr();
cout<<"enter a string: ";
cin>>str1;
p=str1;
cout<<"enter character to be searched: ";
cin>>ch;
while(*p!='\0')
{
if(*p==ch)
{
cout<<"character found";
break;
}
p++;
}
if(*p=='\0')
cout<<"not found";
getch();
}
For Example:
fopen("E:\\cprogram\program.txt","w");
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.
Here, the program.txt file is opened for writing mode.
Open for both reading If the file does not exist, fopen()
r+
and writing. returns NULL.
Open for both reading If the file does not exists, it will be
a+
and appending. created.
PROGRAM 34
WAP to print the content in to a file.
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
This program takes the number from user and stores in file. After you compile
and run this program, you can see a text file program.txt created in C drive of
your computer. When you open that file, you can see the integer you entered.
Similarly, fscanf() can be used to read data from file.
PROGRAM 35
WAP to Read from file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
2. Binary Files
i. Depending upon the way file is opened for processing, a file is classified into
text file and binary file.
ii. If a large amount of numerical data it to be stored, text mode will be
insufficient. In such case binary file is used.
iii. Working of binary files is similar to text files with few differences in opening
modes, reading from file and writing to file.
PROGRAM 36
WAP to open a file and to print it contents on screen.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fclose(fp);
return 0;
}
PROGRAM 37
WAP to read name and marks of n number of students from user and store
them in a file
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
PROGRAM 38
WAP to read name and marks of n number of students from user and store them
in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
PROGRAM 39
WAP to write all the members of an array of structures to a file using fwrite().
Read the array from the file and display on the screen.
#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}
Anuradha Bhatia
Programming in C 6.Programs
PROGRAM 40
WAP to reverse a number.
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
printf("Reverse of entered number is = %d\n", reverse);
return 0;
}
PROGRAM 41
WAP to check whether a given is a palindrome or not.
#include <stdio.h>
int main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or not\n");
scanf("%d",&n);
temp = n;
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}
PROGRAM 42
WAP to print the diamond pattern in c
*
***
*****
***
*
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
printf("Enter number of rows\n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space++;
PROGRAM 43
WAP to check whether a number is prime or not.
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}
PROGRAM 44
WAP to check whether a number is an armstrong number.
Examples:
7 = 7^1
371 = 3^3 + 7^3 + 1^3 (27 + 343 +1)
8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096).
#include <stdio.h>
int power(int, int);
int main()
{
int n, sum = 0, temp, remainder, digits = 0;
printf("Input an integer\n");
scanf("%d", &n);
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
printf("%d is an Armstrong number.\n", n);
else
printf("%d is not an Armstrong number.\n", n);
return 0;
}
int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
PROGRAM 45
WAP to print Fibonacci Series.
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
PROGRAM 46
WAP to print floyds triangle.
1
23
456
7 8 9 10
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
printf("Enter the number of rows of Floyd's triangle to print\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
return 0;
}
PROGRAM 47
WAP to print pascal triangle.
1
11
121
1331
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in pascal triangle\n");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");
for (c = 0 ; c <= i; c++)
printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));
printf("\n");
}
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
PROGRAM 48
WAP to add two numbers using pointers.
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
return 0;
}
PROGRAM 49
WAP to add two numbers using call by reference.
#include <stdio.h>
long add(long *, long *);
int main()
{
long first, second, *p, *q, sum;
printf("Input two integers to add\n");
scanf("%ld%ld", &first, &second);
sum = add(&first, &second);
printf("(%ld) + (%ld) = (%ld)\n", first, second, sum);
return 0;
}
long add(long *x, long *y) {
long sum;
sum = *x + *y;
return sum;
}
PROGRAM 50
WAP to print maximum number of element in the array.
#include <stdio.h>
int main()
{
int array[100], maximum, size, c, location = 1;
printf("Enter the number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
printf("Maximum element is present at location %d and it's value is %d.\n",
location, maximum);
return 0;
}
PROGRAM 51
WAP to print minimum number of element in the array.
#include <stdio.h>
int main()
{
int array[100], minimum, size, c, location = 1;
printf("Enter the number of elements in array\n");
scanf("%d",&size);
printf("Enter %d integers\n", size);
for ( c = 0 ; c < size ; c++ )
scanf("%d", &array[c]);
minimum = array[0];
for ( c = 1 ; c < size ; c++ )
{
if ( array[c] < minimum )
{
minimum = array[c];
location = c+1;
}
}
printf("Minimum element is present at location %d and it's value is %d.\n",
location, minimum);
return 0;
}
PROGRAM 52
WAP to add two matrices.
First Matrix:-
12
34
Second matrix:-
45
-1 5
Sum of First and Second matrix
57
29
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
PROGRAM 53
WAP to subtract two matrices.
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);
printf("Difference of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0; d < n; d++) {
difference[c][d] = first[c][d] - second[c][d];
printf("%d\t",difference[c][d]);
}
printf("\n");
}
return 0;
}
PROGRAM 54
WAP to find transpose of a matix.
12
34
56
then transpose of above matrix will be
135
246
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
}
PROGRAM 55
WAP to multiply two matrix
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
multiply[c][d] = sum;
sum = 0;
}
}
printf("\n");
}
}
return 0;
}
PROGRAM 56
WAP to swap two values using Call by Value
#include <stdio.h>
/* function declaration goes here.*/
void swap( int p1, int p2 );
int main()
{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( a, b );
printf("After: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int p1, int p2 )
{
int t;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
PROGRAM 57
WAP to swap two values using Call by Reference
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
PROGRAM 58
WAP to print the series of prime numbers
#include<stdio.h>
int check_prime(int num);
int main(){
int n1,n2,i,flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d",&n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);
for(i=n1+1;i<n2;++i)
{
flag=check_prime(i);
if(flag==0)
printf("%d ",i);
}
return 0;
}
int check_prime(int num) /* User-defined function to check prime number*/
{
int j,flag=0;
for(j=2;j<=num/2;++j){
if(num%j==0){
flag=1;
break;
}
}
return flag;
}
PROGRAM 59
WAP to find sum of natural numbers using recursion.
#include<stdio.h>
int add(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Sum = %d",add(n));
return 0;
}
int add(int n)
{
if(n!=0)
return n+add(n-1); /* recursive call */
}
PROGRAM 60
WAP to find factorial of a number using recursion
#include<stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}
PROGRAM 61
WAP to find HCF using recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d%d", &n1, &n2);
printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2));
return 0;
}
int hcf(int n1, int n2)
{
if (n2!=0)
return hcf(n2, n1%n2);
else
return n1;
}
PROGRAM 62
WAP to reverse a sentence using recursion
#include <stdio.h>
void Reverse();
int main()
{
printf("Enter a sentence: ");
Reverse();
return 0;
}
void Reverse()
{
char c;
scanf("%c",&c);
if( c != '\n')
{
Reverse();
printf("%c",c);
}
}
PROGRAM 63
WAP to convert binary to decimal or decimal to binary
#include <stdio.h>
#include <math.h>
int binary_decimal(int n);
int decimal_binary(int n);
int main()
{
int n;
char c;
printf("Instructions:\n");
printf("1. Enter alphabet 'd' to convert binary to decimal.\n");
printf("2. Enter alphabet 'b' to convert decimal to binary.\n");
scanf("%c",&c);
if (c =='d' || c == 'D')
{
printf("Enter a binary number: ");
scanf("%d", &n);
printf("%d in binary = %d in decimal", n, binary_decimal(n));
}
if (c =='b' || c == 'B')
{
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("%d in decimal = %d in binary", n, decimal_binary(n));
}
return 0;
}
{
int decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(2,i);
++i;
}
return decimal;
}
PROGRAM 64
WAP to rpint Fibonacci series using recursion
#include <stdio.h>
int fibonaci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main() {
int i;