You are on page 1of 60

PROGRAMMING FOR PROBLEM

SOLVING

Lab Manual
Version 1.0
LIST OF EXPERIMENTS
PAGE
S.NO NAME OF THE EXPERIMENT
NO.
1. Tutorial - 1 Problem solving using computers 3

2. Lab - 1 Familiarization with programming environment 4

3. Tutorial - 2 Variable types and Type conversions 7

4. Lab - 2 Problems on Arithmetic expressions 9

5. Tutorial - 3 Branching and Logical expressions 11

6. Lab - 3 Problems on Branching 14

7. Tutorial - 4 Loops, While and For loops 17

8. Lab - 4 Problems on Iteration 19

9. Tutorial - 5 1D Arrays: Searching and Sorting 21

10. Lab - 5 1D Array manipulation 23

11. Tutorial - 6 2D arrays and Strings 26

12. Lab - 6 2D and String operations 28

13. Tutorial - 7 Functions and Call by value 31

14. Lab - 7 Problems on Functions 33

Tutorial - Numerical methods (Root finding, Numerical


15. 34
8&9 differentiation, Numerical Integration)

16. Lab - 8 & 9 Problems on Numerical methods 36

17. Tutorial - 10 Recursion and structure of Recursive calls 39

18. Lab - 10 Recursive functions 40

19. Tutorial - 11 Pointers, Structures and Dynamic memory allocation 43

20. Lab - 11 Pointers and Structures 45

21. Tutorial - 12 File handling 48

22. Lab - 12 File operations 50

2|Page
TUTORIAL : 01 PROBLEM SOLVING USING COMPUTERS

The problems come from any real-world problem or perhaps even from the abstract
world. The problems need a standard systematic approach to solve. Since it solves with the
help of the computer, it is important to understand the computer’s functional model. The
model shown in the diagram below assumes a single CPU (Central Processing Unit).

Central Processing
Unit
Control Unit
INPUT OUTPUT

Arithmetic and
Logical Unit

STORAGE

Problem Solving is the sequential process of analyzing information related to a given


situation and generating appropriate response options. There are six steps to solve a problem:

1. Understand the Problem


2. Formulate a Model
3. Develop an Algorithm
4. Write the Program
5. Test the Program
6. Evaluate the Solution

Algorithm efficiency is used to describe the properties of an algorithm relating to


how many types of resources it consumes. It can be measured by time and space complexity.

 The time complexity (or) running time of an algorithm is the amount of time that it
takes to complete once it has begun
 The space complexity of an algorithm is the amount of storage space that it requires
while running from start to completion

3|Page
FAMILIARIZATION WITH PROGRAMMING
LAB : 01
ENVIRONMENT

Programming environment is a software package that helps to develop and test the
program code.

PREPROCESSOR:

It expands all macros definitions, conditional compilation instructions and include


