0% found this document useful (0 votes)
7 views62 pages

CP Experiments

The document outlines experiments related to C programming, focusing on operators, conditional statements, and quadratic equations. It includes problem statements, definitions, theoretical explanations, algorithms, and source code for each experiment. The first experiment converts Celsius to Fahrenheit, the second finds the largest of three numbers using nested if-else, and the third determines the nature of roots of a quadratic equation using an if-else ladder.

Uploaded by

prakalp.17375
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views62 pages

CP Experiments

The document outlines experiments related to C programming, focusing on operators, conditional statements, and quadratic equations. It includes problem statements, definitions, theoretical explanations, algorithms, and source code for each experiment. The first experiment converts Celsius to Fahrenheit, the second finds the largest of three numbers using nested if-else, and the third determines the nature of roots of a quadratic equation using an if-else ladder.

Uploaded by

prakalp.17375
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Experiment No: 01

Aim: Study of Operators in C.


Problem Statement: Write a program to accept the temperature in Celsius and to
convert and display it in Fahrenheit.

Problem Definition:
Input: Value of temperature in Celsius
Processing: Convert temperature in Celsius to Fahrenheit.
F=1.8*C+32
Output: Value of temperature in Fahrenheit.

Theory:

An operator is a symbol that specifies the mathematical, logical or relational operator


to be performed C language supports following type of operators.

• Arithmetic Operators
• Logical (or Relational) Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Arithmetic Operators:

There are following arithmetic operators supported by C language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the A - B will give -10
first
* Multiply both operands A * B will give 200
/ Divide numerator by denominator B / A will give 2
% Modulus Operator and remainder of B % A will give 0
after an integer division
++ Increment operator, increases A++ will give 11
integer value by one
-- Decrement operator, decreases A-- will give 9
integer value by one

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 1


Logical (or Relational) Operators:

There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


== Checks if the value of two operands (A == B) is not true.
is equal or not, if yes then condition
becomes true.
!= Checks if the value of two operands (A != B) is true.
is equal or not, if values are not
equal then condition becomes true.
> Checks if the value of left operand (A > B) is not true.
is greater than the value of right
operand, if yes then condition
becomes true.
< Checks if the value of left operand (A < B) is true.
is less than the value of right
operand, if yes then condition
becomes true.
>= Checks if the value of left operand (A >= B) is not true.
is greater than or equal to the value
of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand (A <= B) is true.
is less than or equal to the value of
right operand, if yes then condition
becomes true.
&& Called Logical AND operator. If (A && B) is true.
both the operands are non zero then
condition becomes true.
|| Called Logical OR Operator. If any (A || B) is true.
of the two operands is non zero then
condition becomes true.
! Called Logical NOT Operator. Use !(A && B) is false.
to reverses the logical state of its
operand. If a condition is true then
Logical NOT operator will make
false.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 2


Bitwise Operators:

Bitwise operator works on bits and performs bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

There are following Bitwise operators supported by C language

Operator Description Example


& Binary AND Operator copies a bit (A & B) will give 12 which is 0000
to the result if it exists in both 1100
operands.
| Binary OR Operator copies a bit if (A | B) will give 61 which is 0011
it exists in eather operand. 1101
^ Binary XOR Operator copies the bit (A ^ B) will give 49 which is 0011
if it is set in one operand but not 0001
both.
~ Binary Ones Complement Operator (~A ) will give -60 which is 1100
is unary and has the efect of 0011
'flipping' bits.
<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111
operands value is moved left by the 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The A >> 2 will give 15 which is 0000
left operands value is moved right 1111
by the number of bits specified by
the right operand.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 3


Assignment Operators:

There are following assignment operators supported by C language:

Operator Description Example


= Simple assignment operator, C = A + B will assigned value of A + B
Assigns values from right side into C
operands to left side operand
+= Add AND assignment operator, C += A is equivalent to C = C + A
It adds right operand to the left
operand and assign the result to
left operand
-= Subtract AND assignment C -= A is equivalent to C = C - A
operator, It subtracts right
operand from the left operand
and assign the result to left
operand
*= Multiply AND assignment C *= A is equivalent to C = C * A
operator, It multiplies right
operand with the left operand
and assign the result to left
operand
/= Divide AND assignment C /= A is equivalent to C = C / A
operator, It divides left operand
with the right operand and
assign the result to left operand
%= Modulus AND assignment C %= A is equivalent to C = C % A
operator, It takes modulus
using two operands and assign
the result to left operand
<<= Left shift AND assignment C <<= 2 is same as C = C << 2
operator
>>= Right shift AND assignment C >>= 2 is same as C = C >> 2
operator
&= Bitwise AND assignment C &= 2 is same as C = C & 2
operator
^= bitwise exclusive OR and C ^= 2 is same as C = C ^ 2
assignment operator
|= bitwise inclusive OR and C |= 2 is same as C = C | 2
assignment operator

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 4


Misc Operators

There are few other operators supported by C Language.

Operator Description Example


sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return
4.
& Returns the address of an &a; will give actaul address of the
variable. variable.
* Pointer to a variable. *a; will pointer to a variable.
?: Conditional Expression If Condition is true ? Then value X :
Otherwise value Y

Operators Categories:

All the operators we have discussed above can be categorised into following
categories:

• Postfix operators, which follow a single operand.


• Unary prefix operators, which precede a single operand.
• Binary operators, which take two operands and perform a variety of arithmetic
and logical operations.
• The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression.
• Assignment operators, which assign a value to a variable.
• The comma operator, which guarantees left-to-right evaluation of comma-
separated expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects


how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition
operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has


higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedenace operators
will be evaluated first.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type) * & sizeof Right to left

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 5


Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 6


Algorithm:
Step 1: Start
Step 2: Accept the temperature in Celsius
Step 3: Calculate temperature in Fahrenheit
F=1.8 *C+32
Step 4: Display temperature in Fahrenheit
Step 5: Stop

Source Code:
#include<stdio.h>
#include<conio.h>

void main( )
{
float f, c;
clrscr();
printf(“Enter Temperature in Celsius:”);
scanf(“%f”,&c);
f=1.8*c+32;
printf(“Temperature in Fahrenheit:%f”,f);
getch();
}

Output:
Enter Temperature in Celsius: 30
Temperature in Fahrenheit:86

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 7


Experiment No: 02
Aim: Study of if-else structure in ’C’
Problem Statement: Write a program to accept three numbers and display largest
of three using a nested if else statement

