CP Manual
CP Manual
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
Process: 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
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 is equal or not, if yes then condition (A == B) is not true.
becomes true.
!= Checks if the value of two operands is equal or not, if values are not equal then (A != B) is true.
condition becomes true.
> Checks if the value of left operand is greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right (A >= B) is not true.
operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B) is true.
operand, if yes then condition becomes true.
&& Called Logical AND operator. If both the operands are non zero then condition (A && B) is true.
becomes true.
|| Called Logical OR Operator. If any of the two operands is non zero then (A || B) is true.
condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. !(A && B) is false.
If a condition is true then Logical NOT operator will make false.
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
& Binary AND Operator copies a bit to the result if (A & B) will give 12 which is 0000 1100
it exists in both operands.
| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
eather operand.
^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49 which is 0011 0001
one operand but not both.
~ Binary Ones Complement Operator is unary and (~A ) will give -60 which is 1100 0011
has the efect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands A << 2 will give 240 which is 1111
value is moved left by the number of bits specified 0000
by the right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15 which is 0000 1111
value is moved right by the number of bits
specified by the right operand.
Assignment Operators:
There are following assignment operators supported by C language:
Operator Description Example
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 variable. &a; will give actaul address of the variable.
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
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
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.
Example
if (num > 10)
{
}
else
{
}
result = 2 * num;
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
Theory:
To check roots are
i) Real and equal [when b2 -4ac=0]
ii) Real and distinct [When b2-4ac>0]
iii) Imaginary [ when b2-4ac<0]
Output: Type of roots
i) Real and equal
ii) Real and distinct
iii) Imaginary
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;
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 discriminate„d‟ using the formula b2-4ac If„d‟ equals zero
Print “real and equal roots” Calculate roots using –b/2a Print both the roots
Else if„d‟ is greater than zero Printf “real and distinct roots”
Calculate roots using formula
(-b +sqrt(d)/2a) and (-b-sqrt(d)/2a) Print both the roots.
Else
Printf “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
Conclusion: Concept of if-else ladder find all the roots of a quadratic equation .
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 Process: 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 */
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
Conclusion: Concept of Array is implemented to check largest and second largest element.
Experiment No: 10
Aim: Study of Multi (two)-dimensional Array.
Problem Statement: Write a program for multiplication of two (M*N) matrices.
Problem Definition:
Input: Read elements of two different matrices.
Process: Multiply 2 matrices using matrix multiplication rule.
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,
Row Column numbers (j)
numbe 0 11 3 5 -9 -6
rs (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 }
};
Algorithm:
Step 1: Start
Step 2: Declare variables and 3 two dimensional array(i,j,k,set1[3][3],set2[3][3], multi[3][3] )
Step 3: Read the elements of first 3x3 matrix.
Step 4: Initialize i=0,repeat step no. 5 until i<3
Step 5: Initialize j=0, Repeat the step no. 6 until j< 3
Step 6: Read the elements of matrix1.
Step 7: Read the elements of first 3x3 matrix.
Step 8: Initialize i=0,repeat step no. 9 until i<3
Step 9: Initialize j=0, Repeat the step no. 10 until j< 3
Step 10: Read the elements of matrix.
Step 11: Initialize i=0,repeat step no. 12until i<3
Step 12: Initialize j=0, Repeat the step no. 13,14,15 until j< 3
Step 13: Initilize multi[i][j]=0
Step 14: Initilize k=0, Repeat the step no. 14 until j< 3
Step 15: multi[i][j] += set1[i][k]*set2[k][j] ;
Step 16: Display the resultant matrix
Step 17: Initialize i=0,repeat step no. 18 until i<3
Step 18: Initialize j=0, Repeat the step no. 19 until j< 3
Step 19: Print the elements of resultant matrix.
Step 20: Stop
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 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!";
Algorithm:
Step 1: Start
Step 2: Declare i, j, str[], strRev[]
Step 3: for(i=0;str[i]!='\0';i++)
i--;
for(j=0;i>=0;i--,j++)
strRev[j]=str[i]; strRev[j]='\0'; bool flag=true;
for(int i=0;str[i]!='\0';i++)
if(str[i]!=strRev[i])
flag=false;
Break the Loop
Initializing strRev as a null string Print Enter a string:
Take string input from the user Apply strReverse(str,strRev); print Reversed string:
if string is Pallindrome then print strRev
Step 4: display string is a pallindrome. else
display stringis not a pallindrome.
Step 5: Stop
Conclusion:
Concept of String manipulation is implemented to check if string is palindrome or not.
Experiment No. 14
Aim: Study of 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.
Process: Sort the array using formula
Output: Display array in ascending order.
Theory:
An array in C language is a collection of similar data-type, means an array can hold value of a particular data type
for which it has been declared. Arrays can be created from any of the C data-types int, float, and char. So an integer
array can only hold integer values and cannot hold values other than integer. When we declare array, it allocates
contiguous memory location for storing values whereas 2 or 3 variables of same data-type can have random
locations. So this is the most important difference between a variable and an array.
Types of Arrays:
1. One dimension array (Also known as 1-D array). Discussed below in this tutorial.
2. Two dimension array (Also known as 2-D array). Click on link to see the tutorial
3. Multi-dimension array. Click on link to see the tutorial
Declaration of One Dimensional Arrays:
Syntax: data_type array_name[width];
Example: int roll[8];
In our example, int specifies the type if the variable, roll specifies the name of the variable and the value in bracket
[8] is new for newbie. The bracket ([ ]) tells compiler that it is an array and number mention in the bracket specifies
that how many elements (values in any array is called elements) it can store. This number is called dimension of
array.
Conclusion:
Concept of passing One–dimensional Array to function is implemented.
Experiment No: 15
Aim: Study of 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
Process: Apply Addition of matrix using s=s+a[i][j]
Output: Addition of non Diagonal matrix.
Theory:
Two-dimensional arrays are a little more complicated to use than one-dimensional ones. This page presents two
methods of passing a pointer to a two-dimensional array to a function for processing.
● The first method uses subscript notation inside the function. This method has the same disadvantage as in
Pascal -- the function is essentially array specific in that the data types need to match. However, while in
Pascal you need to have a programmer-defined double- subscripted type which is used for both the array
and the parameter in the called function, in C only the second subscript in each needs to match. A complete
sample program is provided below.
● The second method uses typecasting in the function call and a pointer with offsets inside the function.
This method permits the programmer to use the same function to process information in arrays with
different dimensions. A complete sample program is provided below.
Consider an int array as declared below. #define NUM_STUDENTS 5
#define NUM_TESTS 4
int grades[NUM_STUDENTS][NUM_TESTS];
● By convention, the first subscript is understood to be for rows and the second for columns.
● This array can hold up to 20 integer values, the product of the values used to declare the array.
● As is usual in C, subscripts start with zero, so the subscripts range from 0 to 4 for the rows and 0 to 3 for
the columns.
● If the system uses four bytes for an int, this array would use 80 bytes of RAM. All of the bytes are in
consecutive memory locations, the first row occupying the first 20 bytes, the second the next 20, and so
on.
The following table illustrates how the subscripts are specified for this array, which has five (5) rows and four (4)
columns.
0 1 2 3
It may facilitate your programming, if you keep track of how many elements in the array hold usable values. For
this simple example, we can initialize two variables.
int num_students = 2; int num_tests = 3;
The second and third arguments allow the function to search only the elements which have been initialized.
One of the ways of writing get_highest() uses subscript notation:
int get_highest(int a[][NUM_TESTS], int row, int col)
/* Assumes that there is at least one element */
{
int i, j;
int highest = a[0][0];
So the above example declares a 2D array of integer type. This integer array has been named arr and it can hold
up to 9 elements (3 rows x 3 columns).
Algorithm:
Step 1: Start
Step 2: input int a[3][3],i,j,s=0,r,c;
Step 3: read number of rows from user Step 4: read number of columns from user Step 5:if(r==c)
print "Enter the numbers:" Step 6:for(i=0;i<r;i++)
for(j=0;j<c;j++)
Step 7:Display the matrix for(i=0;i<r;i++) for(j=0;j<c;j++) print Matrix.
print Sum of non diagonal elements are: for(i=0;i<r;i++)
for(j=0;j<c;j++)
Step 8:if(i!=j)
s=s+a[i][j];
Step 9:Display s;
Step 10: Stop.
strcpy(string2, string1);
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.
Algorithm:
Step 1: start
Step 2: Declare four string with string size
Step 3: Read first name from user. Step 4: Read second name from users. Step 5: Read last name
from users.
Step 6: Copy string fnm to name. Concatenate string name, " " Concatenate string name and
mnm. Concatenate string name, “ ”.
Concatenate string name with last names.
Step 7: Display complete name.
Step 8: Stop.
Conclusion: Concept of passing character array to function is implemented
Experiment No: 17
Aim: Study of pointers and function.
Program Statement: Write a program to swap two numbers using call by address.
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:
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 ( )
{
}
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 2: Accept two numbers to be swapped
Step 3: Display the numbers before interchanging them.
Step 4: Call a function to swap the two numbers by passing the address of the original numbers.
Step 5: Display the numbers after interchanging them.
Step 6: Stop
Swap Subprogram:
Step 1: Start
Step 2: Interchange the contents of original memory location
Step 3: Return to the main module.
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 2: Accept n elements from the user.
Step 3: Place the pointer at the last element.
Step 4: Display the element pointed by the pointer.
Step 5: Decrement the pointer by one pointing to the previous element in the list.
Step 6: repeat step 3 and step 4 until all elements are displayed
Step 7: Stop
Conclusion:Concept of array and pointer is implemented
Experiment No: 19
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 & their name, team and batting average.
Process: Accept the details of players.
Compare the batting average of all the players. Arrange them in descending
order of their average.
Output: Display the list 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;
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 & arrange the player as
per the average in descending order.
Step 5: Display the details of players in sorted order.
Step 6: Stop