statements (and anything that starts with a #) and passes the result to the actual compiler.

COMPILER:

It takes lines of code and converts them into machine language (assembly language).
Recall that a computer only understands 1s and 0s. Therefore, convert the instructions into
computer understandable form. It reads the whole source code at once, creates tokens, checks
semantics, generates intermediate code, executes the whole program and involves many
passes. If an error occurs it reads the whole program even if it encounters several errors.

ASSEMBLER:

It translates assembly language programs into machine code. The output of an


assembler is called an object file, which contains a combination of machine instructions as
well as the data required to place these instructions in memory.

LINKER:

It is a computer program that links and merges various object files together in order to
make an executable file. All these files might have been compiled by separate assemblers.

LOADER:

It is a part of operating system and responsible for loading executable files into
memory and executes them. It calculates the size of a program (instructions and data) and
creates memory space for it.

4|Page
DEVELOPING THE PROGRAM USING WINDOWS:

Step - 1. Assume that you have installed Turbo C7 by Akki on your computer
Step - 2. Open Turbo C7 by Akki from the Desktop or Programs menu. Select “File” from
Menu bar, click on the option “New” and type the following program

#include<stdio.h>
#include<conio.h>
void main( )
{
printf("Welcome to Programming Environment");
getch();
}
Step - 3. To SAVE the C program. Select File -> Save (Or using function key F2). Name
the file as “HELLO.C” or some other name with a “.C” extension under TC\BIN
directory in C- Drive.

Step - 4. Compile the program using ALT + F9 (Or) Compile -> Compile in menu bar

5|Page
After compiling, dialog box appears as shown below. If the
compilation is success, “success” message gets displayed; otherwise it shows
the number of errors.

Step - 5. Run the program using CTRL + F9 (Or) Run -> Run in menu bar

Step - 6. After Run it automatically redirects to the output screen. Alternatively the shortcut
for output screen is ALT + F5

6|Page
DEVELOPING THE PROGRAM USING LINUX:

Step - 1. Assume that Ubuntu Linux is installed in the computer


Step - 2. In order to compile and execute a C program ensure that the essential packages
installed in the system. To check that, enter the following command as root in
Linux Terminal:
$ sudo apt-get install build-essential

Step - 3. After installing essential packages, type the following program using (gedit, vi or
graphical text editor). Using text editor,

Alternatively, the above program done through Terminal in gedit by,


$ gedit sampleProgram.c
It will create a sampleProgram.c file

7|Page
Step - 4. To Compile the program, in the Terminal enter the following command to make an
executable version,
$ gcc sampleProgram.c -o sampleProgram

Step - 5. To Run the compiled program, in the Terminal enter the following command,
$ ./sampleProgram

8|Page
VARIABLE TYPES TYPE CONVERSIONS AND
TUTORIAL : 02
ARITHMETIC EXPRESSIONS

VARIABLE TYPES:

A variable is a name used to store a data value. Different types of variables requires
different amount of memory, and have some specific set of operations which can be applied
on them. Memory space is not allocated for a variable while declaration. It happens only on
variable definition. Variable initialization means assigning a value to the variable. The types
of variables are,

 Char - Used to hold/store a Character


 Int - Used to hold/store an Whole numbers
 Float - Used to hold/store a Decimal numbers
 Double - Used to hold/store a Double value
 Void

Syntax for Variable declaration:

1. Data_type variable_name; //for single variable


2. Data_type variable1_name, variable2_name; // for multiple variables

Example for Variable declaration:

1. int fact; //for single variable


2. float num1, num2; // for multiple variables

Syntax for Variable initialization:

Data_type variable_name = value;


Data_type variable1_name, variable2_name = value1, value2;

Example for Variable initialization:

1. int sum = 5; //for single variable


2. float num1= 18.21, num2 = 6.8; // for multiple variables

9|Page
A variable name can consist of alphabets (both upper and lower case), numbers and
only the underscore ‘_’ special character. However, the name must not start with a number
and with keywords. Blank spaces are also not allowed. It takes maximum length up to 31
characters.

TYPE CONVERSION (OR) TYPE CAST:

It means conversion from one data type to another data type. There are two types of type
conversion:

1. Implicit Type Conversion:

It’s also known as ‘Automatic type conversion’ done by the compiler on its
own, without any external trigger from the user. Generally it takes places in an
expression with more than one data type is present. All the data types of the variables
are upgraded to the data type of the variable with largest data type.

The hierarchies of conversion are,

bool  char  short int  int  unsigned int  long  unsigned 


long long  float  double  long double

Example:

int a=42;
float b=a;

2. Explicit Type Conversion:

It is an user defined conversion. Here the user can type cast the result to make it of
a particular data type.

Syntax:

(data_type) expression

Example:
float a=42.12;
int b=(int) a;

10 | P a g e
ARITHMETIC EXPRESSIONS:

An arithmetic expression contains only arithmetic operators and operands. A unary


operator has one operand. A binary operator has two operands and a ternary operator has
three operands. If the expression contains more than one operator precedence level should
followed. In general, BODMAS rules followed to solve the expression.

Operator Meaning of Operator Example


If a = 5 and b = 2 then,
+ Adds two operands
expression (a + b) equals to 7
If a = 5 and b = 2 then,
- Subtracts second operand from the first
expression (a - b) equals to 3
If a = 5 and b = 2 then,
* Multiplies both operands
expression (a * b) equals to 10
If a = 5 and b = 2 then,
/ Divides numerator by de-numerator
expression (a / b) equals to 2
Modulus Operator and remainder of If a = 5 and b = 2 then,
%
after an integer division expression (a % b) equals to 1
Increment operator increases the If a = 5 then, expression (a ++)
++
integer value by one equals to 6
Decrement operator decreases the If a = 5 then, expression (a --)
--
integer value by one equals to 4

11 | P a g e
LAB : 02 PROBLEMS ON ARITHMETIC EXPRESSIONS

AIM:

To construct a ‘C’ program to solve the following problems using Arithmetic


expressions.

a) Convert the length in Feet to Centimeter


b) Convert temperature from Centigrade to Fahrenheit and Fahrenheit to
Centigrade

2a) Convert the length in Feet to Centimeter:

Algorithm:

Step 1  START
Step 2  Get the value for the variable Lft from the user to compute Lcm
Step 3  Compute Lcm by multiplying 30 with Lft value got from the user
Step 4  Print the processed value stored in the “Lcm” to the user
Step 5  STOP

Flowchart:

START

Input Lft

Lcm = Lft * 30

Print Lcm

STOP

12 | P a g e
2b) Convert temperature from Centigrade to Fahrenheit and Fahrenheit to Centigrade:

Algorithm:

Step 1  START
Step 2  Get the value for the variable F from the user to compute C
Step 3  Compute C by subtracting the value of F got from the user with 32 and
multiplying the obtained value to 0.56
Step 4  Print the processed value “C” to the user
Step 5  Get the value for the variable C from the user to compute F
Step 6  Compute F by multiplying the value of C got from the user with 1.8 and
adding the obtained value to 32
Step 7  Print the processed value “F” to the user
Step 8  STOP

Flowchart:

START

Input F

C = (F – 32) * 0.56

Print C

Input C

F = 32 + (C * 1.8)

Print F

STOP

13 | P a g e
RESULT:

Thus the following problems,

a) Convert the length in Feet to Centimeter


b) Convert temperature from Centigrade to Fahrenheit and Fahrenheit to Centigrade

Using Arithmetic expressions are implemented, executed and verified.

14 | P a g e
TUTORIAL : 03 BRANCHING AND LOGICAL EXPRESSIONS

BRANCHING:

In C, programs follow a sequential form of execution of statements. Many times it is


required to alter the flow of sequence of instructions.

 The statements that can alter the flow of a sequence of instructions are called as
control statements.
 To jump from one part of the program to another, these statements will help. The
control transfer may be unconditional or conditional.

Branching Statements are,

If Statement:

It is the simplest and very frequently used control statement. It allows the flow of
program execution and decision making.

Syntax:

if (condition)
{
statement;
}