Problem Definition:
Input: Accept three numbers
Processing: Find the maximum of three numbers
Output: Display maximum number

Theory:
The if statement
The if statement gives the user the choice of executing a statement (possibly
compound) if the expression is evaluated to true or skipping it is the expression is
evaluated to false.

Format 1:

if (expression)
{
statement
}
The statement is executed if and only if the expression is true.
Example
if (num > 10)
{
result = 2 * num;
}
The content of num is multiply by 2 if and only if the value of num is greater than 10.

Format 2: C language also lets one choose between two statements by using the if-
else if structure.

if (expression)
{
statement 1
}
else
{
statement 2
}
In this case, if the expression is true, then the statement 1 is executed. Otherwise,
statement 2 is executed.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 8


Example
if (num > 10)
{
result = 2 * num;
}
else
{
result = 3* num;
}
In the above example, if the num is greater than 10 then the result is equal to the num
multiplied by 2 otherwise it is equal to the num multiplied by 3.

Algorithm:
Step1: Start
Step2: Accept three numbers a, b, c
Step3: if (a>b) and
if(a>c) then
display a
else then
if(b>c) then
display b
else then
display c
Step4: Display largest number
Step5: Stop

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 9


Source Code:
#include<stdio.h>
#include<conio.h>

void main( )
{
int a, b, c;
clrscr();
printf(“Enter The values of a, b, c”);
scanf(“%d %d %d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“%d is the largest number”, a);
}
else
{
printf(“%d is the largest number”, c);
}
}
else
{
if(b>c)
{
printf(“%d is the largest number”, b);
}
else
{
printf(“%d is the largest number”, c);
}
}
getch();
}

Output:
Enter The values of a, b, c 10 15 20
20 is the largest number

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 10


Experiment No: 03
Aim: Study of if-else
else ladder.

Problem Statement: Write a program to find all the roots of a quadratic equation
equa
using if-else ladder.

Problem Definition:
Input: Coefficients of quadratic equation a, b and c
Processing: Using the formula

To check roots are


i) Real and equal [when b2 -4ac=0]
ii) Real and distinct [When b2-4ac>0]
4ac>0]
2
iii) Imaginary [ when b -4ac<0]
Output: Type of roots
i) Real and equal
ii) Real and distinct
iii) Imaginary
Theory:
The if statement
In C programming language the else if ladder is a way of putting multiple ifs together
when multipath decisions are involved. It is a one of the types of decision making and
branching statements. A multipath decision is a chain of if’s in which the statement
associated with each else is an if. The general form of else if ladder is as follows -

if( condition 1)
{
statement 1;
}
else if(condition 2)
{
statement 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statement;
}
statement-x;

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88


Mumbai Page 11
This construct is known as the else if ladder. The conditions are evaluated from the
top of the ladder to downwards. As soon as a true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x
(skipping the rest of the ladder). When all the n conditions become false, then the
final else containing the default statement will be executed.

Algorithm:
Step1: Start
Step2: read co-efficient of quadratic equation a, b, c
Step3: if ‘a’ is zero print “not a quadratic equation”.
Calculate and print the answer using formula =-c/b
Else
Calculate d using the formula b2-4ac
If d=0
Print “real and equal roots”
Print root= –b/2a
if d>0
Print “real and distinct roots”
Calculate roots using formulae
(-b +sqrt(d)/2a) and (-b-sqrt(d)/2a)
Print both the roots.
If d<0
Print “imaginary roots”
Calculate real parts as –b/2a
Calculate imaginary part as sqrt(-d)/2a
Print the roots using real and imaginary parts.
Step4: Stop

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 12


Source Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
float A , B , C , root1 , root2;
float realp , imgp , disc;
clrscr();
printf(" Enter the values of A , B and C\n");
scanf("%f%f%f" , &A , &B , &C);

if(A==0 || B==0 || C==0)


{
printf(" Error: Roots cannot be determined\n");
}

else
{
dis = (B * B) - (4 * A * C);
if(disc<0)
{
printf(" Imaginary Roots\n");
realp = -B/(2*A);
imagp = sqrt(abs(disc))/(2*A);
printf(" Root1 = %f + i%f\n" , realp , imagp);
printf(" Root2 = %f - i%f\n" , realp , imagp);
}

else if( disc == 0)


{
printf(" Roots are real and equal\n");
root1 = -B/(2 * A);
root2 = Root1;
printf(" Root1 = %f\n" , root1);
printf(" Root2 =%f\n" , root2);
}

else if(disc>0)
{
printf(" Roots are real and distinct\n");
root1 = (-B + sqrt(disc))/(2*A);
root2 = (-B - sqrt(disc))/(2*A);
printf(" Root1 = %f\n" , root1);
printf(" Root2 = %f\n" , root2);
}

}
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 13


Output:

Output1:
Enter the values of A , B and C
321
Imaginary roots
Root1 = -0.3333 + i0.471402
Root2 = -0.3333 - i0.471405

Output2:
Enter the values of A , B and C
121
Roots are real and equal
Root1 = -1.0000
Root2 = -1.0000

Output3:
Enter the values of A , B and C
352
Roots are real and distinct
Root1 = -0.666667

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 14


Experiment No: 04
Aim: Study of switch case.
Problem Statement: Write a program to implement an arithmetic calculator for
addition, subtraction, multiplication, division and modulo operation using switch case.

Problem Definition:
Input: Accept two numbers and select operation
Processing: Find the result of selected operation
Output: Display result of operation

Theory:
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for
each switch case.
Syntax:
The syntax for a switch statement in C programming language is as follows:
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement:

• The expression used in a switch statement must have an integral or enumerated


type, or be of a class type in which the class has a single conversion function to an
integral or enumerated type.

• You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.

• The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.

• When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 15


• When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.

• Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.

• A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.

Algorithm:
Step1: Start
Step2: Enter two numbers a, b
Step3: Enter a choice from 1-5(op)
Step4: switch(op)
case 1: res=a+b;
break;
case 2: res=a-b;
break;
case 3: res=a*b;
break;
case 4: res=a/b;
break;
case 5: res=a%b;
break;
default: invalid choice;
Step5: Display Result
Step6: Stop

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 16


