CP Experiments
CP Experiments
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:
• Arithmetic Operators
• Logical (or Relational) Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators:
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Operators Categories:
All the operators we have discussed above can be categorised into following
categories:
Precedence of C Operators:
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.
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
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.
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
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
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
if( condition 1)
{
statement 1;
}
else if(condition 2)
{
statement 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statement;
}
statement-x;
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
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 distinct\n");
root1 = (-B + sqrt(disc))/(2*A);
root2 = (-B - sqrt(disc))/(2*A);
printf(" Root1 = %f\n" , root1);
printf(" Root2 = %f\n" , root2);
}
}
}
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
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 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.
• 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
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
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:
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
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
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.
Problem Definition:
Input: Accept a decimal number.
Processing: Divide the number by 2 and get quotient & remainder.
Output: Display the binary equivalent.
Theory:
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 6: continue this process for the condition no. is greater than 0.
Output:
Enter Decimal Number:10
The binary equivalent is 1010
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:
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.
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
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)
Output:
Enter a number to check whether it is a PRIME NUMBER or not:6
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 4: for(j=1;j<=i-1;j++)
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--)
Output:
A B C D C B A
A B C B A
A B A
A
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.
Output:
Enter the value of n and r: 5 4
Value of BIO is: 5
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.
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;
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
Problem Definition:
Input: Read variables, array size and array elements.
Theory:
To pass an entire array to a function, only the name of the array is passed as an
argument.
result = calculateSum(num);
This informs the compiler that you are passing a one-dimensional array to the
function.
#include <stdio.h>
float calculateSum(float num[]);
void main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
}
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
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,
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
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
s=s+a[i][j]
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();
}
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.
For example,
Note: In C programming, you can pass arrays to functions, however, you cannot
return arrays from functions.
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
Problem Definition:
Input: Data type:-integer variable i, j
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
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:
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
Problem Definition:
Input: Read thee string from user
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>
strcpy(string2, string1);
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 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.
Output:
Enter First Name: Manoj
Enter Middle Name: Shankarrao
Enter Last Name: Dhande
String after concatenation: Manoj Shankarrao Dhande
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;
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
After Sorting:
Player Name Team Name Batting Average
---------------------------------------------------------------------
Sachin India 94
Umar Pakistan 78
Yuvraj India 67
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;
return 0;
}
// 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;
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.
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
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
For example,
void f1 (int *, int *);
void main ( )
{
----------------
// call by address
f1 (&a, &b);
---------------------
}
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.
OUTPUT:
CALL BY Address
Enter two numbers
10
20
BEFORE CALLING :
A : 10 B : 20
AFTER CALLING :
A : 20 B : 10
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
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