Example:

if (rem==0)
{
printf(“The entered number is even.”);
}

If … Else Statement:

It is an extension of if statement. If the result of the condition is true, then program


statement 1 is executed else program statement 2 will be executed.

15 | P a g e
Syntax:

if (condition)
{
statement 1;
}
else
{
statement 2;
}

Example:

if (rem==0)
{
printf(“The entered number is even.”);
}
else
{
printf(“The entered number is odd.”);
}

Nested If Statement:

One if statement occurs within another if statement, then such type of is called nested
if statement.

Syntax:

if (condition1)
{
if (condition2)
{
statement-1;
}
else
{

16 | P a g e
statement-2;
}
}
else
{
statement-3;
}

Example:

if(n= =15)
{
printf(“Play foot ball”);
}
else
{
if(n= =10)
printf(“Play cricket”);
else
printf(“don’t play”);
}

If …. Else if …. Else:

It checks the condition given in if and else if block and executes the respective block;
otherwise it will execute the else block.

Syntax:

if(condition)
{
statement;
}
else if( condition)
{
statement;
}

17 | P a g e
else
{
statement;
}

Example:

if(n= =15)
{
printf(“Play foot ball”);
}
else if(n= =10)
{
printf(“Play cricket”);
}
else
{
printf(“don’t play”);
}

Switch Statement:

It consists of several cases which includes a default case. Each case must have a break
statement to jump out of switch block on its execution. The cases are matched then they
execute with the provided condition.

Syntax:

switch(variable)
{
case 1:
statement;
break;
default:
statement;
}

18 | P a g e
Example:

switch(n)
{
case 'S':
printf("Sunday");
break;
case 'M':
printf("Monday");
break;
default:
printf("Out of Choice");
break;
}

LOGICAL EXPRESSIONS:
An expression is any legal combination of symbols that represents a value. Every
expression consists of at least one operand and can have one or more operators. An
expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are commonly used in decision making in C
programming.

Operator Meaning of Operator Example


Logical AND. If c = 5 and d = 2 then, expression
&&
True only if all operands are true ((c == 5) && (d > 5)) equals to 0.
Logical OR. If c = 5 and d = 2 then, expression
||
True only if either one operand is true ((c == 5) || (d > 5)) equals to 1.
Logical NOT. If c = 5 then, expression
!
True only if the operand is 0 ! (c == 5) equals to 0.

19 | P a g e
LAB : 03 PROBLEMS ON BRANCHING

AIM:

To construct a ‘C’ program to solve the following problems using Branching and
Logical expressions.

a) Find the given numbers is Odd or Even


b) Find the Biggest of three numbers

3a) Find the given numbers is Odd or Even:

Algorithm:

Step 1 START
Step 2  Get the value for the variable Num from the user to compute odd or even
Step 3  Perform modulo 2 operation on the number got from the user
Step 4  Compare the modulo operation output to zero
Step 5  Check the output equals to zero, continue to step 7
Step 6  Check the output not equal to zero, continue to step 8
Step 7  Print “Even” go to step 9
Step 8  Print “Odd”, go to step 9
Step 9  STOP

Flowchart:
START

Input Num

T F
If
Num % 2 == 0

Print Even Print Odd

STOP

20 | P a g e
3b) Find the Biggest of three numbers:

Algorithm:

Step 1  START
Step 2  Get the value for the variable A, B, C from the user to compute the biggest
Step 3 Compare the value A, B. If A > B, continue to step 4, otherwise go to step 5
Step 4  Compare the value A, C. If A > C, continue to step 6, otherwise go to step 8
Step 5  Compare the value A, C. If B > C, continue to step 7, otherwise go to step 8
Step 6  Print "A is the Big", go to step 9
Step 7  Print "B is the Big", go to step 9
Step 8  Print “C is the Big", go to step 9
Step 9  STOP

Flowchart:

START

Input A, B, C

T F T If
T Print A is
Print A is If If
big B>C A>B A>C big

F
F
Print C is
Big

STOP

21 | P a g e
RESULT:

Thus the following problems,

a) Find the given numbers is Odd or Even


b) Find the Biggest of three numbers

Using Branching and Logical expressions are implemented, executed and verified.

22 | P a g e
TUTORIAL : 04 LOOPS, WHILE AND FOR LOOPS

LOOPS:

When a single statement or a group of statements executed again and again in a


program until a specific condition is met, then such type processing is called loop. Loop is
divided into two parts:

(a) Body of the loop

(b) Control of loop

There are three loops in C programming.

FOR LOOP:

It is one step loop, which initialize, check the condition and increment / decrement the
step in the loop in a single statement.

Syntax:

for( initialization; condition; iteration)


{
statements;
}

Example:

for(count = 1; count <= num; ++count)


{
sum += count;
}

WHILE LOOP:

It is also called as an entry control loop. In this, first of all condition is checked and if
it is true, then group of statements or body of loop is executed. It will execute again and again
till condition becomes false.

23 | P a g e
Syntax:

while (test condition)


{
statements;
}

Example:

while (count <= num)


{
sum += count;
--count;
}

DO...WHILE LOOP:
It is also called as exit control loop. do-while statement. In this statement, first body
of the loop is executed and then the condition is checked. If condition is true, then the body of
the loop is executed. When condition becomes false, then it will exit from the loop.

Syntax:

do
{
statements;
} while (condition);

Example:

do
{
sum += count;
--count;
} while (count <= num);

