[go: up one dir, main page]

0% found this document useful (0 votes)
26 views40 pages

CP Manual

Uploaded by

tanudevu2
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)
26 views40 pages

CP Manual

Uploaded by

tanudevu2
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/ 40

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
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

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denominator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division
++ Increment operator, increases integer value by A++ will give 11
one
-- Decrement operator, decreases integer value by A-- will give 9
one

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

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 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

= Simple assignment operator, Assigns values C = A + B will assigned value of A + B into C


from right side operands to left side operand

+= Add AND assignment operator, It adds right C += A is equivalent to C = C + A


operand to the left operand and assign the
result to left operand

-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A


subtracts right operand from the left
operand and assign the result to left operand

*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left
operand and assign the result to left operand

/= Divide AND assignment operator, It divides C /= A is equivalent to C = C / A


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 operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2


operator
|= bitwise inclusive OR and assignment C |= 2 is same as C = C | 2
operator

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.

* 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

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

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

Conclusion: Concept of operator is implemented for given problem statement


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
Process: 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.
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

Conclusion: If else control statement is implemented to find largest of three numbers.


Experiment No. 03
Aim: Study of if-else ladder.
Problem Statement: Write a program to find all the roots of a quadratic equation using if-else ladder.
Problem Definition:
Input: Coefficients of quadratic equation a, b and c
Process: Using the formula

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 */