Source Code:
# include<stdio.h>
void main()
{
int a, add, sub, mul, mod, div, x, y;
printf("enter a number\n :");
scanf("%d",&x);
printf("enter another number\n :");
scanf("%d",&y);
printf("1=addition")
printf("2=subtraction");
printf("3=multiplication");
printf("4=division");
printf("5=Modulus");
printf("enter tour choice\n :");
scanf("%d",&a);
switch(a)
{
case 1: add=x+y;
printf("addition of %d and %d is =%d\n",x,y,add);
break;
case 2: sub=x-y;
printf("subtraction of %d and %d is =%d\n",x,y,sub);
break;
case 3: mul=x*y;
printf("multiplication of %d and %d is =%d\n",x,y,mul);
break;
case 4: div=x/y;
printf("division of %d and %d is =%d\n",x,y,div);
break;
case 5: mod=x%y;
printf("division of %d and %d is =%d\n",x,y,mod);
break;
default :printf("wrong choice");
}
}

Output:
enter a number
2
enter another number
3
1=addition
2=subtraction
3=multiplication
4=division
5=Modulus
1
addition of 2 and 3 is =5

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 17


Experiment No: 05
Aim: Study of while loop.
Problem Statement: Write a program to check whether the given number is
Armstrong number or not using while loop.

Problem Definition:
Input: Accept a number
Processing: Compare the sum of cubes of each digit of a number with itself.
Output: Display whether entered number is Armstrong number or not.

Theory:

A while loop is a control flow statement that allows code to be executed


repeatedly based on a given Boolean condition. The while loop can be thought of as a
repetition if statement.

The while construct consists of a block of code and a condition. The condition
is evaluated, and if the condition is true, the code within the block is executed. This
repeats until the condition becomes false. Because while loop checks the condition
before the block is executed, the control structure is often also known as a pre-test
loop. Compare with the do while loop, which tests the condition after the loop has
executed.

An Armstrong number of three digits is an integer such that the sum of the cubes of
its digits is equal to the number itself.

In other word “A number is Armstrong if it is equal the sum of cube of its digits.”
Example of Armstrong number is 371 because according to definition cube of its
digits sum will be equal to number so
Armstrong number 371= (3)3+(7)3+(1)3
371=27+343+1
371=371

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 18


Algorithm:
Step 1: Take input from user.

Step 2: Check whether the number has any divisor other than 1 and the number itself.

Step 3: If there is any divisor other than 1 or that number itself, then

Step 4: Consider the number as NOT PRIME

Step 5: Else consider the number as a PRIME NUMBER.

Source Code:
#include <stdio.h>
#include<conio.h>
void main()
{
int number, sum = 0, temp, remainder;
printf("Enter a number\n");
scanf("%d",&number);
temp = number;
while( temp != 0 )
{
remainder = temp%10;
sum = sum + remainder*remainder*remainder;
temp = temp/10;
}
if ( number == sum )
printf("Entered number is an Armstrong number.");
else
printf("Entered number is not an Armstrong number.");
getch( );
}
Output: Enter a number
371
Entered number is an Armstrong number.
Enter a number
111
Entered number is not an Armstrong number.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 19


Experiment No: 06
Aim: Study of do-while loop
Problem Statement: Write a program to find binary equivalent of a given
decimal number using as while loop.

Problem Definition:
Input: Accept a decimal number.
Processing: Divide the number by 2 and get quotient & remainder.
Output: Display the binary equivalent.

Theory:

In most computer programming languages, a do while loop, sometimes just called a


while loop, is a control flow statement that allows code to be executed once based on
a given Boolean condition. Note though that unlike most languages, FORTRAN's do
loop is actually the same as the for loop.

The do while construct consists of a process symbol and a condition. First, the code
within the block is executed, and then the condition is evaluated. If the condition is
true the code within the block is executed again. This repeats until the condition
becomes false. Because do while loops check the condition after the block is
executed, the control structure is often also known as a post-test loop. Contrast with
the while loop, which tests the condition before the code within the block is executed.
It is possible, and in some cases desirable, for the condition to always evaluates to
true, creating an infinite loop. When such a loop is created intentionally, there is
usually another control structure (such as a break statement) that allows termination of
the loop.
Algorithm:
Step 1: initialize sum=0 and i=1

Step 2: take input from user.

Step 3: find the reminder after divide by 2.

Step 4: get the new sum value.

Step 5: get the quotient value after divide by 2.

Step 6: continue this process for the condition no. is greater than 0.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 20


Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i=1,dec;
clrscr();
printf("Enter Decimal Number:");
scanf("%d",&dec);
do
{
rem=dec%2;
sum=sum+(i*rem);
dec = dec/2;
i=i*10
}while (dec > 0);
printf("\n The binary equivalent is %d",sum);
getch();
}

Output:
Enter Decimal Number:10
The binary equivalent is 1010

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 21


Experiment No: 07
Aim: Study implementation of for-loop.
Problem Statement: Write a program to check whether an entered number is
prime number or not using for-loop.

Problem Definition:
Input: Accept a number
Processing: Divide the number by numbers less than it and check for remainder
as zero or not each time.
Output: Display result as prime number or not.

Theory:

In computer science a for loop is a programming language statement which allows


code to be repeatedly executed. A for loop is classified as an iteration statement.

Unlike many other kinds of loops, such as the while loop, the for loop is often
distinguished by an explicit loop counter or loop variable. This allows the body of the
for loop (the code that is being repeatedly executed) to know about the sequencing of
each iteration. For loops are also typically used when the number of iterations is
known before entering the loop. For loops are the shorthand way to make loops when
the number of iterations is known, as a for loop can be written as a while loop.

A natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) is called a prime or a prime number if it has


exactly two positive divisors, 1 and the number itself. Natural numbers greater than 1
that are not prime are called composite.

Algorithm:
Step 1: Take input from user.

Step 2: Check whether the number has any divisor other than 1 and the number itself.

Step 3: If there is any divisor other than 1 or that number itself, then

Step 4: Consider the number as NOT PRIME