24 | P a g e
LAB : 04 PROBLEMS ON ITERATION

AIM:

To construct a ‘C’ program to solve the following problems using Iterative


statements.

a) Find the Sum of given ten Natural numbers


b) Print the Multiplication table for given number

4a) Find the Sum of given ten Natural numbers:

Algorithm:

Step 1  START
Step 2  Assign zero for the variable S and one for the variable I
Step 3  Check the variable I is less than or equal to 10, continue to step 4, otherwise
go to step 6
Step 4  Compute the value of S by adding it with I, continue to step 5
Step 5  Increment the value of I by adding it with 1, continue to step 3
Step 6  Print the value of S to the user, go to step 7
Step 7  STOP

Flowchart: START

Assign
S = 0, I = 1

S=S+I

I=I+1

T
Is I <= 10
F

Print S

STOP

25 | P a g e
4b) Print the Multiplication table for given number:

Algorithm:

Step 1  START
Step 2  Assign M and the value 1 to the variable I
Step 3  Get the value for Num from the user
Step 4  Check the value of I is equal to 11, continue to step 8, otherwise step 5
Step 5  Compute M by multiplying I with value of Num got from the user
Step 6  Print “M” to the user
Step 7  Increment I by adding it with 1, go to step 4
Step 8  STOP

Flowchart:

START

Assign
M, I = 1

Input Num

T
Is I = 11
F
M = Num * I

Print M

I=I+1

STOP

RESULT:

Thus the following problems,

a) Find the Sum of given ten Natural numbers


b) Print the Multiplication table for given number
Using Iterative statements are implemented, executed and verified.

26 | P a g e
ONE DIMENSION ARRAY: SEARCHING AND
TUTORIAL : 05
SORTING

ARRAY:

An array is a group of related data items, which share common name. It is the set of
homogeneous data.

ONE DIMENSIONAL ARRAY:

This type of array is also called as linear array and list array. These arrays are of
ladder type. In the linear array only one subscript is used. It is written either in row or in
column form.

Syntax for Declaration:

Data_type array_name [size];

Example for Declaration:

int num [5];

Syntax for Initialization:

Data_type array_name[size]={list of values};

Example for Initialization:

int num [5] = {4, 2, 8, 6, 1};

Always, Contiguous (adjacent) memory locations are used to store array elements in memory.

SEARCHING:

It is the process of searching the element from the group of elements. There are two
popular methods of searching and they are linear search and binary search.

27 | P a g e
 Linear Search:
This is one of the simplest techniques for searching an unordered table for a
particular element. In this each and every entry in the table is checked in a sequential
manner until the desired element is found.
 Binary Search:
 The basic requirement is the elements of the array should have been sorted
alphabetically or numerically in the ascending order.
 The approximate middle element of the array is located by dividing the entire
number of elements by two
 Key value gets compared with middle element
 If its value is too high, then the right side to the middle element is examined
and the procedure is repeated until the required element is found
 If the value is too low, then the left side to the middle element is tried and the
procedure is repeated until the required element is found

SORTING:

This is the operation of arranging the elements of a table into some sequential order
according to ordering criteria. The sort is performed according to the key value of each of the
elements. Depending on the structure of the key, elements can be sorted numerically,
alphabetically or alphanumerically. The elements are arranged in ascending or descending
order according to the numerical value of each of the elements.

28 | P a g e
LAB : 05 ONE DIMENSION ARRAY MANIPULATION

AIM:

To construct a ‘C’ program to solve the following problems using One dimensional
array.

a) Find the Sum and average of 10 elements in an array


b) Search a number from a list of given numbers

5a) Find the Sum and average of 10 elements in an array:

Algorithm:

Step 1  START
Step 2  Assign I = 0, Sum = 0
Step 3  Check the value of I is less than 10, continue to step 4, otherwise step 7
Step 4  Get the array elements A [I] from the user, continue to step 5
Step 5  Compute Sum by adding it with A [I] got from the user, continue to step 6
Step 6  Increment I by adding it with 1, continue to step 3
Step 7  Print “Sum” to the user
Step 8  Compute Avg by dividing Sum by 10, continue to step 9
Step 9  Print “Avg” to the user
Step 10  STOP

29 | P a g e
Flowchart:

START

Assign I = 0, Sum = 0

T
Is I < 10

F
Input A [I]

Sum = Sum + A [I]

I=I+1

Print Sum

Avg = Sum / 10

Print Avg

STOP

5b) Search a number from the list of given numbers:


Algorithm:

Step 1  START
Step 2  Get the size of an array N from the user
Step 3  Assign C = 0
Step 4  Check the condition C is less than N, continue to step 5, otherwise step 7
Step 5  Get the array values for A [C] from the user, continue to step 6
Step 6  Increment C by adding it with 1, continue to step 4

30 | P a g e
Step 7  Get the search key S from the user
Step 8  Check the condition C is less than N, continue to step 9, otherwise step 12
Step 9  Check A [C] is less than S, continue to step 10, otherwise step 11
Step 10  Print “Element Found” to the user
Step 11  Print “Element Not Found” to the user
Step 12  STOP

Flowchart:

START

Input N

Assign C = 0

F
Is C < N
T

Input A [C]

C=C+1

Input S

T F
Is Print Element
Is C < N
A [C] < S Not Fond
F T

Print Element
Fond

STOP

31 | P a g e
RESULT:

Thus the following problems,

a) Find the Sum of all elements in an array