/* 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.
● 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

Conclusion:Concept of switch case implement to perform arithmetic operations


Experiment No: 05
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
Process: 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.

Conclusion: Concept of for control statement is implemented


Experiment No: 06
Aim: Study of nested for-loop
Problem Statement: Write a program to generate the following pattern using nested for loop.
Problem Definition:
Input: Accept a number of rows of the pattern
Process: 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.

Conclusion: Concept of nested for loop is implemented to display pattern


Experiment No: 07
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
Process: 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
Algorithm:
Step 1: Take input from user.
Step 2: Initialize sum=0.
Step 3: For num>=0, divide the no. by 10. And get the new remainder value.
Step 4: find the new value of sum.
Step 5: Check the condition sum==number.
Step 6: if condition is true than no. is Armstrong no. if not than not an Armstrong no.
Conclusion: Concept of while control statement is implemented to check if the entered number is Armstrong or not
Experiment No: 08
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.
Process: 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 remainder 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.
Conclusion:Concept of while loop control statement is implemented.
Experiment No: 09
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.
Process: 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;

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

Conclusion:Concept of 2D array is implemented to perform addition of two matrices.


Experiment No. 11
Aim: Study for passing simple parameters to function.
Problem Statement: Write a program to find 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.
Process: Calculate the value of BIO, by using the formula BIO=n!/(r!(n-r)!) 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); Definitions as follows,
int Demo( int par1, int par2)
{
int total = 10; printf("Hello World"); total = total + l;
return total;
}
Algorithm for main ():
Step 1: Start
Step 2: Declare function
Step 3: Declare the variables (i, n, r, BIO)
Step 4: Read the value of n and r
Step 5: Call function in formula , BIO=n!/(r!(n-r)!)
Step 6: Display the result
Step 7: Stop
Algorithm for findFactorial (int num):
Step 1: Start
Step 2: Declare variable i,f=0
Step 3: Initialize i=0,Reapeat step 4 until i<=num
Step 4: f=f*i
Step 5: Return f to main function
Conclusion: Concept of passing parameters to function is implemented
Experiment No. 12
Aim: Study of recursive function.
Problem Statement: Write a program to find out GCD and LCM of two given numbers, using
recursive function.
Problem Definition:
Input: Read two natural integer numbers.
Process: Among 2 numbers divide greater by smaller
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.
Algorithm for main ():
Step 1: Start
Step 2: Declare function for GCD and LCM
Step 3: Declare the variables num1,num2,gcd,lcm
Step 4: Read the value of num1 and num2
Step 5: Call function of GCD, as gcd=find_gcd(num1,num2);
Step 6: Display the GCD of two numbers
Step 7: Check num1>num2,if true goto step 8,if false goto step9 Step 8: Call function of LCM,
as lcm = find_lcm(num1,num2); Step 9: Call function of LCM, as lcm = find_lcm(num2,num1);
Step 10: Display the LCM of two numbers.
Step 11: Stop
Algorithm for GCD (int n1,int n2):
Step 1: Start
Step 2: Reapeat step 3, 4 until n1!=n2
Step 3: Check n1>n2 ,if true return find_gcd(n1-n2,n2)
Step 4: If false return find_gcd(n1,n2-n1)
Step 5: Return n1 to main function
Algorithm for LCM (int n1,int n2):-
Step 1: Start
Step 2: Declare variable temp=0
Step 3: Check , temp % n2 == 0 && temp % n1 == 0 if true, return temp
Step 4: temp=temp+1
Step 5: call find_lcm(n1,n2)
Step 6: return temp to main
Conclusion:

Concept of recursive function is implemented .


Experiment No: 13
Aim: Study of 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[], strrev[])
Process: 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"
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 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.

C Array Assignment and Initialization:


We can initialize and assign values to the arrays in the same way as we do with variable. We can assign value to
an array at the time of declaration or during runtime. Let‟s look at each approach. Syntax: data_type
array_name[size]={list of values};
Example:
int arr[5]={1,2,3,4,5};
int arr[]={1,2,3,4,5};
In our above array example we have declared an integer array and named it “arr” which can hold 5
elements, we are also initializing arrays in the same time.
Both statements in our example are valid method to declare and initialize single dimension array. In our
first example we mention the size (5) of an array and assigned it values in curly brace, separating
element‟s value by comma (,). But in second example we left the size field blank but we provided its
element‟s value. When we only give element values without providing size of an array then C compiler
automatically assumes its size from given element values.
Algorithm:
Step 1: Read variables n1, n2, i, x, y, z; Create array int a[50],b[50], c[100];
Step 2: print “Enter two arrays which are sorted in ascending order" print"How many elements
in 1st array"
read number of elements from the user for 1st array. print"Enter the elements of 1st array"
enter the elements for 1st array.
Step 3: for(i=1;i<n1;i++) Enter the elements of 1st array if (a[i]<a[i-1])
Step 4: print"Array should be sorted in ascending order" exit(1);
Step 5: Stop

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

0 [0][0] [0][1] [0][2] [0][3]


1 [1][0] [1][1] [1][2] [1][3]
2 [2][0] [2][1] [2][2] [2][3]
3 [3][0] [3][1] [3][2] [3][3]
4 [4][0] [4][1] [4][2] [4][3]

Array Initialization: Inline


To initialize all elements of the grades array to -1 (a number that is highly improbable for a grade), you could use
a nested loop structure such as the following.
for( i = 0; i < NUM_STUDENTS; i++) for( j = 0; j < NUM_TESTS; j++)
grades[i][j] = -1;

Array Initialization: At Declaration


It is also possible to initialize elements of an array at the time of its declaration. The following declaration assigns
values for three grades for each of the first two students in the array. Note that the values for a specific row are
enclosed within their own pair of curly brackets.
int grades[NUM_STUDENTS][NUM_TESTS] = { {55, 60, 65},
{95, 90, 85} };

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;

Array Processing: Using Subscripts in a Function


Since, by definition, the name of any array is a pointer, we can call a function which returns the highest grade in
the array as follows.
high_test = get_highest( grades, num_students, num_tests);

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];

for( i = 0; i < row; i++) for( j = 0; j < col; j++)


if ( a[i][j] > highest)
highest = a[i][j]; return highest;
}
It is necessary in this instance to specify the number of columns in the array (the number of items in a row) so that
the compiler can determine the offsets from the beginning of the array. Unlike with the one-dimensional array
algorithm, where we avoided comparing the first element with itself, here the extra code required does not
outweigh the simplicity of the above algorithm.
The 2D array is also known as Matrix or Table, it is an array of array. See the 2D array image, in that image each
row is an array.
Declaration of 2D array:
Syntax: data_type array_name[row_size][column_size];
Example: int arr[3][3];

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.

Conclusion: Concept of passing Multi-dimensional Array to function


Is implemented
Experiment No: 16
Aim: Study of passing character array to function.
Problem Statement: Write a program to concatenate first, middle and last name using function.
Problem Definition:
Input: Read first, middle & last name from user
Process: Concatenate all string together using strcat 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);

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 ( )
{

// call by address f1 (&a, &b);

}
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.

Conclusion:Concept of pointers and function is implemented


Experiment No: 18
Aim: Study of arrays and pointers.
Program Statement: Write a program using pointers to display the contents of an array in reverse
order.
Problem Definition:
Input: List of numbers.
Process: 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 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 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

Conclusion: Concept of structure is implemented


Experiment No: 20

Aim: Study of File.


Program Statement: Write a program to copy the contents of one file to another file.
Problem Definition:
Input: Name of source and destination file.
Process: Open the source file in read mode & destination file in write mode.
Copy the contents character by character from source file to destination file till
end of file is encountered.
Output: Contents of source file copied to contents of destination file
Theory:
We frequently use files for storing information which can be processed by our programs. In order to store
information permanently and retrieve it we need to use files. As you know, you can have many files on
your disk. If you wish to use a file in your programs, then you must specify which file or files you wish
to use. Specifying the file you wish to use is referred to as opening the file.
When you open a file you must also specify what you wish to do with it i.e. Read from the file, Write
to the file, or both. Because you may use a number of different files in your program, you must specify
when reading or writing which file you wish to use. This is accomplished by using a variable called a
file pointer.
Every file you open has its own file pointer variable. You declare these file pointer variables as follows:
FILE *fopen(), *fp1, *fp2, *fp3; //variables fp1, fp2, fp3 are file pointers.
The file <stdio.h> contains declarations for the Standard I/O library and should always be included at
the very beginning of C programs using files. Constants such as FILE, EOF and NULL are defined in
<stdio.h>.
Reading from Files
To read from a file, the file must be opened for reading e.g. fp = fopen( “prog.c”, “r”) ;
The above statement opens a file called prog.c for reading and associates the file pointer fp with the file.
When we wish to access this file for I/O, we use the file pointer variable fp to refer to it. You can have
up to about 20 files open in your program - you need one file pointer for each file you intend to use.
Writing to Files
To write to a file, the file must be opened for writing e.g. fp = fopen( fname, “w” );
If the file does not exist already, it will be created. If the file does exist, it will be overwritten! So, be
careful when opening files for writing, in case you destroy a file unintentionally. Opening files for writing
can also fail. If you try to create a file in another users directory where you do not have access you will
not be allowed and fopen will fail.
File I/O The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar() and putc(c,fp) is similar to putchar(c).
Thus the statement
c = getc(fp); //reads the next character from the file referenced by fp and the statement
putc(c,fp); //writes the character c into file referenced by fp.
Closing a Files
The function fclose is used to close the file i.e. indicate that we are finished processing this file.
Algorithm:
Step 1: Start
Step 2: Accept the name of source and destination file from user.
Step 2: Open source file in read mode.
Step 3: Open destination file in write mode.
Step 4: If the file is not opened then display error message and go to step 8.
Step 5: Read one character at a time from source file & copy it in the destination file.
Step 6: Repeat step 6 until end of file(EOF) is reached.
Step 7: Close all the open files.
Step 8: Stop

Conclusion: Concept of file is implemented.

You might also like