Step 5: Else consider the number as a PRIME NUMBER.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 22


Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{

int number,i,flag=1;
printf("Enter a number to check whether it is a PRIME NUMBER or not:");
scanf("%d",&number);
for(i=2;i<=number/2;i++)
{

if((number%i)==0)
{

flag=0;
break;

}
}
if(flag==0)

printf("This is not a prime number.");


else
printf("This is a prime number.");
getch();

Output:
Enter a number to check whether it is a PRIME NUMBER or not:6

This is not a prime number.

Enter a number to check whether it is a PRIME NUMBER or not:17

This is a prime number

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 23


Experiment No: 08
Aim: Study of nested for-loop
Problem Statement: Write a program to generate the following pattern using
nested for loop.
A B C D C B A
A B C B A
A B A
A

Problem Definition:
Input: Accept a number of rows of the pattern
Processing: Using nested for loop for printing spaces, characters in forward &
reverse order
Output: Display the desired pattern.

Theory:
In many cases we may use loop statement inside another looping statement. This type
of looping is called nested loop. In nested loop the inner loop is executed first and
then outer. The nested loop must be used to input or output multi-dimensional array
elements.

Algorithm:
Step 1: Read number of rows as input (i.e. n=4)

Step 2: for(i=1;i<=n;i++)

Step 3: i defines no.of rows

Step 4: for(j=1;j<=i-1;j++)

Step 5: j defines no. of spaces for a line

Step 6: for(k=65;k<=65+n-i;k++)

Step 7: here k is the character to print the character for above condition.

Step 8: for(k=65+n-i-1;k>=65;k--)

Step 9: here again character is printed

Step 10: above process continues till loop terminate.

Step 11: new line.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 24


Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,n;
clrscr();
printf(“Enter the rows of the pattern”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i-1;j++)
printf(" ");
for(k=65;k<=65+n-i;k++)
printf("%c",k);
for(k=65+n-i-1;k>=65;k--)
printf("%c",k);
printf("\n");
}
getch();
}

Output:
A B C D C B A
A B C B A
A B A
A

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 25


Experiment No: 09
Aim: Study for passing simple parameters to function.
Problem Statement: WAP to find out value of BIO using function, where BIO is
defined as BIO= n!/(r!(n-r)!), n and r are natural numbers.

Problem Definition:
Input:-read the value of n and r.
Processing: - Calculate the value of BIO, by using the formula
BIO=n!/(r!(n-r)!)
To find out this use the concept of function.
Output:-Display the value of BIO.

Theory: A function is a module or block of program code which deals with a