b) Search a number from a list of given numbers
Using One dimensional array was implemented, executed and verified.

32 | P a g e
TUTORIAL : 06 TWO DIMENSIONAL ARRAYS AND STRINGS

TWO DIMENSIONAL ARRAYS:

An array of arrays is known as 2D (or) two dimensional arrays. It is also known as


matrix. A matrix can be represented as a table of rows and columns. Here array has two
subscripts. One subscript denotes row & the other denotes the column.

Syntax for Declaration:

Data_type array_name [ROW][COL];

The total number of elements in a 2-D array is ROW * COL.

Example for Declaration:

int num [2] [3];

Syntax for Initialization:

Data_type array_name [ROW][COL] = {list of values};

Example for Initialization:

int num [2] [3] = {{4, 2, 8}, {6, 1, 7}};

In the 1D array, no need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, in 2D array defining at least the
second dimension of the array is important.

STRINGS:

It stored as an array of characters terminated by a null character. An array of


characters is a string only if it’s last element is a null character ('\0'). The null character is an
escape sequence just like \n (newline), \t (tab). When compiler encounters a sequence of
characters enclosed in the double quotation marks, it appends a null character ‘\0’ at the end.

33 | P a g e
Declaring and initializing a string variable:

A string variable is any valid variable name and always declared as an array. When
the compiler assigns a character string to a character array, it automatically supplies a null
character '\0' at the end of the string. Therefore, the size should be equal to the maximum
number of characters in the string +1. While declaring a string, size of string is not
mandatory. This extra location is to store the null character '\0'. Character arrays may be
initialized when they are declared.

String Handling Functions:

C programming language is rich in library functions, but to handle or operate some


functions in string, powerful string handling functions are used. All these function are linked
with the "string.h" header file. Five commonly used string handling functions are,

 strcat ( ):
It is used to concatenate or combine two different strings together.
Syntax:
strcat (string1, string2);
Example:
strcat (s1, s2);
 strcmp ( ):
It is used to compare two strings. It will check which string is alphabetically
equal with the other string.
Syntax:
strcmp (string1, string2);
Example:
strcmp (s1, s2);
 strcpy ( ):
It is used to copy one string into another string. Note that target or destination
field should be larger than the source field. In other words size of the string1 should
be larger to receive the contents of the string2.
Syntax:
strcpy (string1, string2);

34 | P a g e
Example:
strcpy (s1, s2);
 strlen ( ):
It is used to count the number of character in a string i.e. to find the length of
the string.
Syntax:
strlen(string);
Example:
strlen (s1);
 strrev ( ):
It is used to reverse a string.
Syntax:
strrev (string);
Example:
strrev (s1);

35 | P a g e
LAB : 06 TWO DIMENSION AND STRING OPERATIONS

AIM:

To construct a ‘C’ program to solve the following problems using Two dimensional
arrays and String operations.

a) Find the Transpose of a given matrix


b) Find the Vowels and Consonants from the given character

6a) Find the Transpose of a given matrix:

Algorithm:

Step 1  START
Step 2  Get the value of R and C from the user to form a matrix
Step 3  Assign I = 0 and check the condition I is less than R, continue to step 4,
Otherwise step 5
Step 4  Assign J = 0 and check the condition J is less than C, continue to step 5,
Otherwise step 3
Step 5  Get the array elements A [I] [J] from the user, continue to step 6
Step 6  Check for the condition I is less than R, continue to step 7, otherwise step 9
Step 7  Check for the condition J is less than C, continue to step 8, otherwise step 6
Step 8  Compute Transpose by T [J] [I] = A [I] [J] continue to step 9
Step 9  Print “T [I] [J]” to the user
Step 10  STOP

36 | P a g e
Flowchart:

START

Input R, C

For (I = 0; I < R; I++)

For (J = 0; J < C; J++)

Input A [I] [J]

For (I = 0; I < R; I++)

For (J = 0; J < C; J++)

T [J] [I] = A [I] [J]

Print T [I] [J]

STOP

6b) Find the Vowels and Consonants from the given character:

Algorithm:

Step 1  START
Step 2  Declare a variable ‘ch’ of character data type
Step 3  Read character given by the user and store it in a variable "ch"
Step 4  Compare "ch" with the vowels in both upper and lower case
Step 5  If matches with vowels, display vowel found
Step 6  Not matches with vowels display consonant found
Step 7  STOP

37 | P a g e
Flowchart:

START

Assign V = 0, C = 0

Input S

Evaluate length L using S

For (I = 0; I <L; I++)


T

if(S=='a'||S=='A'||S=='e'||S=='E'||
S=='i'||S=='I'||S=='o'||S=='O'||S=='u F
'|| S=='U')

V=V+1

if(S >='a' && S


<=’z’||S>='A' && S<='Z')

C=C+1

Print V, C

STOP

RESULT:

Thus the following problems,

a) Find the Transpose of a given matrix


b) Find the Vowels and Consonants from the given character
Using Two dimensional arrays and String was implemented, executed and verified.

38 | P a g e
TUTORIAL : 07 FUNCTIONS AND CALL BY VALUE

FUNCTIONS:

It is a group of statements that together perform a task. Every C program has at least
one function, which is main ( ), and complex programs can define additional functions.
Logically divide the entire program into separate functions, such that each function performs
a specific task.

There are 3 aspects in each function. They are,

 Function declaration (or) prototype:


It tells the compiler about a function's name, return type, and parameters. The
actual body of the function can be defined separately. Declaration function must be
terminated with semicolon (;).
Syntax:

return_type function_name (parameter);

Example:

int max (int num1, int num2);

 Function call:
It calls the actual function. When calling actual function, the control goes to
corresponding function definition and entire code (or) statements get executed.
To call any function, just write the function name and if any parameter is
required then pass parameter to function
Syntax:

function_name ( ); (Or) variable = function_name (parameter);

Example:

max ( ); (Or) ret = max (a, b);

 Function definition:
It contains all the statements to be executed with function header and a
function body.

39 | P a g e
The parts of function definitions are,
 Return type: A function may return a value or nothing. The
return_type is the data type of the value the function returns. Return
type parameters and return statement are optional
 Function name: It is the name of function decided by programmer
and it is mandatory to give the name for the function
 Parameters: It is a value passed to a function at the time of calling of
function. It acts like a placeholder and optional one
 Function body: It is the collection of statements (or) actual operation
(or) logic.

Syntax:

return_type function_name (parameters)


{
function body;
}

Example:

int max(int num1, int num2)


{
if (num1 > num2)
result = num1;
return result;
}

Types of functions:

1. Predefined standard library functions:


These are the built in functions to handle tasks such as mathematical
computations, I/O processing, string handling. These functions are already defined in
the header file, so whenever there is a need, add by including the specified header file
to use within the program
2. User Defined functions:
The functions created by the user to do some specific task

40 | P a g e
CALL BY VALUE:

It is the default way of calling a function. There are two types of parameters,

 Actual parameters: The parameters that appear in function calls


 Formal parameters: The parameters that appear in function declarations

While calling a function, actual parameters get passed to the function. In this, the values
of actual parameters are copied to the formal parameters. The operations performed on the
formal parameters don’t reflect in the actual parameters.

CALL BY REFERENCE:

While calling a function, actual parameters get passed to the function. In this the
operation performed on formal parameters, affects the value of actual parameters because all
the operations performed on the value stored in the address of actual parameters.

41 | P a g e
LAB : 07 PROBLEMS ON FUNCTIONS

AIM:

To construct a ‘C’ program to swap two numbers using Call by value and Call by
reference.

Algorithm:

Step 1  START
Step 2  Declare and define the function swap ( )
Step 3  Get the values for A and B from the user
Step 4  Print the values of A and B before swapping, to the user
Step 5  Call the function swap ( ), go to step 6
Step 6  Assign T = A, A = B, B = T, go to step 6 and continue to step 7
Step 7  Print the values of A and B after swapping to the user
Step 8  STOP

Flowchart:
START

Declare swap ( )

Input A, B

Print Before swap A,


B
Assign
Call swap ( ) T = A, A = B, B = T

Print After swap A, B

STOP
RESULT:

Thus the swapping of two numbers using Call by value and Call by reference was
implemented, executed and verified.

42 | P a g e
NUMERICAL METHODS
TUTORIAL : (ROOT FINDING, NUMERICAL DIFFERENTIATION
08 & 09
AND NUMERICAL INTEGRATION)

NUMERICAL METHODS:

 Numerical analysis is the study of algorithms that uses a numerical approximation to


solve complex mathematical and scientific problems
 Numerical methods can only deliver approximate solutions to problems over a
defined interval such as time or distance

ROOT FINDING:

 It is a process of finding roots of continuous functions


 A root of a function f, from the real numbers to real numbers (or) from the complex
numbers to the complex numbers, is a number x such that f (x) = 0
 The roots of a function cannot be computed exactly. So root finding algorithms
provide approximations to roots, expressed either as floating point numbers or as
small isolating intervals, or disks for complex roots

Secant Method:

It uses a succession of the roots of secant lines to find a better approximation of root.
The algorithm is a root bracketing method and is the most efficient method of finding the root
of a function. It requires two initial guesses which are the start and end interval points.

Secant Formula:

𝒙𝒏 − 𝟏 − 𝒙𝒏 − 𝟐 (𝒙𝒏 − 𝟐 ) 𝒇 (𝒙𝒏 − 𝟏 ) − (𝒙𝒏 − 𝟏 ) 𝒇 (𝒙𝒏 − 𝟐 )


𝒙𝒏 = 𝒙𝒏 − 𝟏 − 𝒇(𝒙𝒏−𝟏 ) =
𝒇 (𝒙𝒏 − 𝟏 ) − 𝒇 (𝒙𝒏 − 𝟐 ) 𝒇 (𝒙𝒏 − 𝟏 ) − 𝒇 (𝒙𝒏 − 𝟐 )

NUMERICAL DIFFERENTIATION:

 It is the process of computing the value of the derivative of a function, whose


analytical expression is not available, but it is specified through a set of values at
certain tabular points X0, X1 …. Xn

43 | P a g e
 In such cases, first determine an interpolating polynomial approximating the function
and then differentiate the polynomial to approximately compute the value of the
derivative at the given point

Euler’s Method:

It is a first order numerical method used to solve differential equations. It is also


popularly known as Forward Euler’s method. It is a very basic method for numerical
integration of ordinary differential equations and simple to implement, but it does not provide
accurate results under some circumstances.

Euler’s Formula:

The solution for Euler’s numerical method is generated by iterating on the two formulas:

𝒙𝒏 − 𝟏 = 𝒙𝒏 + 𝒉

𝒚𝒏 + 𝟏 = 𝒚𝒏 + 𝒉 ∗ 𝒇 (𝒙𝒏 + 𝒚𝒏 )