particular task. Making functions is a way of isolating one block of code from other
independent blocks of code.
Functions serve two purposes.
• They allow a programmer to say: `this piece of code does a specific job which
stands by itself and should not be mixed up with anything else',
• Second they make a block of code reusable since a function can be reused in
many different contexts without repeating parts of the program text.
A function can take a number of parameters, do required processing and then return a
value. There may be a function which does not return any value.
You already have seen couple of built-in functions like printf( ); Similar way you can
define your own functions in C language.

Declaration and Definition


When a function is defined at any place in the program then it is called function
definition. At the time of definition of a function actual logic is implemented with-in
the function.
A function declaration does not have any body and they just have their interfaces.
A function declaration is usually declared at the top of a C source file, or in a separate
header file.
A function declaration is sometime called function prototype or function signature.
For the Demo() function which returns an integer, and takes two parameters a
function declaration will be as follows:
int Demo( int par1, int par2);

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 26


Definitions as follows,
int Demo( int par1, int par2)
{
int total = 10;
printf("Hello World");
total = total + l;
return total;
}

Algorithm for main Function:


Step1. Start
Step2. Declare function
Step3. Declare the variables (i, n, r, BIO)
Step4. Read the value of n and r
Step5.Call function in formula , BIO=n!/(r!(n-r)!)
Step6.Display the result
Step7.Stop

Algorithm for find Factorial Function:


Step1.Start
Step2.Declare variable i,f=0
Step3. Initialize i=0,Reapeat step 4 until i<=num
Step4. f=f*i
Step5. Return f to main function

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 27


Source Code:
#include<stdio.h>
int findFactorial(int);
void main()
{
int i,BIO,n,r;
printf("Enter the value of n and r: ");
scanf("%d%d",&n,&r);
BIO = findFactorial(n)/( findFactorial(n)* findFactorial(n-r));
printf("Value of BIO is %d:",BIO);
getch( );
}
int findFactorial(int num)
{
int i,f=1;
for(i=1;i<=num;i++)
f=f*i;
return(f);
}

Output:
Enter the value of n and r: 5 4
Value of BIO is: 5

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 28


Experiment No: 10
Aim: Study for recursive function.
Problem Statement: WAP to find out GCD and LCM of two given numbers,
using recursive function.

Problem Definition:
Input:-Input the two natural integer numbers.
Processing: - Calculate the value of GCD, by using the formula
GCD(a, b)= a if b=0
GCD(a, b= GCD(b, a%b) otherwise
LCM(a,b)= (a * b) / GCD(a,b)
To find out this use the concept of function.
Output:-Display the GCD and LCM of two numbers.

Theory:
Recursive function is a special function that contains a call to itself. C supports
creating recursive function with ease and efficient. Recursive function allows you to
divide the complex problem into identical single simple cases which can handle
easily. Recursive function must have at least one exit condition that can be satisfied.
Otherwise, the recursive function will call itself repeatly until the runtime stack
overflows.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 29


Source Code:
#include <stdio.h>
int GCD(int, int);
void main()
{
int num1,num2,gcd,lcm;
printf("\nEnter two numbers:\n ");
scanf("%d %d",&num1,&num2);
gcd=GCD(num1,num2);
printf("\n\nGCD of %d and %d is: %d\n\n",num1,num2,gcd);
printf("\n\nLCM of %d and %d is: %d\n\n",num1,num2,(num1*num2)/gcd);
getch();
}
int GCD(int n1,int n2)
{
if(n2==0)
return(n1);
else
return GCD(n2,n1%n2);
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 30


Experiment No: 11
Aim: Study of one-dimensional Array.
Problem Statement: Write a program to find largest and second largest element
of array.

Problem Definition:
Input: Accept elements of an array.
Processing: Sort elements of an array in ascending order.
Output: Display largest and second largest element of sorted array.
Theory:
An array in C Programming Language can be defined as number of memory
locations, each of which can store the same data type and which can be references
through the same variable name. An array is a collection of similar elements. These
similar elements could be all integers or all floats or all characters etc. All elements of
any given array must be of the same type i.e. we can’t have an array of 10 numbers, of
which 5 are ints and 5 are floats.

Declaration of an Array:
datatype variable_name[lengthofarray];
for example,
double height[10];
float width[20];
int min[9];
char name[20];

Initializing Arrays
Initializing of array is very simple in c programming. The initializing values
are enclosed within the curly braces in the declaration and placed following an equal
sign after the array name. Here is an example which declares and initializes an array
of five elements of type int. Array can also be initialized after declaration.

int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one statement
int studentAge[4];
studentAge[0]=14;
studentAge[1]=13;
studentAge[2]=15;
studentAge[3]=16;

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 31


Algorithm:
Step 1: Start
Step 2: Declare variables and array(i,j,n,x[20],temp)
Step 3: Read the value of total no. of elements i.e. n in array
Step 4: Initialize i=0,repeat step no. 5 until i<total no. of elements
Step 5: Read the elements of array.
Step 6: Initialize i=0, Repeat the step no. 7 until i< n-1
Step 7: Initialize j=0, Repeat the step no. 8,9,10 until j< n-1
Step 8: temp=x[j]
Step 9: x[j]=x[j+1]
Step 10: x[j+1]=temp
Step 11: Display the largest and second largest element
Step 12: Stop

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 32


Source code:
# include <stdio.h>
# include<conio.h>
void main( )
{
int i, n,max,smax= -32768;
int x[20];
printf("\n Enter number of elements :");
scanf(“%d ”,&n);
printf("\n Enter Numbers in any order : ");
for(i=0; i<n; i++)
scanf(“%d”,&x[i]);
max=x[0];
for(i=1 ; i<n ; i++)
{
if(x[i]>max)
max=x[i];
}
for(i=0;i<n;i++)
if((x[i]>smax)&&(x[i]<max))
smax=x[i];
printf("\n Largest Element is : %d“,max);
printf("\n Second largest Element is : %d",smax);
getch( );
}

Output:
Enter number of elements :5
Enter Numbers in any order : 45 39 20 67 81
Largest Element is : 81
Second largest Element is : 67

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 33


Experiment No: 12
Aim: Program for passing one –dimensional Array to function.

Problem Statement: Write a program to accept N elements of an array and to sort


and Display them in ascending order using function.

Problem Definition:
Input: Read variables, array size and array elements.

Processing: Sort the array using formula

Output: Display array in ascending order.

Theory:
To pass an entire array to a function, only the name of the array is passed as an
argument.

result = calculateSum(num);

However, notice the use of [] in the function definition.

float calculateSum(float num[])


{
... ..
}

This informs the compiler that you are passing a one-dimensional array to the
function.

// Program to calculate the sum of array elements by passing to a


function

#include <stdio.h>
float calculateSum(float num[]);

void main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()


result = calculateSum(num);
printf("Result = %.2f", result);
getch();
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 34


float calculateSum(float num[])
{
float sum = 0.0;

for (int i = 0; i < 6; ++i)


sum += num[i];
return(sum);
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 35


Source code:
#include <stdio.h>
#include<conio.h>
void main()
{
void sort(int number[],int);
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);

printf("Enter the numbers \n");


for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
sort(number,n);
getch();
}
void sort(int number[], int n)
{
int a;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;

}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\t", number[i]);

}
Output:
Enter the value of N 5
Enter the numbers 20 30 10 60 80
The numbers arranged in ascending order are given below
10 20 30 60 80

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 36


Experiment No: 13
Aim: Study of Multi (two)-dimensional Array.
Problem Statement: Write a program for multiplication of two (M*N) matrices.
Problem Definition:
Input: Elements of two different matrices.
Processing: Check compatibility of two matrices. If compatible then perform
multiplication and display resultant matrix.
Output: Display the multiplication of two matrices.

Theory:
In C Language one can have arrays of any dimensions. To understand the concept
of multidimensional arrays let us consider the following 4 X 5 matrix,

Column numbers (j)

0 11 3 5 -9 -6
Row numbers (i)

1 5 6 -8 7 24

2 -8 9 2 12 45

3 10 13 -10 4 5

Declaration of two dimensional array,


Datatype variable_name [rowsize][columnsize];
For example,
float table [50] [50];
Initialization is as follows,
int values [3] [4] = {
{ 1, 2, 3, 4 }
{ 5, 6, 7, 8 }
{ 9, 10, 11, 12 }
};

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 37


Source Code:
#include <stdio.h>
#include <conio.h>
void main ()
{
int i , j , k ;
int set1[3][3] , set2[3][3] , multi[3][3] ;
printf(" Enter values of first 3X3 matrix :\n") ;
for (i=0 ; i<3 ; i++)
for (j=0 ; j<3 ; j++)
scanf(“%d”,&set1[i][j]) ;
printf(" Enter values of second 3X3 matrix :\n)" ;
for (i=0 ; i<3 ; i++)
for (j=0 ; j<3 ; j++)
scanf(“%d”,&set2[i][j]) ;
for (i=0 ; i<3 ; i++)
for (j=0 ; j<3 ; j++)
multi[i][j] = 0;
for (k=0 ; k<3 ; k++)
multi[i][j] += set1[i][k]*set2[k][j] ;
printf("The resulting 3X3 matrix is :\n") ;
for (i=0 ; i<3 ; i++)
for (j=0 ; j<3 ; j++)
printf(“%d\t”multi[i][j]);
printf("\n") ;
getch ( ) ;
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 38


Output:
Enter values of first 3X3 matrix :
1 1 1 1
2 2 2 2
3 3 3 3
Enter values of second 3X3 matrix :
1 1 1
1 2 2 2
3 3 3

The resulting 3X3 matrix is :


6 6 6
12 12 12
18 18 18

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 39


Experiment No: 14
Aim: Program for passing Multi-dimensional Array to function

Problem Statement: Write a program to calculate and display sum of all the
elements except diagonal elements of the matrix using function.

Problem Definition:
Input: Array Elements

Processing: Apply Addition of matrix using

s=s+a[i][j]

Output: Addition of non Diagonal matrix.

Theory:
To pass multidimensional arrays to a function, only the name of the array is passed to
the function (similar to one-dimensional arrays).
#include <stdio.h>
void displayNumbers(int num[2][2]);
void main()
{
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
scanf("%d", &num[i][j]);
}
}
displayNumbers(num); // pass multi-dimensional array to a function
getch();
}

void displayNumbers(int num[2][2])


{
printf("Displaying:\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}
Notice the parameter int num[2][2] in the function prototype and function definition:

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 40


// function prototype
void displayNumbers(int num[2][2]);

This signifies that the function takes a two-dimensional array as an argument. We can
also pass arrays with more than 2 dimensions as a function argument.

When passing two-dimensional arrays, it is not mandatory to specify the number of


rows in the array. However, the number of columns should always be specified.

For example,

void displayNumbers(int num[][2])


{
// code
}

Note: In C programming, you can pass arrays to functions, however, you cannot
return arrays from functions.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 41


Source Code:
#include<stdio.h>
#include<conio.h>
void main( )
{
int addition(int x[][10], int,int;
int i,j,r,c,s;
printf(“Enter size of matrix:”);
scanf(“%d%d”,&r,&c);
printf(“Enter Matrix Elements:”);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf(“%d”,&x[i][j]);
s=addition(x,r,c);
printf(“Sum of elements except diagonal elements is: %d”,s);
getch();
}
int addition(int x[][10],int r, int c)
{
int i,j, sum=0;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
sum=sum+x[i][j];
return(sum);
}

Output:
Enter size of matrix:3 3
Enter Matrix Elements:
1 2 3
2 1 3
3 2 1
Sum of elements except diagonal elements is: 15

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 42


Experiment No: 15
Aim: To write a program for character array.

Problem Statement: Write a program to check whether entered string is


palindrome or not .

Problem Definition:
Input: Data type:-integer variable i, j

Character str[], char strRev[])

Processing: get a string from user and apply reverse function.

Output: String is Palindrome or not .

Theory:
A string constant , such as
"I am a string"

Strings in C are represented by arrays of characters. The end of the string is marked
with a special character, the null character, which is simply the character with the
value 0. (The null character has no relation except in name to the null pointer. In the
ASCII character set, the null character is named NUL.) The null or string-terminating
character is represented by another character escape sequence, \0.

String constants are often used in making the output of code intelligible using printf ;

printf("Hello, world\n");
printf("The value of a is: %f\n", a);

String constants can be associated with variables. C provides the char type variable,
which can contain one character--1 byte--at a time. A character string is stored in an
array of character type, one ASCII character per location. Never forget that, since
strings are conventionally terminated by the null character ``\0'', we require one extra
storage location in the array!

C does not provide any operator which manipulate entire strings at once. Strings are
manipulated either via pointers or via special routines available from the

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 43


standard string library string.h. Using character pointers is relatively easy since the
name of an array is a just a pointer to its first element.

Strings in C are represented by arrays of characters. The end of the string is


marked with a special character, the null character, which is simply the character with
the value 0. (The null character has no relation except in name to the null pointer. In
the ASCII character set, the null character is named NUL.) The null or string-
terminating character is represented by another character escape sequence, \0. (We've
seen it once already, in thegetline function of chapter 6.)

Because C has no built-in facilities for manipulating entire arrays (copying them,
comparing them, etc.), it also has very few built-in facilities for manipulating strings.

In fact, C's only truly built-in string-handling is that it allows us to use string
constants (also called string literals) in our code. Whenever we write a string,
enclosed in double quotes, C automatically creates an array of characters for us,
containing that string, terminated by the \0 character. For example, we can declare and
define an array of characters, and initialize it with a string constant:

char string[] = "Hello, world!";

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 44


Source Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
int i, len, flag=0;
int flag = 0;
printf("Enter a string:");
scanf("%s", str);
len = strlen(str);
for(i=0,j=len-1;i < len/2 ;i++.j--)
{
if(str[i] != str[j])
{
flag = 1;
break;
}
}

if (flag==0)
printf("String is a palindrome");
else
printf("String is not a palindrome");
getch();
}

Output :
Enter a string : MADAM
String is a palindrome

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 45


Experiment No: 16
Aim: Program for passing character array to function.

Problem Statement: Write a program to concatenate first, middle and last


name using Function.

Problem Definition:
Input: Read thee string from user

Processing: concatenate all string together using user defined function.

Output: Display first name, middle name and last name together

Theory:
C's only truly built-in string-handling is that it allows us to use string
constants (also called string literals) in our code. Whenever we write a string,
enclosed in double quotes, C automatically creates an array of characters for us,
containing that string, terminated by the \0 character. For example, we can declare and
define an array of characters, and initialize it with a string constant:
char string[] = "Hello, world!";
In this case, we can leave out the dimension of the array, since the compiler can
compute it for us based on the size of the initializer (14, including the terminating \0).
This is the only case where the compiler sizes a string array for us, however; in other
cases, it will be necessary that we decide how big the arrays and other data structures
we use to hold strings are.

To do anything else with strings, we must typically call functions. The C library
contains a few basic string manipulation functions, and to learn more about strings,
we'll be looking at how these functions might be implemented.

Since C never lets us assign entire arrays, we use the strcpy function to copy one
string to another:

#include <string.h>

char string1[] = "Hello, world!";


char string2[20];

strcpy(string2, string1);

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 46


In formal language theory and pattern matching (including regular expressions), the
concatenation operation on strings is generalized to an operation on sets of strings as
follows:

For two sets of strings S1 and S2, the concatenation S1S2 consists of all strings of the
form vw where v is a string from S1 and w is a string from S2.

In this definition, the string vw is the ordinary concatenation of strings v and w as


defined in the introductory section. In this context, sets of strings are often referred to
as formal languages.

In formal language theory and computer programming, string concatenation is the


operation of joining two character strings end-to-end. For example, the concatenation
of "snow" and "ball" is "snowball".

In many programming languages, string concatenation is a binary infix operator. The


"+" operator is often overloaded to denote concatenation for string arguments: "Hello,
" + "World"; has the value "Hello, World".

In formal language theory and pattern matching (including regular expressions), the
concatenation operation on strings is generalized to an operation on sets of strings as
follows:

For two sets of strings S1 and S2, the concatenation S1S2 consists of all strings of the
form vw where v is a string from S1 and w is a string from S2.

In this definition, the string vw is the ordinary concatenation of strings v and w as


defined in the introductory section. In this context, sets of strings are often referred to
as formal languages.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 47


Source Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char fname[30], mname[10],lname[10];
void stringConcat(char fname[],char mname[],char lname[]);
printf(“Enter First Name:”);
gets(fname);
printf(“Enter Middle Name:”);
gets(mname);
printf(“Enter Last Name:”);
gets(lname);
stringConcat(fanme,mname,lname);
getch( );
}
void stringConcat(char fname[],char mname[],char lname[])
{
int n, i,j;
n=strlen(fname);
fname[n]=” “;
for(i=0,j=n+1;mname[i]!=’\0’; i++,j++)
{
fname[j]=mname[i];
}
fname[j]=” “;
for(i=0,k=j+1;lname[i]!=’\0’; i++,k++)
{
fname[k]=mname[i];
}
fname[j]=’\0’;
printf(“String after concatenation: ”)
puts(fname);

Output:
Enter First Name: Manoj
Enter Middle Name: Shankarrao
Enter Last Name: Dhande
String after concatenation: Manoj Shankarrao Dhande

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 48


Experiment No: 17
Aim: Study of Structure.
Program Statement: Define a structure called Player with data members. Player
name, team name, batting average. Create array of objects, store information about
players. Sort and display information of players in descending order of batting
average.

Problem Definition:
Input: Number of players and their name, team and batting average.
Processing: Accept the details of players. Compare the batting average of all
the players and arrange them in descending order of their average.
Output: Display the list of players in descending order of their batting
average.

Theory: A structure is a group of data elements grouped together under one name.
These data elements, known as members, can have different types and different
lengths. Data structures are declared in C using the following syntax:

struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
-------------------
-------------
} object_names;

Where structure_name is a name for the structure type, object_name can be a set of
valid identifiers for objects that have the type of this structure. Within braces { } there
is a list with the data members, each one is specified with a type and a valid identifier
as its name.
The first thing we have to know is that a structure creates a new type: Once a structure
is declared, a new type with the identifier specified as structure_name is created and
can be used in the rest of the program as if it was any other type.
For example:
struct product
{
int weight;
float price;
};
product apple, banana;

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 49


We have first declared a structure type called product with two members: weight and
price, each of a different fundamental type. We have then used this name of the
structure type (product) to declare three objects of that type: apple, banana as we
would have done with any fundamental data type. Once declared, product has become
a new valid type name like the fundamental ones int, char or short and from that point
on we are able to declare obects (variables) of this compound new type, like we have
done with apple, banana.

Right at the end of the struct declaration, and before the ending semicolon, we can use
the optional field object_name to directly declare objects of the structure type. For
example, we can also declare the structure objects apple, banana at the moment we
define the data structure type this way:
struct product
{
int weight;
float price;
}apple, banana;
Once we have declared our objects of a determined structure type (apple, banana) we
can operate directly with their members. To do that we use a dot (.) inserted between
the object name and the
member name. For example, we could operate with any of these elements as if they
were standard variables of their respective types: apple.weight,apple.price
Each one of these has the data type corresponding to the member they refer to:
apple.weight, banana.weight are of type int, while apple.price, banana.price are of
type float.
Algorithm:
Step 1: Start
Step 2: Accept number of players from the user.
Step 3: For each player accept player name, team name and batting average.
Step 4: Compare the batting average of each player with all the others and arrange the
player as per the average in descending order.
Step 5: Display the details of players in sorted order.
Step 6: Stop

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 50


Source Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct Player
{
char playerName[10];
char teamName[10];
int battingAvg;
};
void main()
{
struct Player p[10],temp;
int n,i,j;
clrscr();
printf("Enter no of Players:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Player Name :\n");
scanf("%s",&p[i].playerName);
printf("Enter Team Name :\n");
scanf("%s",&p[i].teamName);
printf("Enter batting average of player :\n");
scanf("%d",&p[i].battingAvg);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i].battingAvg<p[j].battingAvg)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
printf("\nAfter Sorting:\n");
printf("Player Name\t Team Name\t Batting Average\n");
printf("----------------------------------------------------------------\n");
for(i=0;i<n;i++)
{
printf("%s\t\t",p[i].playerName);
printf("%s\t\t",p[i].teamName);
printf("%d\n",p[i].battingAvg);
}
getch();
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 51


OUTPUT:
Enter Player Name :Umar
Enter Team Name :Pakistan
Enter batting average of player :78
Enter Player Name :Sachin
Enter Team Name :India
Enter batting average of player :94
Enter Player Name :Yuvraj
Enter Team Name :India
Enter batting average of player :67

After Sorting:
Player Name Team Name Batting Average
---------------------------------------------------------------------
Sachin India 94
Umar Pakistan 78
Yuvraj India 67

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 52


Experiment No: 18
Aim: Study of Structure.
Program Statement: Define a structure called Player with data members. Player
name, team name, batting average. Create array of objects, store information about
players. Sort and display information of players in descending order of batting
average using function.

Problem Definition:
Input: Number of players and their name, team and batting average.
Processing: Accept the details of players. Compare the batting average of all
the players and arrange them in descending order of their average.
Output: Display the list of players in descending order of their batting
average.

Theory:
#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
void display(struct student s);

int main()
{
struct student s1;

printf("Enter name: ");

// read string input from the user until \n is entered


// \n is discarded
scanf("%s", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

display(s1); // passing struct as an argument

return 0;
}

void display(struct student s) {


printf("\nDisplaying information\n");

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 53


printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
Here, a struct variable s1 of type struct student is created. The variable is passed to
the display() function using display(s1); statement.
Here's how you can return structure from a function:
#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
struct student getInformation();

int main()
{
struct student s;

s = getInformation();

printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);

return 0;
}
struct student getInformation()
{
struct student s1;

printf("Enter name: ");


scanf ("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

return s1;
}
Here, the getInformation() function is called using s = getInformation(); statement.
The function returns a structure of type struct student. The returned structure is
displayed from the main() function.
Notice that, the return type of getInformation() is also struct student.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 54


Source Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct Player
{
char playerName[10];
char teamName[10];
int battingAvg;
};
void main()
{
struct Player p[10],temp;
void sort(struct Player p[],int);
int n,i,j;
clrscr();
printf("Enter no of Players:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Player Name :\n");
scanf("%s",&p[i].playerName);
printf("Enter Team Name :\n");
scanf("%s",&p[i].teamName);
printf("Enter batting average of player :\n");
scanf("%d",&p[i].battingAvg);
}
sort(p,n);
getch();
}
void sort(struct p[],int n)
{
int i,j,temp;
struct Player temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i].battingAvg<p[j].battingAvg)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
printf("\nAfter Sorting:\n");
printf("Player Name\t Team Name\t Batting Average\n");
printf("----------------------------------------------------------------\n");

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 55


for(i=0;i<n;i++)
{
printf("%s\t\t",p[i].playerName);
printf("%s\t\t",p[i].teamName);
printf("%d\n",p[i].battingAvg);
}
getch();
}

Output:
Enter Player Name :Umar
Enter Team Name :Pakistan
Enter batting average of player :78
Enter Player Name :Sachin
Enter Team Name :India
Enter batting average of player :94
Enter Player Name :Yuvraj
Enter Team Name :India
Enter batting average of player :67

After Sorting:
Player Name Team Name Batting Average
---------------------------------------------------------------------
Sachin India 94
Umar Pakistan 78
Yuvraj India 67

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 56


Experiment No: 19
Aim: Study of pointers and function.
Program Statement: Write a program to swap two numbers using Call- by -value
and call- by-reference.

Problem Definition:
Input: Two numbers.
Process: Interchange the contents of memory location in the called function
by using a temporary variable.
Output: Swapped numbers.

Theory:
In call by value method, the value of the actual parameters is copied into the
formal parameters. In call by value method, we cannot modify the value of the actual
parameter by the formal parameter. In call by value, different memory is allocated for
actual and formal parameters since the value of the actual parameter is copied into the
formal parameter. The actual parameter is the argument which is used in the function
call whereas formal parameter is the argument which is used in the function definition

Pointers can be used in functions declaration. The call by address is a type of


method invocation in which the address or the location of the parameters are passed to
the calling portion of the function. When pointer variable is used as formal argument,
then calling a function is referred as call by address. In call by address, when a
function is called by a program, the address of actual arguments are copied on to the
formal arguments. That is, formal and actual arguments are referencing to same
memory location. Therefore change in value of formal argument affects the value of
actual argument. The call by address is used when function produces more than one
value and provides these values to the caller.

For example,
void f1 (int *, int *);
void main ( )
{
----------------
// call by address
f1 (&a, &b);
---------------------
}

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 57


void f1(int *x, int *y)
{
----------------
}
We are calling the function in statement

f1 (&a, &b);
And we are passing address of a and b to the formal pointer variables x and y. x and
a refers to same memory location; y and b refers to same memory location. Any
change in value of x or y will ultimately changes the value of a and b.

Algorithm:
Main Program:
Step 1: Start
Step 1: Accept two numbers to be swapped
Step 2: Display the numbers before interchanging them.
Step 3: Call a function to swap the two numbers by passing the address of the original
numbers.
Step 4: Display the numbers after interchanging them.
Step 5: Stop

Swap Subprogram:
Step 1: Start
Step 2: Interchange the contents of original memory location
Step 3: Return to the main module.

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 58


Source Code:
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int a,b;
clrscr();
printf("CALL BY Address\n");
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("BEFORE CALLING : \n");
printf("A : %d B : %d\n",a,b);
/* swap( ) is called by passing the addresses of two variables whose values are
to be
interchanged. */
swap(&a,&b);
printf("AFTER CALLING : \n");
printf("A : %d B : %d",a,b);
getch();
}
// swap( ) function exchange the value of two integer variables using call by address.
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

OUTPUT:
CALL BY Address
Enter two numbers
10
20
BEFORE CALLING :
A : 10 B : 20
AFTER CALLING :
A : 20 B : 10

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 59


Experiment No: 20
Aim: Program for array and pointers.
Program Statement: Write a program using pointers to display the contents of
array in reverse order.

Problem Definition:
Input: List of numbers.
Processing: Point to the last element. Keep on displaying the contents and
decrement the pointer to point to previous element till pointer reaches the first
element.
Output: Display the list in reverse order.

Theory:
If *ptr = 2; the compiler will know how many bytes to copy into that memory location
pointed to by ptr. If ptr was declared as pointing to an integer, 2 bytes would be
copied, if a long, 4 bytes would be copied. Similarly for floats and doubles the
appropriate number will be copied. But, defining the type that the pointer points to
permits a number of other interesting ways a compiler can interpret code.
For example, consider a block in memory consisting of ten integers in a row.
That is, 20 bytes of memory are set aside to hold 10 integers. Now, let's say we point
our integer pointer ptr at the first of these integers. Furthermore let’s say that integer
is located at memory location 2000 (decimal). What happens when we write: ptr++;

Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it
points to an integer (its current address, 2000, is the address of an integer), it adds 2 to
ptr instead of 1, so the pointer "points to" the next integer, at memory location 2002.
Similarly, if the ptr was declared as a pointer to a long, it would add 4 to it instead of
1. The same goes for other data types such as floats, doubles, or even user defined
data types such as structures. This is obviously not the same kind of "addition" that

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 60


we normally think of. In C it is referred to as addition using "pointer arithmetic".
Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in
the program when ptr is incremented may be different), incrementing a pointer using
the unary ++ operator, either pre- or post-, increments the address it stores by the
amount sizeof(type) where "type" is the type of the object pointed to. (i.e. 2 for an
integer, 4 for a long, etc.). Since a block of 10 integers located contiguously in
memory is, by definition, an array of integers, this brings up an interesting
relationship between arrays and pointers.

Consider the following:


int arr[ ] = {1,2,3,4,5};

Here we have an array containing 5 integers. We refer to each of these integers by


means of a subscript to arr, i.e. using arr[0] through arr[4]. But, we could
alternatively access them via a pointer as follows:
int *ptr;
ptr = &arr[0]; //point our pointer at the first integer in our array

In C, the standard states that wherever we might use &var_name[0] we can replace
that with var_name, thus in our code where we wrote:
ptr = &arr[0];
we can write:
ptr = arr;
to achieve the same result.
The name of the array is the address of first element in the array.
Algorithm:
Step 1: Start
Step 1: Accept n elements from the user.
Step 2: Place the pointer at the last element.
Step 3: Display the element pointed by the pointer.
Step 4: Decrement the pointer by one so that it points to the previous element in the
list.
Step 5: repeat step 3 and step 4 until all elements are displayed
Step 6: Stop
Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 61
Source Code:
// Program to display elements of an array in reverse order using pointer
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void main()
{
int a[SIZE],*ptr,i,n;
clrscr();
printf("\nEnter the number of elements: ");
scanf("%d",&n);
printf("\nEnter the elements of an array :\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
ptr=a+n-1;
printf("\nThe elements in reverse order are : \n");
for(i=0;i<n;i++)
{
printf("%d ",*ptr);
ptr--;
}
getch();
}

OUTPUT:
Enter the number of elements: 5
Enter the elements of an array :
12345
The elements in reverse order are :
54321

Shah & Anchor Kutchhi Engineering College, Chembur, Mumbai-88 Page 62

You might also like