Where h = length of subdivisions

NUMERICAL INTEGRATION:

 It is the process of computing the value of a definite integral,


𝒃
∫𝒂 𝒇(𝒙) 𝒅𝒙 when the values of the integrand function, y = f(x) is given at some
tabular points
 The integrand is first replaced with an interpolating polynomial, and then the
integrating polynomial is integrated to compute the value of the definite integral. This
gives us 'Quadrature formula' for numerical integration.
 For equidistant tabular points, X0, X1 …. Xn either the Newton's formula or Sterling’s
formulas are used. Otherwise, Lagrange's formula for the interpolating polynomial is
used.

Simpson Rule:

𝒙𝟐 𝒉
∫𝒙𝟎 𝒇(𝒙) 𝒅𝒙 ≈ [𝟑] ∗ 𝒇𝟎 + 𝟒 ∗ 𝒇𝟏 + 𝒇𝟐

44 | P a g e
LAB : 08 & 09 PROBLEMS ON NUMERICAL METHODS

AIM:

To construct a ‘C’ program to solve the following problems using Numerical


methods.

a) Find the Numerical differentiation of a given equation using Euler’s method


b) Find the Roots of a given equation using Secant method

8a) Find the Numerical differentiation of a given equation using Euler’s method:

Algorithm:

Step 1  START
Step 2  Declare and define the function diff ( )
Step 3  Get the values x0, y0, h and xn from the user
Step 4  The values of n is calculated as n = (xn - x0)/ h + 1
Step 5  Call the function diff ( )
Step 6  Check for x < xn, if it satisfies assign x0 = x and y0 = y
Step 7  Not satisfies then end the loop and function
Step 8  STOP

45 | P a g e
Flowchart:

8b) Find the Roots of a given equation using Secant method:

Algorithm:

Step 1  START
Step 2  Get the values x0, x1 and e from the user
Step 3  Compute f (a) and f (b)
Step 4  Compute f (c) = [a * f (b) - b * f (a)] / [f (b) - f (a)]
Step 5  For accuracy of x2, check if [(c - b) / c] > e, if satisfies go to step 6
Step 6  Assign a = b and b = c
Step 7  Not satisfies display the required root as c
Step 8  STOP

46 | P a g e
Flowchart:

RESULT:

Thus the following problems,

a) Find the Numerical differentiation of a given equation using Euler’s method


b) Find the Roots of a given equation using Secant method

Using Numerical methods was implemented, executed and verified.

47 | P a g e
RECURSION AND STRUCTURE OF RECURSIVE
TUTORIAL : 10
CALLS

RECURSION:

The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function. This is very useful to solve the
problems like calculating the Factorial of a number, generating Fibonacci series and resolve
Tower of Hanoi.

STRUCTURE OF RECURSIVE CALLS:

Syntax:

void recursion ( )
{
recursion ( ); /* function calls itself */
}
int main ( )
{
recursion ( );
}

Example:

int fact (int i)


{
return i * factorial (i - 1);
}
int main ( )
{
factorial (i);
}

48 | P a g e
LAB : 10 RECURSIVE FUNCTIONS

AIM:

To construct a ‘C’ program to solve the following problems using Recursive


functions.

a) Find the Factorial of a given number


b) Find the Sum of digits of a given number

10a) Find the Factorial of a given number

Algorithm:

Step 1  START
Step 2  Declare the variable N, F and Fact
Step 3  Get the value N from the user
Step 4  If the value N is greater than 0 go to step 5
Step 5  Declare and initialize fact as1
Step 6  Compare the value of N to 1, if equal go to step 9
Step 7  Not equals then multiply Fact with N and increment the value of N
Step 8  Multiply the values until it satisfies step 6
Step 9  Display the value F
Step 10  STOP

49 | P a g e
Flowchart:

10b) Find the Sum of digits of a given number:

Algorithm:

Step 1  START
Step 2  Declare sum, rem and initialize sum as 0
Step 3  Get the value N from the user
Step 4  While the value N is equal to 0 go to step 8
Step 5  Not equals then go to step 6
Step 6  Calculate rem = N % 10, sum = sum + rem and N = N / 10
Step 7  Repeat the calculations till it satisfies step 4
Step 8  Display the value sum
Step 9  STOP

50 | P a g e
Flowchart:

RESULT:

Thus the following problems,

a) Find the Factorial of a given number


b) Find the Sum of digits of a given number

Using Recursive functions was implemented, executed and verified.

51 | P a g e
POINTERS, STRUCTURES AND DYNAMIC
TUTORIAL : 11
MEMORY ALLOCATION

POINTERS:

It is a variable that stores or points to the address of another variable. The main
purpose is to allocate the memory dynamically i.e. at run time. Every variable has a memory
location and every memory location has its address defined which can be accessed using
Address of operator (&), which denotes an address in memory. Dereference operator (*)
gives the value from the address.

Syntax for declaration:

data_type *var_name;

Example for declaration:

int *p;

STRUCTURES:

It is a collection of different data types which are grouped together and each element
in a structure is called member. If you want to access structure members, structure variable
should be declared. Many structure variables can be declared for same structure and memory
will be allocated for each separately. Keyword “struct” is used for creating a structure.

Syntax for declaration:

struct structure_name
{
data_type member1;
.
data_type member n;
} structure_variable;

52 | P a g e
Example for declaration:

struct employee
{
int id;
char name[20];
float salary;
} e1, e2;

DYNAMIC MEMORY ALLOCATION:

The process of allocating memory during program execution is called dynamic


memory allocation. There are 4 dynamic memory allocation functions. They are,

 Memory allocation:
The function used here is malloc ( ). It is used to allocate space in memory during the
execution of the program.
Syntax - malloc (number *sizeof (int));
Example - malloc (20 * sizeof (int);
 Continuous allocation:
The function used here is calloc ( ). It initializes the allocated memory to zero.
Syntax - calloc (number, sizeof (int));
Example - calloc (20, sizeof (int);
 Reallocation:
The function used here is realloc ( ). It modifies the allocated memory size by
malloc ( ) and calloc ( ) functions to new size.
Syntax - realloc (pointer_name, number * sizeof (int));
Example - realloc (ptr, 100 * sizeof (int));
 Free:
The function used here is free ( ). It frees the allocated memory by malloc ( ), calloc (
), realloc ( ) functions and returns the memory to the system.
Syntax - free (pointer_name);
Example - free (ptr);

53 | P a g e
LAB : 11 POINTERS AND STRUCTURES

AIM:

To construct a ‘C’ program to solve the following problems using Pointers and
Structures.

a) Display Student information using Structures


b) Convert the given String to Lower case using Pointers

11a) Display Student information using Structures:

Algorithm:

Step 1  START
Step 2  Declare the variable N, I, J, rollnum, name, class, m1 to m6, s and total
Step 3  Get the values for N from the user
Step 4  Initialize the value I to 0
Step 5  If I is lesser than N then go to step 6 otherwise go to step 8
Step 6  Get the values for rollnum, name, class, m1 to m6 from the user
Step 7  Calculate total by adding m1 to m6 and increment I to I+1
Step 8  Initialize the value J to 0
Step 9  If J is lesser than N then go to step 10 otherwise go to step 12
Step 10  Display the values to the user
Step 11  Increment J to J+1
Step 12  STOP

54 | P a g e
Flowchart:

11b) Convert the given String to Lower case using Pointers:

Algorithm:

Step 1  START
Step 2  Declare string variable S and pointer variable C
Step 3  Get the values for the string variable from the user
Step 4  Assign the string variable to the pointer variable
Step 5  While the pointer variable C is not equal to null then go to step 7
Step 6  If equals go to step 8
Step 7  Check character by character from the inputted string by using logical AND
Step 8  Display the converted string to the user
Step 9  STOP

55 | P a g e
Flowchart:

RESULT:

Thus the following problems,

a) Display Student information using Structures


b) Convert the given String to Lower case using Pointers

Using Pointers and Structures was implemented, executed and verified.

56 | P a g e
TUTORIAL : 12 FILE HANDLING

FILE HANDLING:

File is a collection of bytes that is stored on secondary storage devices like disk. There
are two kinds of files in a system. They are,

 Text files (ASCII):


Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary files:
Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled
version of text files.

File Operations:

There are 4 basic operations that can be performed on any files. They are,

 Opening / Creating a file:


fopen ( ) function is used to open a file to perform operations such as reading,
writing. It creates a new file if the mentioned file name does not exist.

Syntax for Opening / Creating:

FILE *fopen (const char *filename, const char *mode)

Example for Opening / Creating:

FILE *fp;
fp = fopen (“C:\file.txt”, “w”);

 Closing a file:
fclose() function closes the file that is being pointed by file pointer fp.

Syntax for Closing:

int fclose(FILE *fp);

Example for Closing:

fclose (fp);

57 | P a g e
 Reading a file:
fgets() function is used to read a file line by line.

Syntax for Reading:

char *fgets(char *string, int n, FILE *fp)

Example for Reading:

char text[300];
fgets(text,200,fp)

 Writing in a file:
fprintf() function writes string into a file pointed by fp.

Syntax for Writing:

int fputs( const char *s, FILE *fp );

Example for Writing:

FILE *fp;
fp = fopen (“C:\file.txt”, “w”);
fputs("Programming n C",fp);

File Modes:

There are many modes in opening a file. Based on the mode of file, it can be opened
for reading or writing or appending the texts. They are,

 r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist
 w – Opens a file in write mode. It returns null if file could not be opened. If file exists,
data are overwritten
 a – Opens a file in append mode. It returns null if file couldn’t be opened

58 | P a g e
LAB : 12 FILE OPERATIONS

AIM:

To construct a ‘C’ program to Copy the contents of one file to another file using File
operations.

Algorithm:

Step 1  START
Step 2  Get source file fname1 and destination file fname2 from the user
Step 3  Open fname1 in Read mode and fname2 in Write mode
Step 4  If the file fname1 and fname2 equal to null, continue to step 5, go to step 6
Step 5  Print unable to open to the user, go to step 9
Step 6  If the character not equal to end of file, continue to step 7, go to step 8
Step 7  Read a character from source file and write to destination file
Step 8  Close source and destination file
Step 9  Print File copied successfully to the user
Step 10  STOP

59 | P a g e
Flowchart:

START

Get Source file fname1

Get Desti file fname2

Fs = fopen (fname1, “r”)


Ft = fopen (fname2, “w”)

F
If fs==NULL ||
ft = NULL

T F
If ch !=
EOF T
Print Unable to open
T

Ch = fgetc (Fs);
Fputc (ch, Ft);

fcloseall ( )

Print File Copied


successfully

STOP

RESULT:

Thus the Copying the contents of one file to another file using File operations were
implemented, executed and verified.

60 | P a g e

You might also like