Sie sind auf Seite 1von 110

FACULTY OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

B.E. (COMPUTER SCIENCE AND ENGINEERING) - II SEMESTER

ETSP207 - COMPUTER PROGRAMMING LAB

NAME: ........................................................................................

REG NO: ........................................................................................


FACULTY OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ETSP207 - COMPUTER PROGRAMMING LAB

Certified that this is the Bonafide record of work done by


Mr/Miss.............................................................................................
Register Number ........................... of B.E. (Computer Science and
Engineering), II Semester in Computer Programming Lab during the year
2018-2019.

Annamalai Nagar Staff in-Charge


Date:

Internal Examiner External Examiner


CONTENTS

EXP. DATE NAME OF THE EXPERIMENT PAGE SIGNATURE


No. No

1. Tutorial 1: Problem solving using 1


computers:
Lab1: Familiarization with programming
environment
3

2. Tutorial 2: Variable types and type


conversions: 6
Lab 2: Simple computational problems
using arithmetic expressions
8
3. Tutorial 3: Branching and logical
expressions:
Lab 3: Problems involving if-then-else 10
structures

12
Tutorial 4: Loops, while and for loops:
4.
Lab 4: Iterative problems e.g., sum of
series 18

Tutorial 5: 1D Arrays: searching, sorting:


5. Lab 5: 1D Array manipulation 20

Tutorial 6: 2D arrays and Strings 23


6.
Lab 6: Matrix problems, String operations

Tutorial 7: Functions, call by value:


7. Lab 7: Simple functions 25

Tutorial 8: Numerical methods (Root 27


8.
finding, numerical differentiation,
numerical integration)
Lab 8: Programming for solving 33
Numerical methods problems
EXP. DATE NAME OF THE EXPERIMENT PAGE SIGNATURE
No. No
9. Tutorial 9: Numerical methods (Numerical
differentiation, numerical integration):
Lab 9: Programming for solving Numerical
methods problems

10. Tutorial 10: Recursion, structure of


recursive calls
Lab 10: Recursive functions

Tutorial 11: Pointers, structures and


11. dynamic memory allocation
Lab 11: Pointers and structures

Tutorial 12: File handling:


12. Lab 12: File operations
1. Problem Solving using Computers

Problem Solving using Computers


Computers can do amazing things, from basic laptops capable of simple word processing
and spreadsheet functions to incredibly complex supercomputers completing millions of
financial transactions a day and controlling the infrastructure that makes modern life possible.
But no computer can do anything until designed to behave in specific ways. That's what
computer programming is.
Programming is a creative process that instructs a computer on how to do a task.
Computers do what they are told, and their instructions come in the form of programs written by
humans. Many knowledgeable computer programmers write source code that can be read by
humans but not by computers. In many cases, that source code is compiled to translate the source
code into machine code, which can be read by computers but not by humans.
Problem Solving
A computer cannot solve a problem on its own. One has to provide step by step solutions
of the problem to the computer. In fact, the task of problem solving is not that of the computer.
It is the programmer who has to write down the solution to the problem in terms of simple
operations which the computer can understand and execute. In order to solve a problem by the
computer, one has to pass though certain stages or steps. They are
1. Understanding the problem: Understand the objective of the problem.
2. Analyse the problem: Analyse the inputs required and the expected output of the problem.
3. Search the problem solving methods: There may exist more than one solution technique
for any problem. Here, search for all the problem solving methods for solving the problem.
And choose the best solution technique.
4. Coding and implementation: The last stage of the problem solving is the conversion of the
detailed sequence of operations in to a language that the computer can understand.
Algorithm
A set of sequential steps usually written in ordinary language to solve a given problem is
called Algorithm. Algorithm is a complete, unambiguous, finite number of logical steps for
solving a specific problem.
Steps in Algorithm Development
It may be possible to solve to problem in more than one ways, resulting in more than one
algorithm. The choice of various algorithms depends on the factors like reliability, accuracy and
easy to modify. The most important factor in the choice of algorithm is the time requirement to

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

1
execute it, after writing code in High-level language with the help of a computer. The algorithm
which will need the least time when executed is considered the best.
1. Identification of input: For an algorithm, there are quantities to be supplied called input and
these are fed externally. The input is to be indentified first for any specified problem.
2. Identification of output: From an algorithm, at least one quantity is produced, called for any
specified problem.
3. Identification of the processing operations: All the calculations to be performed in order to
lead to output from the input are to be identified in an orderly manner.
4. Processing Definiteness: The instructions composing the algorithm must be clear and there
should not be any ambiguity in them.
Algorithm Examples
1. Write an algorithm to calculate the simple interest using the formula. Simple interest =
P*N* R/100 where P is principle Amount, N is the number of years and R is the rate of
interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2 : Calculate simple interest as Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.
2. Write an algorithm to find the area of the square
Step 1: Read the side of the square a.
Step 2: Area = a*a
Step 3: Output the Area
Step 4: Stop.
3.Write an algorithm to find the largest of three numbers A, B, C
Step 1: Read the numbers A,B,C
Step 2: BIG = 0
Step 3: if (A>BIG)
BIG = A
Step 4 : if (B>BIG)
BIG = B
Step 5: if(C>BIG)
BIG = C
Step 6: Print BIG
Step 6: Stop.
5. Write an algorithm to test whether a given integer value is prime or not.
Step 1: Start
Step 2: Declare variables n,i,flag.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

2
Step 3: Initialize variables
flag←1
i←2
Step 4: Read n from user.
Step 5: Repeat the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop
6. Write an algorithm to find the factorial of a number.
Step 1: Start
Step 2: Declare variables n, fact, i.
Step 3: Initialize variables
fact←1
i←1
Step 4: Read value of n
Step 5: if i<=n
5.1: fact←fact*i
5.2: i←i+1
Step 6: Display factorial
Step 7: Stop
Flow Chart
A flow chart is a step by step diagrammatic representation of the logic paths to solve a
given problem. The flowcharts are pictorial representation of the methods to be used to solve a
problem and plan its solution in a systematic and orderly manner. A flowchart when translated
in to a proper computer language, results in a complete program.
Differences between Algorithm and Flowchart

Algorithm Flowchart
A method of representing the step-by-step Flowchart is diagrammatic representation of
logical procedure for solving a problem an algorithm. It is constructed using different
types of boxes and symbols.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

3
It contains step-by-step English descriptions, The flowchart employs a series of blocks
each step representing a particular operation and arrows, each of which represents a
leading to solution of problem particular step in an algorithm

These are particularly useful for small These are useful for detailed representations
problems of complicated programs
For complex programs, algorithms prove to be For complex programs, Flowcharts prove to
Inadequate be adequate

Symbols used in Flowcharts


Start/Stop: Rectangle with rounded sides is used to indicate either START/ STOP of the
program.

Input and output indicators: Parallelograms are used to represent input and output
operations. Statements like INPUT, READ and PRINT are represented in these Parallelograms.

Process Indicators: Rectangle is used to indicate any set of processing operation such as for
storing arithmetic operations.

Decision Makers: The diamond is used for indicating the step of decision making and
therefore known as decision box. Decision boxes are used to test the conditions or ask
questions and depending upon the answers, the appropriate actions are taken by the computer.
The decision box symbol is

Flow Lines: Flow lines indicate the direction being followed in the flowchart. In a
Flowchart, every line must have an arrow on it to indicate the direction. The arrows
maybe in any direction.

On- Page connectors: Circles are used to join the different parts of a flowchart and these
circles are called on-page connectors. A circle connects sections on the same page in a
complicated flowchart to give a neat shape to the flowchart.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

4
Off-page connectors: This connector represents a break in the path of flowchart which is too large
to fit on a single page. It is similar to on-page connector. The connector symbol marks where the
algorithm ends on the first page and where it continues on the second.

Flowchart Examples:
1. Draw a flowchart to calculate the simple interest using the formula. Simple interest = P*N*
R/100 where P is principle Amount, N is the number of years and R is the rate of interest.

2. Draw a flowchart to find the area of the square

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

5
3. Draw a flowchart to find the largest of three numbers X, Y,Z.

5. Draw a flowchart to test whether a given integer value is prime or not.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

6
6. Draw a flowchart to find the factorial of a number.

Familiarization with Programming Environment

To set up local programming the environment for C programming language, following


two software tools are required on the computer (a) Text Editor and (b) The C Compiler.
Text Editor
Text editor is used to type the program. Examples of few editors include Windows
Notepad, OS Edit command, vim or vi. The name and version of text editors can vary on
different operating systems. For example, Notepad will be used on Windows, and vim or vi can be
used on windows as well as on Linux or UNIX.
The files created with the editor are called the source files and they contain the program
source codes. The source files for C programs are typically named with the extension ".c". Before
starting the programming, make sure the availability of one text editor in place and enough
experience to write a computer program, save it in a file, compile it and finally execute it.
The C Compiler
The source code written in source file is the human readable source for the program. It
needs to be "compiled", into machine language so that the CPU can actually execute the program
as per the instructions given. The compiler compiles the source codes into final executable
programs. How to compile C code? How to make executable programs from C source code files?
Consider the example C program.
#include<stdio.h>
main()
{ /* My first C Program */
printf(“Hello World! \n”);
}

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

7
The compilation of the C program can be explained with the flow diagram as shown below.

Let us examine each component of the flow diagram in more detail.

• The input of the C compilation process is C source code file and its result is an
executable file. The output of the previous component is the input of the next component.
• The preprocessor uses the source code as input. The preprocessor is in charge of
removing all the comments and interpreting preprocessor directives indicated by the
hash # sign. For example in the hello world program, the #include directive is used to
include code of the corresponding file e.g., standard I/O file, stdio.h. The preprocessor
will include the source code in the stdio.h file in the main program before transferring it
to the compiler.
• After preprocessor processing the source, it transfers the result to the C compiler. The C
compiler is responsible for translating from plain source code into assembly code.
• The assembler is in charge of creating object code. On Windows systems the object code
files have .obj extension.
• If in the source code file, you use functions from a library, the linker will combine these
functions with the main() function to make an executable file of the program.

Compile and Execute C Program


Following are the simple steps to compile and execute a C program
• Open a text editor and add the above-mentioned code.
• Save the file as hello.c
• Now compile and execute to see the output of your C program.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

8
C Program Structure
A C program basically consists of the following parts
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Look at a simple code that would print the words "Hello World".

include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Look at the various parts of the above program
• The first line of the program #include <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
This Hello World program will help to understand various basic concepts related to C
programming.
Program Entry Point
C - Header Files is the entry point in a C program. A header file is a file with extension
.h which contains C function declarations and macro definitions to be shared between several
source files. #include <stdio.h> statement: keep a note that this statement is at the top of a C
program.
Every C program starts with main(), which is called the main function, and then it is
followed by a left curly brace. The rest of the program instruction is written in between and
finally a right curly brace ends the program. The coding part inside these two curly braces is
called the program body. The left curly brace can be in the same line as main(){ or in the next
line like it has been mentioned in the above program.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

9
Functions
Functions are small units of programs and they are used to carry out a specific task. For
example, the above program makes use of two functions: main() and printf(). Here, the function
main() provides the entry point for the program execution and the other function printf() is
being used to print an information on the computer screen. User can define their own functions
but C programming itself provides various built-in functions like main(), printf(), etc., which
can be used in programs based on the requirement. Some of the programming languages use
the word sub-routine instead of function, but their functionality is more or less the same.
Comments
C program can have statements enclosed inside /*.....*/. Such statements are called
comments and these comments are used to make the programs user friendly and easy to
understand. The good thing about comments is that they are completely ignored by compilers
and interpreters.

Whitespaces

When writing a program using any programming language, various printable characters
are used to prepare programming statements. These printable characters are

a, b, c,......z,
A, B, C,.....Z,
1, 2, 3,...... 0,
!, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '.

Apart from these characters, there are some characters which are used very frequently
but they are invisible in the program and these characters are spaces, tabs (\t), new lines (\n).
These characters are called whitespaces. These three important whitespace characters are
common in all the programming languages and they remain invisible in the text document.

Explanation White Space Representation


To create a new line \n
To create a tab \t
To create space Empty space

A line containing only whitespace, possibly with a comment, is known as a blank line,
and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs,
newline characters, and comments. Here all the created spaces around "Hello, World!" are
useless and the compiler will ignore them at the time of compilation.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

10
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
which produces the following result
Hello, World!

Semicolons
Every individual statement in a C Program must be ended with a semicolon (;), for
example, to write "Hello, World!" twice in different lines, then it will be written as follows
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World! \n" );
printf( "Hello, World!" );
}
This program will produce the following result
Hello, World!
Hello, World!

Here, a new line character \n is used in the first printf() function to create a new line. If this new
line is not used as in the following program,
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}
This program will produce the following result
Hello, World!Hello, World!

Syntax Error
If the rules defined by the programming language are not followed, then at the time of
compilation, the program will show syntax errors and the program will not be compiled. From
syntax point of view, even a single dot or comma or a single semicolon should be taken care of.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

11
Data types
A very simple but very important concept in almost all the programming languages is
called data types. As its name indicates, a data type represents a type of the data which can be
processed using a computer program. It can be numeric, alphanumeric, decimal, etc. Consider
an easy example of adding two whole numbers 10 & 20, which can be done simply as follows.
10 + 20
Consider another problem of adding two decimal numbers 10.50 & 20.50, which will be written
as follows.
10.50 + 20.50
The two examples are straightforward. Now consider another example of recording student
information in a notebook as shown below.
Name: Sara
Class: 6th
Section: J
Age: 13
Sex: F
The first example dealt with whole numbers, the second example added two decimal
numbers, whereas the third example is dealing with a mix of different data. Now, put it as
follows.
• Student name "Sara" is a sequence of characters which is also called a string.
• Student class "6th" has been represented by a mix of whole number and a string of two
characters. Such a mix is called alphanumeric.
• Student section has been represented by a single character which is 'J'.
• Student age has been represented by a whole number which is 13.
• Student sex has been represented by a single character which is 'F'.
This way, it is understood that in day-to-day life, different types of data such as strings,
characters, whole numbers (integers), and decimal numbers (floating point numbers) are being
dealt with.
Similarly, while writing a computer program to process different types of data, its type has
to be clearly specified. Otherwise the computer does not understand how different operations
can be performed on that given data. Different programming languages use different keywords
to specify different data types. C programming language uses int to specify integer data,
whereas char specifies a character data type.
C Data Types
Type Keyword Value range which can be represented by this data
type
Character char -128 to 127 or 0 to 255
Number int -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
Small Number short -32,768 to 32,767

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

12
Long Number long -2,147,483,648 to 2,147,483,647
Decimal Number float 3.4E-38 to 3.4E+38
Double Precision double 1.7E-308 to 1.7#+308
Greater Precision long double 3.4E-4932 to 1.1E+4932

These data types are called primitive data types and these data types can be used to build more
complex data types, which are called user-defined data type, for example a string will be a
sequence of characters.
Variables
Creating variables is also called declaring variables in C programming. Different
programming languages have different ways of creating variables inside a program. For example,
C programming has the following simple way of creating variables.

#include <stdio.h>
int main() {
int a;
int b;
}

The above program creates two variables to reserve two memory locations with names a
and b. These variables are created using int keyword to specify variable data type which means
integer values are stored in these two variables. Similarly, variables can be created to store long,
float, char or any other data type. For example :
/* variable to store long value */
long a;

/* variable to store float value */


float b;
A variable name can hold a single type of value. For example, if variable a has been defined as
int type, then it can store only integer. Listed below are the key points about variables.
• C programming language requires a variable creation, i.e., declaration before its usage in
the program. A variable name cannot be used in the program without creating it.
• A variable name can be declared only once inside the program. For example, if a variable
a has been defined to store an integer value, then you cannot define a again to store any
other type of value.
• Any name can be given to a variable like age, sex, salary, year1990 or anything else.
• C does not allow starting their variable names with a digit, so 1990year will not be a valid
variable name whereas year1990 or ye1990ar are valid variable names.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

13
Store Values in Variables
The program given here has two additional statements where the user is storing 10 in variable a and
20 is being stored in variable b. Almost all the programming languages have similar way of storing
values.
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20; }

variables. Keep variable name in the left hand side of an equal sign ‘=’ and whatever value to be
stored in the variable, keep that value in the right hand side. In other words, when above program is
executed, the memory location named a will hold 10 and memory location b will hold 20.
Accessing stored values in variables
Without using the stored values in the variables, then there is no point in creating variables and
storing values in them. The above program has two variables a and b and they store the values 10
and 20, respectively. Following C program, prints the values stored in its variables.
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
printf( "Value of a = %d\n", a );
printf( "Value of b = %d\n", b );
}

When the above program is executed, it produces the following result


Value of a = 10
Value of b = 20
Similarly, different data types can be printed using different % and characters as seen in the
following table.
%d Print integer value
%f Print floating point value
%c Print character value

Characters
If it was easy to work with numbers in computer programming, it would be even easier to
work with characters. Characters are simple alphabets like a, b, c, d...., A, B, C, D,....., but with an

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

14
exception. In computer programming, any single digit number like 0, 1, 2,....and special characters
like $, %, +, -.... etc., are also treated as characters and to assign them in a character type variable,
put them inside single quotes. For example, the following statement defines a character type variable
ch and assign a value 'a' to it
char ch=’a’;
Here, ch is a variable of character type which can hold a character of the implementation's
character set and 'a' is called a character literal or a character constant. Not only a, b, c,.... but when
any number like 1, 2, 3.... or any special character like !, @, #, #, $,.... is kept inside single quotes,
then they will be treated as a character literal and can be assigned to a variable of character type, so
the following is a valid statement
char ch = ‘1’;
A character data type consumes 8 bits of memory which means it can store anything in a
character whose ASCII value lies in between -127 to 127, so it can hold any of the 256 different
values. A character data type can store any of the characters available on the keyboard including
special characters like !, @, #, #, $, %, ^, &, *, (, ), _, +, {, }, etc.
Note that only a single alphabet or a single digit number can be kept inside single quotes and
more than one alphabets or digits are not allowed inside single quotes. So the following statements
are invalid in C programming.
char ch1 = 'ab';
char ch2 = '10';
Given below is a simple example, which shows how to define, assign, and print characters in
C Programming language.
#include <stdio.h>
int main() {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
printf( "ch1: %c\n", ch1);
printf( "ch2: %c\n", ch2);
printf( "ch3: %c\n", ch3);
printf( "ch4: %c\n", ch4);
}

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

15
Here, %c is used to print a character data type. When the above program is executed, it produces the
following result.
ch1: a
ch2: 1
ch3: $
ch4: +
Keywords

Like int, long, and float, there are many other keywords supported by C programming
language which will be used for different purpose. Different programming languages provide
different set of reserved keywords, but there is one important and common rule in all the
programming languages that reserved keyword cannot be used to name our variables, which means
that variable cannot be named as int or float rather these keywords can only be used to specify a
variable data type. For example, while trying to use any reserved keyword for the purpose of
variable name will flash a syntax error.

# #include <stdio.h>
int main() {
int float;
float = 10;
printf( "Value of float = %d\n", float);
}
}}
While compiling the above program, it produces the following error.

main.c: In function 'main':


multiple types in one declaration
int float;

If proper name is given to the variables, then the above program should compile and execute
successfully.
#include <stdio.h>
int main() {
int count;
count = 10;
printf( "Value of count = %d\n", count);
}

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

16
Reserved Keywords

Here is a table having almost all the keywords supported by C Programming language.

auto else long switch break enum register


break enum register typedef const for signed
do int struct double continue goto sizeof
default if static while typedef void volatile
Operators
An operator in a programming language is a symbol that tells the compiler or interpreter
to perform specific mathematical, relational or logical operation and produce final result.
Arithmetic Operators

Computer programs are widely used for mathematical calculations. A C program can be
written which can do simple calculation like adding two numbers (2 + 3) and which can solve a
complex equation like P(x) = x4 + 7x3 - 5x + 9. In the first expression 2 and 3 are operands and
+ is an operator. Similar concepts exist in Computer programming. Take a look at the following
statements
2+3
P(x) = x4 + 7x3 - 5x + 9.
These two statements are called arithmetic expressions in a programming language and
+,- used in these expressions are called arithmetic operators and the values used in these
expressions like 2, 3 and x, etc., are called operands. In their simplest form, such expressions
produce numerical results.
Similarly, C programming language provides various arithmetic operators. The following
table lists down a few of the important arithmetic operators available in C programming
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
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% This gives remainder of an integer division B % A will give 0

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

17
Following is a simple example of C Programming to understand the above mathematical
operators.

#include <stdio.h>
int main() {
int a, b, c;
a = 10;
b = 20;
c = a + b;
printf( "Value of c = %d\n", c);
c = a - b;
printf( "Value of c = %d\n", c);
c = a * b;
printf( "Value of c = %d\n", c);
c = b / a;
printf( "Value of c = %d\n", c);
c = b % a;
printf( "Value of c = %d\n", c);
}

When the above program is executed, it produces the following result

Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0

Operator Precedence
Operator precedence determines which operator is performedfirst in an expression with
more than one operators with different precedence. For example 10 + 20 * 30 is calculated as 10
+ (20 * 30) and not as (10 + 20) * 30. Following table illustrates the precedence followed while
evaluating an arithmetic expression starting from the topmost precedence.

() parenthesis
*/% Multiplication/division/modulus
+- Addition/Subtraction
= Assignment

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

18
Relational Operators
C programming language provides various relational operators. The following table lists
down a few of the important relational operators available in C programming language. Assume
variable A holds 10 and variable B holds 20, then

Operator Description Example


Checks if the values of two operands are equal
== (A == B) is not true.
or not, if yes then condition becomes true.
Checks if the values of two operands are equal
!= or not, if values are not equal then condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater
> than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater
>= than or equal to the value of right operand, if (A >= B) is not true.
yes then condition becomes true.
Checks if the value of left operand is less than
<= or equal to the value of right operand, if yes (A <= B) is true.
then condition becomes true.

An example of C Programming which makes use of relational operators is shown below.


if statement is used to check a condition and if the condition is true, then the body of if statement
is executed, otherwise the body of if statement is skipped.

#include <stdio.h>
int main()
{
int a, b;
a = 10;
b = 20;
/* Here we check whether a is equal to 10 or not */
if( a == 10 ) {
/* if a is equal to 10 then this body will be executed */
printf( "a is equal to 10\n");
}

/* Here we check whether b is equal to 10 or not */


if( b == 10 ) {
/* if b is equal to 10 then this body will be executed */

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

19
printf( "b is equal to 10\n");
}

/* Here we check if a is less b than or not */


if( a < b ) {
/* if a is less than b then this body will be executed */
printf( "a is less than b\n");
}

/* Here we check whether a and b are not equal */


if( a != b ) {
/* if a is not equal to b then this body will be executed */
printf( "a is not equal to b\n");
}
}

Above program produces the following result.


a is equal to 10
a is less than b
a is not equal to b

Logical Operators
Logical operators are very important in any programming language and they help to take
decisions based on certain conditions. To combine the result of two conditions, then logical
AND and OR logical operators are used in producing the final result. The following table shows
all the logical operators supported by the C language. Assume variable A holds 1 and variable B
holds 0, then

Operator Description Example


Called Logical AND operator. If both the operands are
&& (A && B) is false.
non-zero, then condition becomes true.
Called Logical OR Operator. If any of the two operands
|| (A || B) is true.
is non-zero, then condition becomes true.
Called Logical NOT Operator. Use to reverses the
! logical state of its operand. If a condition is true then !(A && B) is true.
Logical NOT operator will make false.
Example:

#include <stdio.h>
int main() {
int a = 1;
int b = 0;
if ( a && b ) {

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

20
printf("This will never print because condition is false\n" );
}
if ( a || b ) {
printf("a||b This will be printed print because condition is true\n" );
}
if ( !(a && b) ) {
printf("a&&b This will be printed print because condition is
true\n" );
}
}
Above program produces the following result.

a||b This will be printed print because condition is true


a&&b This will be printed print because condition is true
Escape Sequences
Many programming languages support a concept called Escape Sequence. When a
character is preceded by a backslash (\), it is called an escape sequence and it has a special
meaning to the compiler. For example, \n in the following statement is a valid character and it is
called a new line character.
char ch = '\n';
The following table lists the escape sequences available in C programming language.

Escape Sequence Description


\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

21
The following example shows how the compiler interprets an escape sequence in a print
statement.
#include <stdio.h>
int main() {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = '\t';
ch2 = '\n';
printf( "Test for tabspace %c and a newline %c will start here", ch1, ch2);
}
The output of the above program will be:

Test for tabspace and a newline

will start here

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT, AU

22
2. Variable Types and Type Conversions

Type Conversion in C
Type casting is a way to convert a variable from one data type to another data type. For example,
if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. A
type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion (or) Automatic Type Conversion
• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
• All the data types of the variables are upgraded to the data type of the variable with
largest data type.
• It is possible for implicit conversions to lose information, signs can be lost (when signed
is implicitly converted to unsigned), and overflow can occur (when long long is
implicitly converted to float).

bool → char → short int → int →


unsigned int → long → unsigned →
long long → float → double → long double

Example of Type Implicit Conversion:

#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
Output:
x = 107, z = 108.000000

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

23
2. Explicit Typecasting:
In C language, Many conversions, especially those that imply a different interpretation of the
value, require an explicit conversion.
1 float f;
2 int a = 20, b = 3;
3 f = a/b
The value of f will be 6.000000 instead of 6.666666 because operation between two integers
yields an integer value. Sure one way to solve this problem is to use mixed mode arithmetic
and change the type of either a or b to double or float. Changing the type of variables is not
always feasible and is certainly not a good program design.

A cast operator is a unary operator used to temporarily convert constant, variable or expression
to a particular type. The syntax of cast operator is:
(datatype)expression
The data type desired, such as int, float are substituted for the word datatype.

So writing the above statement as:


f = (float)a/b;
Then the correct answer is 6.666666.

Here is how the cast operator works: First, it converts the variable a which of type int to type
float temporarily. It is already known that the operation between a float and int operand yields
a float result, that’s why answer comes out to be 6.666666 instead of 6.000000.

This process is also called type casting and it is user defined. Here the user can type cast the
result to make it of a particular data type.

#include<stdio.h>
int main()
{
int a = 25, b = 13;
float result;

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

24
result = a/b;
// display only 2 digits after decimal point
printf("(Without typecasting) 25/13 = %.2f\n", result );
result = (float)a/b;
// display only 2 digits after decimal point
printf("(With typecasting) 25/13 = %.2f\n", result );
// signal to operating system everything works fine
return 0;
}

Expected Output:
(Without typecasting) 25/13 = 1.00
(With typecasting) 25/13 = 1.92

Inbuilt Typecast Functions in C:


There are many inbuilt type casting functions available in C language which performs data type
conversion from one type to another.
S.No Typecast Description
Function
1 atof() Convert string to Float
2 atoi() Convert string to int
3 atol() Convert string to long
4 itoa() Convert int to string
5 ltoa() Convert long to string

Ex. No.2 Simple Computational Problems using Arithmetic Expressions

2(a) Arithmetic Operators

Aim: To write a C program to understand the Arithmetic Operators in C

Algorithm:
1. Start
2. Add the numbers and print the result
3. Multiply the numbers and print the result
4. Divide the numbers and print the result
5. Get the remainder and print the result
6. Increment a and print the result
7. Decrement a and print the result
8. End

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

25
Program:
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

Sample Input/Output
Value of c is 31
Value of c is 11
Value of c is 210
Value of c is 2
Value of c is 1
Value of c is 21
Value of c is 22

2(b) Simple Interest

Aim: Write a C program to calculate Simple Interest

Algorithm:
1. Start
2. Get the values of P,N,R
3. Calculate SI = PNR/100
4. Print SI
5. End

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

26
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int p,n,r,si;
clrscr();
printf("Enter Principle, Rate of interest & Time :");
scanf("%d%d%d",&p,&r,&n);
si=(p*r*n)/100;
printf("Simple Interest is :%d",si);
getch();
}
Sample Input/Output
Enter Principle, Rate of interest & Time: 1000
25
5
Simple Interest is : 1250

RESULT:
Thus the C program for finding simple interest has been successfully executed

2(c) Convert Temperature from Degree Centigrade to Fahrenheit


Aim: Write a C program to convert temperature from degree centigrade to Fahrenheit

Algorithm:
1. Start
2. Get the temperature in degree centigrade
3. Calculate Fahrenheit = 1.8*C+32
4. Print the temperature in Fahrenheit
5. End

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
float c,f;
clrscr();
printf("Enter the Temperature in Centigrade: ");

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

27
scanf("%f",&c);
f=(1.8*c)+32;
printf("Temperature in Fahrenheit is : %f",f);
getch(); }
Sample Input/Output
Enter the Temperature in Centigrade: 78
Temperature in Fahrenheit is : 172.399994

RESULT:
Thus the C program for converting temperature from centigrade to fahrenheit has been
successfully executed

2(d) Calculate Percentage of marks in 5 subjects

Aim: Write a C program to calculate percentage of marks in 5 subjects

Algorithm:
1. Start
2. Assign total as 500
3. Get the marks in 5 subjects
4. Add the marks in 5 subjects and get the sum.
5. Calculate percentage = sum * 100 / total
6. Print the percentage
7. End

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int s1,s2,s3,s4,s5,total=500,sum=0;
float per;
clrscr();
printf("Enter Marks of 5 Subjects: ");
scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5);
sum=s1+s2+s3+s4+s5;
printf("Sum of 5 Subjects is: %d\n",sum);
per=(sum*100)/total;
printf("Percentage is: %f",per);
getch();

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

28
}

Sample Input/Output
Enter Marks i=of 5 Subjects : 98
78
67
95
83
Sum of 5 subjects is 421
Percentage is: 84.000000

RESULT:
Thus the C program for calculating percentage of marks in 5 subjects has been successfully
executed

2(e) Calculate Area and Circumference of a Circle

Aim: Write a C program to find area and circumference of a circle


Algorithm:
1. Start
2. Read the value of radius of the circle
3. Calculate Area = π*r*r
4. Print the area of the circle
5. Calculate Circumference = 2*π*r
6. Print the circumference of the circle
7. End

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float pi=3.14,area,ci;
clrscr();
printf("Enter the Radius of a Circle:");
scanf("%d",&r);
area=pi*r*r;
printf("Area of a Circle is: %f\n",area);
ci=2*pi*r;
printf("Circumference is: %f",ci);
getch();

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

29
}

Sample Input/Output
Enter the Radius of a Circle:15
Area of a Circle: 706.500000
Circumference is: 94.200005

RESULT:
Thus the C program for calculating area and circumference of a circle has been successfully
executed

Dr. M. Kalaiselvi Geetha, Dept. of Computer Science and Engineering, FEAT,AU

30
3. BRANCHING AND LOGICAL EXPRESSIONS

An if statement consists of a Boolean expression followed by one or more statements.

Syntax
The syntax of an 'if' statement in C programming language is −

if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement
will be executed. If the Boolean expression evaluates to false, then the first set of code after
the end of the 'if' statement (after the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and if it is
either zero or null, then it is assumed as false value.

i) if...else statement

An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

Syntax
The syntax of an if...else statement in C programming language is −

if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise,
the else block will be executed.

C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

31
ii) nest if-else statements
It is always legal in C programming to nest if-else statements, which
means you can use one if or else if statement inside another if or else if
statement(s).

Syntax
The syntax for a nested if statement is as follows −

if( boolean_expression 1) {

/* Executes when the boolean expression 1 is true */


if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if
statements.

iii) switch statement


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

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

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

Ex. No. 3(a).

AIM:

To write a C program to compare two numbers using if statement

ALGORITHM:

1. Start
2. Input the value of x and y
3. if(x>y) then
4. Print x is greater than y
5. if (x<y) then
6. Print x is less than y
7. if (x==y) then

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

33
8. Print x is equal to y
9. End.

PROGRAM:

#include <stdio.h>
#include <conio.h>

void main()
{
int x, y;
printf("Enter the value of x:");
scanf("%d", &x);
printf("Enter the value of y:");
scanf("%d", &y);

if (x>y)
{
printf("x is greater than y\n");
}

if (x<y)
{
printf("x is less than y\n");
}

if (x==y)
{
printf("x is equal to y\n");
}
getch();
}
SAMPLE INPUT-OUTPUT:

Enter the value of x: 20


Enter the value of y: 10
x is greater than y

Enter the value of x: 10


Enter the value of y: 20
x is less than y

Enter the value of x: 10


Enter the value of y: 10
x is equal to y

RESULT:

Thus the C program for comparing two numbers has been successfully executed.

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

34
Ex. No. 3(b).

AIM:

To write a C program to find whether a number is odd or even using if else statement

ALGORITHM:

1. Start
2. Input number
3. Remainder number%2
4. if(Remainder=0) then print “Even Number”
5. else print “Odd Number”
6. end

PROGRAM:
#include<stdio.h>
#include<conio.h>

void main()
{
int n;
printf("Enter a n value");
scanf("%d",&n);
if(n%2==0)
printf("Number is even");
else
printf("Number is odd");
getch();
}

SAMPLE INPUT- OUTPUT:

Enter n value
5
Number is odd

RESULT

Thus the C program for finding odd or even number has been successfully executed

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

35
Ex. No. 3(c).

AIM:

To write a C program to calculate electricity bill using nested if else statement

Algorithm:

1. Start
2. Read unit consumed from user.
3. If unit < = 50 then amount = unit * 0.50.
4. If unit > 50 and unit <=100 then amount = 50*0.5 + (unit-50) * 0.75.
5. If unit > 100 and unit <=250 then amount = 50*0.5 + 100*0.75 + (unit-50) * 1.20.
6. If unit > 250 then amount = 50*0.5 + 100*0.75 + 100*1.20 + (unit-50) * 1.50.
7. Calculate the surcharge amount i.e. surcharge = amount * 0.20.
8. Calculate the net amount i.e. net_amount = amount + surcharge.
9. End.

PROGRAM:

/* C program to calculate electricity bill */


#include <stdio.h>
#include <conio.h>
void main()
{
int cust_sno,unit;
float amt,sur_charge,total_amt;
char cust_name[25];
clrscr();
printf("Enter the customer service no :\t");
scanf("%d",&cust_sno);
printf("\nEnter the customer Name :\t");
scanf("%s",cust_name);
printf("\nEnter the unit consumed by customer :\t");
scanf("%d",&unit);
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = (50*0.50)+((unit-50)*0.75);
}
else if(unit <= 250)
{
amt = (50*0.50)+(100*0.75)+((unit-150)*1.20);
}
else
{
amt = (50*0.50)+(100*0.75)+(100*1.20)+((unit-250)*1.50);

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

36
}

/* Calculate total electricity bill after adding surcharge */


sur_charge = amt*0.20;
total_amt = amt+sur_charge;
clrscr();
printf("\t\t\tElectricity Bill\n");
printf("\nCustomer Service No :%d",cust_sno);
printf("\nCustomer Name :%s",cust_name);
printf("\nUnit Consumed :%d",unit);
printf("\nNet Amount with Surcharge :%.2f",total_amt);
getch();
}

Sample Input/output

Enter the customer service no: 353


Enter the customer Name: Ram
Enter the unit consumed by customer: 50

Electricity Bill
Customer Service No : 353
Customer Name : Ram
Unit Consumed : 50
Net Amount with Surcharge : 30.00

Enter the customer service no: 353


Enter the customer Name: Ram
Enter the unit consumed by customer: 50

Electricity Bill
Customer Service No : 119
Customer Name : Radha
Unit Consumed : 300
Net Amount with Surcharge : 354.00

Ex. No. 3(d).

Aim:
To write a C program to display the words for any given numbers entered between
zero and nine from the user using switch (…) case … statement.

Algorithm:

1. Get the value for N from the user.

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

37
2. Check the value of N with the cases listed below. If the value of N matched with
the case value, then execute that case, otherwise display “Invalid value entered for
N”,
a. N=0, display “Zero”
b. N=1, display “One”
c. N=2, display “Two”
d. N=3, display “Three”
e. N=4, display “Four”
f. N=5, display “Five”
g. N=6, display “Six”
h. N=7, display “Seven”
i. N=8, display “Eight”
j. N=9, display “Nine”
3. Stop the process.

PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int num;
printf("\n\nEnter a number between 0 - 9 :: ");
scanf("%d",&num);
switch(num)
{
case 0:
printf("\nEntered number is Zero \n");
break;
case 1:
printf("\nEntered number is One \n");
break;
case 2:
printf("\nEntered number is Two \n");
break;
case 3:
printf("\nEntered number is Three \n");
break;
case 4:
printf("\nEntered number is Four \n");
break;
case 5:
printf("\nEntered number is Five \n");
break;
case 6:
printf("\nEntered number is Six \n");
break;
case 7:
printf("\nEntered number is Seven \n");
break;

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

38
case 8:
printf("\nEntered number is Eight \n");
break;
case 9:
printf("\nEntered number is nine \n");
break;
default:
printf("\nEnter the number between is 0 - 9 \n");
break;
}
}

Sample Input/Output:

Enter a number between 0 - 9 :: 0

Entered number is Zero

Enter a number between 0 - 9 :: 1

Entered number is One

Enter a number between 0 - 9 :: 9

Entered number is nine

Enter a number between 0 - 9 :: 10

Enter the number between is 0 - 9

Result:
Thus, a C program to display the words for any given numbers entered between zero
and nine from the user using switch (…) case statement is executed and verified.

Dr.S.Pasupathy , Dept. of Computer Science and Engineering, FEAT, AU

39
4. Loops (for, while and do...while)

i) for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is –

for (initial value; condition; increment value)


{
statement(s);
}

Here is the flow of control in a 'for' loop −


The initial value is executed first, and only once. This initial value allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just after the
'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the 'for' loop terminates.

Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

40
ii) while Loop:
A while loop in C programming repeatedly executes a target statement as long as a given condition
is true.
Syntax
The syntax of a while loop in C programming language is –

while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following
the loop.
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop
in C programming checks its condition at the bottom of the loop.

iii) do...while Loop:


A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least
one time.
Syntax
The syntax of a do...while loop in C programming language is −

do
{
statement(s);
} while(condition);

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.

Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

41
Exp. No: 4. a) SUM OF NATURAL NUMBERS SERIES USING for LOOP
STRUCTURE ( 1 + 2 + 3 +4+ ……+n)

Aim:
To write a C program to compute the sum of series of numbers using for loop structure
Algorithm:

1. Get the value of n from the user.


2. Assign the initial value 0 to sum and initial value 1 to i [sum=0 and i=1].
3. Compute the sum of value of sum and i. Then assign the result to sum.
4. Increment the value of i by 1.
5. Check the value of i. If the value of i is not less than or equal to n go to step 3.
6. Display the result available in sum.
7. Stop the process.

Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, sum = 0;
clrscr();
printf("Enter a positive number: ");
scanf("%d", &n);
for(i=1; i <= n; ++i)
{
sum += i;
}
printf("Sum of Natural Series = %d", sum);
getch();
}
Sample Input and Output

Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

42
Enter a positive number: 50
Sum of Natural Series = 1275

Enter a positive number: 100

Sum of Natural Series = 5050

RESULT:
Thus the C program for finding sum of natural numbers series using has been successfully
executed

Exp. No. 4. b) SUM OF EVEN NUMBERS SERIES USING while LOOP STRUCTURE
(2+4+6+8+……. +n)
Aim:

To write a C program to compute the sum of series of numbers using for loop structure
Algorithm:

1. Get the value of n from the user.


2. Assign the initial value 0 to sum and initial value 2 to i [sum=0 and i=2].
3. Compute the sum of value of sum and i. Then assign the result to sum.
4. Increment the value of i by 2.
5. Check the value of i. If the value of i is not less than or equal to n go to step 3.
6. Display the result available in sum.
7. Stop the process.

Source Code:
#include <stdio.h>
#include <conio.h>
void main()
{
int n, i, sum = 0;

Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

43
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
i = 2;
while ( i <=n )
{
sum += i;
i=i+2;
}
printf("Sum of Even Series= %d”, sum);
getch();
}

Sample Input and Output


Enter a positive number: 50
Sum of Even Series = 650

Enter a positive number: 100

Sum of Even Series = 2550

RESULT:
Thus the C program for finding sum of even numbers series has been successfully executed

Exp. No. 4. c) SUM OF ODD NUMBERS SERIES USING do…while LOOP


STRUCTURE (1+3+5+7+……. +n)
Aim:

To write a C program to compute the sum of series of numbers using for loop structure
Algorithm:

Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

44
1. Get the value of n from the user.
2. Assign the initial value 0 to sum and initial value 1 to i [sum=0 and i=1].
3. Compute the sum of value of sum and i. Then assign the result to sum.
4. Increment the value of i by 2.
5. Check the value of i. If the value of i is not less than or equal to n go to step 3.
6. Display the result available in sum.
7. Stop the process.

Source Code:
#include <stdio.h>
#include <conio.h>
void main()
{
int n, i, sum = 0;
clrscr();
printf("Enter a positive integer: ");
scanf("%d", &n);
i = 1;
do
{
sum += i;
i=i+2;
} while ( i <=n );
printf("Sum of Odd Series= %d",sum);
getch();
}

Sample Input and Output


Enter a positive number: 50
Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

45
Sum of Odd Series = 625

Enter a positive number: 100

Sum of Odd Series = 2500

RESULT:
Thus the C program for finding sum of odd numbers series has been successfully executed

Dr. M. Balasubramanian, Dept. of Computer Science and Engineering, FEAT, AU

46
5. ONE DIMENSIONAL ARRAY
Array

An array is a group (or collection) of same data types. For example an int array holds the
elements of int types while a float array holds the elements of float types.

How to declare array in C

int num[35]; /* An integer array of 35 elements */

char ch[10]; /* An array of characters for 10 elements */

Similarly an array can be of any data type such as double, float, short etc.

Various ways to initialize an array

In the above example, we have just declared the array and later we initialized it with the values
input by user. However you can also initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5}; OR (both are same)

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

Un-initialized array always contain garbage values.

How to access element of an array in C

You can use array subscript (or index) to access any element stored in array. Subscript starts with
0, which means arr[0] represents the first element in the array arr.

In general arr[n-1] can be used to access nth element of an array. where n is any integer number.

For example:

int mydata[20];

mydata[0] /* first element of array mydata*/

mydata[19] /* last (20th) element of array mydata*/

Example of Array in C programming to find out the average of 4 integers

#include <stdio.h>
int main()
{

Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

47
int avg = 0;
int sum =0;
int x=0;
/* Array- declaration – length 4*/
int num[4];
/* We are using a for loop to store the entered values in the array*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20

Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

48
RESULT:
Thus the C program for finding average of 4 integers has been successfully executed

Input data into the array

Here we are iterating the array from 0 to 3 because the size of the array is 4. Inside the loop we
are displaying a message to the user to enter the values. All the input values are stored in the
corresponding array elements using scanf function.

for (x=0; x<4;x++)

printf("Enter number %d \n", (x+1));

scanf("%d", &num[x]);

Reading out data from an array

Suppose, if we want to display the elements of the array then we can use the for loop in C like
this.

for (x=0; x<4;x++)

printf("num[%d]\n", num[x]);

Various ways to initialize an array

In the above example, we have just declared the array and later we initialized it with the values
input by user. However you can also initialize the array during declaration like this:

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

OR (both are same)

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

Un-initialized array always contain garbage values.


Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

49
Ex No. 4 1-D Array

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

4(a) Searching an Element in an Array


Aim: To write a C program for searching an element in a given I-D array

Algorithm

1. Start
2. Get the array size from the user in variable ‘num’
3. Input the array elements using ‘for loop’
4. Read the element to be searched in variable ‘ele’
5. Start search from zeorth location using a ‘while loop’
6. If the element is found, print the location using the loop variable ‘i’
7. Else print element not found
8. End

Program

#include<stdio.h>

int main()
{
int a[30], ele, num, i;

printf("\nEnter no of elements :");


scanf("%d", &num);

printf("\nEnter the values :");

for (i = 0; i < num; i++)


{
scanf("%d", &a[i]);
}

//Read the element to be searched


Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

50
printf("\nEnter the elements to be searched :");
scanf("%d", &ele);

//Search starts from the zeroth location


i = 0;
while (i < num && ele != a[i])

{
i++;
}

if (i < num)
{
printf("Number found at the location = %d", i + 1);
} else

{
printf("Number not found");
}

return (0);
}

Sample Input Output

Enter no of elements: 5
11 22 33 44 55
Enter the elements to be searched: 44

Number found at the location = 4

RESULT:
Thus, the C program for Searching an Element in an Array has been successfully executed

4(b) Sorting the elements of an Array

Aim: To write a C program for Sorting the elements of an Array in a given I-D array

Algorithm

1. Start

Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

51
2. Get the array size from the user in variable ‘n’
3. Input the array elements using ‘for loop’
4. Use two for loops with loop variables ‘i’ and ‘j’ for comparing the array elements
5. Use a temporary variable ‘tmp’ to swap the array values to sort them in ascending order
6. Use for loop to print the sorted array in both ascending and descending order
7. End

#include <stdio.h>
int main()
{
int a[100],n,i,j;
printf("Array size: ");
scanf("%d",&n);
printf("Elements: ");

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for (int i = 0; i < n; i++) //Loop for ascending ordering
{
for (int j = 0; j < n; j++) //Loop for comparing other values
{
if (a[j] > a[i]) //Comparing other array elements
{
int tmp = a[i]; //Using temporary variable for storing last value
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
printf("\n\nAscending : "); //Printing message
for (int i = 0; i < n; i++) //Loop for printing array data in ascending order
{
printf(" %d ", a[i]);
}

printf("\n\nDescending : "); //Printing message


for (int i = n-1; i < -1; i--) //Loop for printing array data in descending order
{
printf(" %d ", a[i]);
}

return 0; //returning 0 status to system

Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

52
}

Sample Input Output

Array size: 10

Elements : 3 4 7 6 5 1 2 8 10 9

Ascending : 1 2 3 4 5 6 7 8 9 10

Descending : 10 9 8 7 6 5 4 3 2 1

RESULT:
Thus, the C program for Sorting the elements of an Array has been successfully executed

Dr. T. S. Subashini, Dept. of Computer Science and Engineering, FEAT, AU

53
6. 2D ARRAYS AND STRINGS

1. Matrix Operations

A matrix is a rectangular array of numbers. C allows the creation of a matrix using two dimensional
arrays. Two dimensional (2D) arrays can be declared as:

datatype array_name[row_size] [column_size];

Example: int matrix[3][4]; creates a 2D array called matrix with 3 rows and 4 columns

2D arrays can be initialized using any of the following statements:

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

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

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

2D arrays can also be initialized by assigning the user supplied inputs obtained using scanf().To
access the individual elements in the 2D array, use matrix[i][j], where i denotes the row index and j
denotes the column index.

2D array index starts from 0 and goes up to its maximum size minus one. The first index selects the
row and the second index selects the column within that row. The elements of the 2D array are
stored in contiguous memory locations in a row-wise manner, starting from first row and ending
with last row.

Example: matrix[1][2] refers to element stored in the 3rd column of 2nd row, because index value
always ranges from 0 to (maximum size-1).

Col=0 Col=1 Col=2


Row=0 1 2 3
Row=1 4 5 6

Operations on matrices, such as addition, multiplication, transpose can be performed by accessing


the individual elements of the matrix.

2. String Operations

A string is a sequence of characters that is treated as a single data item.

Example: “Engineering Mathematics”

C does not support strings as a data type. But strings can be represented a 1D character arrays. The
C compiler automatically appends a null character ‘\0’ at the end of the string. Hence the size of the
string should be equal to the maximum number of characters in the string plus one to accommodate
the null character.

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

54
Example: char city[12] = “Chidambaram”;

C H i d a m b a r a m \0

Strings (say string1, string2) can be read from the terminal using scanf() or gets().

scanf(“%s”, string1);

gets(string2);

scanf() reads a sequence of characters and terminates when the first white space is encountered or
a new line character (‘\n’) is encountered. gets() reads a string of text containing white spaces and
until a new line character (‘\n’) is encountered.

Example:

char name[25], address[100];

scanf(%s”, name);

gets(address);

The strings name and address will be stored as:

name

R a m u \0

address

N O . 3 N e h r u S t r e e t \0

Strings can be displayed using printf() or puts().

printf(“%s, string1);

puts(string2);

Example:

printf(%s”, name); will output the string “Ramu”.

puts(address); will output the string “No.3 Nehru Street”

Operations on Strings:

The library functions in string.h can be used to perform the desired operations on strings:

strcat() concatenates two strings by appending string2 to string1.

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

55
strcat(string1, string2)

strcmp() compares two strings and returns value 0 if they are equal, positive integer if string1 is
greater than string2, and negative integer if string1 is lesser than string2.

strcmp(string1, string2)

strcpy() – copies one string over another by asigning the contents of string2 to string1.

strcpy(string1, string2)

strlen() – finds the length of a string by counting the number of characters in the string excluding the
‘\0’.

strlen(string)

The operations on strings can be performed without using the above library functions also. Since
strings are 1D character arrays, manipulation can be done on the elements of the 1D character array
to achieve the desired result of string operations.

LAB 6. MATRIX PROBLEMS, STRING OPERATIONS

Ex. No. 6(a)

AIM:

To write C programs to perform operations on matrices, such as Addition, Multiplication and


Transpose.

i) Matrix Addition

ALGORITHM:

1. Start.
2. Read the number of rows (r) and columns (c) of the two matrices.
3. Read the elements of first matrix a[r][c].
4. Read the elements of second matrix b[r][c].
5. Repeat steps 5 through 7 by varying i from 0 to r-1.
6. Repeat step 6 through 7 by varying j from 0 to c-1.
7. Calculate sum[i][j] = a[i][j] + b[i][j].
8. Display the elements of sum matrix sum[r][c].
9. Stop.

PROGRAM:

/* This program takes two matrices of order r*c and stores it in two-dimensional array. Then, the
program adds these two matrices and displays the result on the screen */

#include <stdio.h>

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

56
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("\n Enter number of rows (between 1 and 100): ");


scanf("%d", &r);
printf("\n Enter number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\n Enter elements of 1st matrix:\n");


for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}

printf("\n Enter elements of 2nd matrix:\n");


for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element b%d%d: ",i+1, j+1);
scanf("%d", &b[i][j]);
}

/* Adding Two matrices */

for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
sum[i][j]=a[i][j]+b[i][j];
}

/* Displaying the result */


printf("\n Sum of two matrix is: \n\n");
for(i=0;i<r;++i)
{
for(j=0;j<c;++j)
{
printf("%d ",sum[i][j]);
}
printf("\n");
}

return 0;
}

SAMPLE INPUT-OUTPUT:
Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

57
Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12: 2
Enter element a21: 2
Enter element a22: 2
Enter elements of 2nd matrix:
Enter element b11: 3
Enter element b12: 3
Enter element b21: 4
Enter element b22: 4

Sum of two matrix is:

5 5
6 6

RESULT:
Thus the C program to add two matrices was executed successfully.

(ii)Matrix Multiplication

ALGORITHM:

1. Start.
2. Read the number of rows (r1) and columns (c1) of the first matrix (a).
3. Read the number of rows (r2) and columns (c2) of the second matrix (a).
4. Check if c1 is not equal to r2, then Display the message “Error! column of first matrix not
equal to row of second” and Repeat steps 2 and 3.
5. Read the elements of first matrix a[r1][c1].
6. Read the elements of second matrix b[r2][c2].
7. Initialize all the elements of result matrix to 0 by varying i from 0 to r1-1 and j from 0 to c2-1.
8. Repeat steps 8 through 11 by varying i from 0 to r1-1.
9. Repeat steps 9 through 11 by varying j from 0 to c2-1.
10. Repeat steps 10 through 11 by varying k from 0 to c1-1.
11. Calculate result[i][j] = result[i][j] + ( a[i][k] + b[k][j] ).
12. Display the elements of product matrix result[r1][c2].
13. Stop.

PROGRAM:
#include <stdio.h>

/* This program takes two matrices of order r1*c1 and r2*c2 respectively. Then, the program
multiplies these two matrices (if possible) and displays the result on the screen. */

int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

58
printf("\n Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);

printf("\n Enter rows and column for second matrix: ");


scanf("%d %d",&r2, &c2);

// Column of first matrix should be equal to column of second matrix and


while (c1 != r2)
{
printf("\n Error! column of first matrix not equal to row of second.\n\n");
printf("\n Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("\n Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}

// Storing elements of first matrix.


printf("\n Enter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

// Storing elements of second matrix.


printf("\n Enter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}

// Initializing all elements of result matrix to 0


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}

// Multiplying matrices a and b and


// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

59
// Displaying the result
printf("\n Output Matrix:\n");
for(i=0; i<r1; ++i)
{
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}

SAMPLE INPUT-OUTPUT:
Enter rows and column for first matrix: 2 3

Enter rows and column for second matrix: 3 2

Enter elements of matrix 1:


Enter elements a11: 2
Enter elements a12: 2
Enter elements a13: 2
Enter elements a21: 1
Enter elements a22: 1
Enter elements a23: 1

Enter elements of matrix 2:


Enter elements b11: 3
Enter elements b12: 3
Enter elements b21: 2
Enter elements b22: 2
Enter elements b31: 1
Enter elements b32: 1

Output Matrix:
12 12
6 6

RESULT:
Thus the C program to multiply two matrices was executed successfully.

(iii)Transpose of Matrix:

ALGORITHM:

1. Start.
2. Read the number of rows (r) and columns (c) of the matrix (a).
3. Read the elements of matrix a[r][c].
4. Display the elements of the input matrix a[r][c].

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

60
5. Repeat steps 5 through 7 by varying i from 0 to c-1.
6. Repeat steps 6 through 7 by varying j from 0 to r-1.
7. Set transpose[j][i] = a[i][j].
8. Display the elements of transpose matrix transpose[c][r].
9. Stop.

PROGRAM:
#include <stdio.h>

/* This program takes a matrix of order r*c from the user and computes the transpose of that
matrix. */

int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("\n Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);

// Storing elements of the matrix


printf("\n Enter elements of matrix:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

// Displaying the matrix a[][] */


printf("\nEntered Matrix: \n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("%d ", a[i][j]);
if (j == c-1)
printf("\n\n");
}

// Finding the transpose of matrix a


for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
transpose[j][i] = a[i][j];
}

// Displaying the transpose of matrix a


printf("\n Transpose of Matrix:\n");
for(i=0; i<c; ++i)
{
for(j=0; j<r; ++j)
{
printf("%d ",transpose[i][j]);

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

61
}
printf("\n");
}
return 0;
}

SAMPLE INPUT-OUTPUT:
Enter rows and columns of matrix: 2 3

Enter elements of matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 6
Enter element a23: 7

Entered Matrix:
2 3 4
5 6 7

Transpose of Matrix:
2 5
3 6
4 7

RESULT:
Thus the C program to find the transpose of a matrix was executed successfully.

Ex. No. 6(b)


AIM:

To write C programs to get string from the user and manipulate strings with and without using
library functions in C.

(i)String Operations without using library functions

ALGORITHM:

1. Start.
2. Display the menu with 6 choices corresponding to the operations to be performed on
strings.
3. Read the choice from the user.
4. If choice = 1, find the length of the string as follows:
(i) Accept string
(ii) Increment length value by 1 for each character in the string until ‘\0’ is encountered.
(iii) Display length.
5. If choice=2, find frequency of occurrence of a character in string as follows:
(i) Accept string, character (ch) whose frequency is to be found.
(ii) Set frequency=0.

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

62
(iii) For each character in the input string, Increment frequency by 1 when the character
ch is equal to the character in the input string.
(iv) Display frequency.
6. If choice=3, copy one string to another as follows:
(i) Accept string1.
(ii) Copy character by character from string1 to string2 until ‘\0’ is encountered in
string1.
(iii) Append ‘\0’ to string2 and display the copied string string2.
7. If choice=4, concatenate two strings a follows:
(i) Accept string1, string2.
(ii) Find the length of string1 and store it in i.
(iii) Repeat step 7(iv) until ‘\0’ is encountered in string2.
(iv) Append the characters present in string2 onto string1 starting from the (i+1)th
position of string1.
(v) Append ‘\0’ to string1 and Display the concatenated string1.
8. If choice=5, compare two strings as follows:
(i) Accept string1, string2.
(ii) Initialize i=0.
(iii) If (string1[i] is equal to string2[i]) and (string1[i] is not equal to '\0') then i=i+1 and
Repeat Step 8(iii).
(iv) If string1[i] > string2[i] then display “String1 is greater than String2”.
(v) Else If string1[i] < string2[i] then display “String2 is greater than String1”. Else
Display “The two strings are equal”.
9. If choice=6, find the reverse of a string as follows:
(i) Accept string.
(ii) Find the length of string. Set last position=length and first position=0.
(iii) If first position < length, then Interchange the character in the first position and last
position in the string using a temporary variable.
(iv) Decrement last position by 1 and increment first position by 1 and Repeat Step 9(iii).
(v) Display the reversed string.
10. Else display “Invalid choice”.
11. Stop.

PROGRAM:

#include <stdio.h>
#include <string.h>
#include <conio.h>

/* Program to accept string input and perform operations on strings without using library functions
*/
int main()
{
char str[100], s1[100], s2[100];
char ch, temp;
int i, j, choice, length = 0, frequency = 0;

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

63
clrscr();
fflush(stdin);
printf("\n STRING OPERATIONS ");
printf("\n 1. String length");
printf("\n 2. Frequency of occurence of a character in string");
printf("\n 3. Copy one string to another");
printf("\n 4. Concatenate two strings");
printf("\n 5. Compare two strings");
printf("\n 6. Reverse a string ");
printf("\n Enter your choice (1 - 6): ");
scanf("%d", &choice);

fflush(stdin);
switch(choice)
{
case 1: printf("Enter a string: ");
scanf("%s",str);

for(i = 0; str[i] != '\0'; ++i);


length=i;
printf("Length of string: %d", length);
break;

case 2: printf("\n Enter a string: ");


scanf("%s",str);
printf("\n Enter a character to find the frequency: ");
scanf(" %c", &ch);

for(i = 0; str[i] != '\0'; ++i)


{
if(ch == str[i])
++frequency;
}
printf("\n Frequency of %c in %s = %d", ch, str, frequency);
break;

case 3: printf("Enter string s1: ");


scanf("%s",s1);

for(i = 0; s1[i] != '\0'; ++i)


{
s2[i] = s1[i];
}

s2[i] = '\0';
printf("After copying, String s2= %s", s2);
break;

case 4: printf("Enter first string: ");


scanf("%s", s1);

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

64
printf("Enter second string: ");
scanf("%s", s2);

// calculate the length of string s1 and store it in i


for(i = 0; s1[i] != '\0'; ++i);

for(j = 0; s2[j] != '\0'; ++j, ++i)


{
s1[i] = s2[j];
}

s1[i] = '\0';
printf("After concatenation: %s", s1);
break;

case 5: printf("Enter first string: ");


scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

i = 0;
while (s1[i] == s2[i] && s1[i] != '\0')
i++;
if (s1[i] > s2[i])
printf("%s is greater than %s", s1, s2);
else if (s1[i] < s2[i])
printf("%s is lesser than %s", s1, s2);
else
printf("%s is equal to %s", s1, s2);
break;

case 6: printf("Enter a string: ");


scanf("%s",str);

for(i = 0; str[i] != '\0'; ++i);


length=i-1;
i=0;
while (i < length)
{
temp = str[i];
str[i] = str[length];
str[length] = temp;
i++;
length--;
}

printf("\n Reversed string is: %s", str);


break;

default: printf("\n Invalid choice..");

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

65
break;
}

getch();
return 0;
}

Sample INPUT-OUTPUT:

STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings
6. Reverse a string
Enter your choice (1 - 6): 1
Enter a string: Computer
Length of string: 8

STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings
6. Reverse a string
Enter your choice (1 - 6): 2

Enter a string: system

Enter a character to find the frequency: s

Frequency of s in system = 2
STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings
6. Reverse a string
Enter your choice (1 - 6): 3
Enter string s1: Python
After copying, String s2= Python

STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

66
6. Reverse a string
Enter your choice (1 - 6): 4
Enter first string: Engineering
Enter second string: Physics
After concatenation: EngineeringPhysics

STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings
6. Reverse a string
Enter your choice (1 - 6): 5
Enter first string: India
Enter second string: Indian
India is lesser than Indian

STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings
6. Reverse a string
Enter your choice (1 - 6): 6
Enter a string: Hello

Reversed string is: olleH

STRING OPERATIONS
1. String length
2. Frequency of occurence of a character in string
3. Copy one string to another
4. Concatenate two strings
5. Compare two strings
6. Reverse a string
Enter your choice (1 - 6): 7

Invalid choice..

RESULT:
Thus the operations on strings have been carried out without using the library functions in string.h.

(ii)String Operations using library functions

ALGORITHM:

1. Start.

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

67
2. Display the menu with 4 choices corresponding to the operations to be performed on
strings.
3. Read the choice from the user.
4. If choice = 1, find the length of the string as follows:
(i) Accept string.
(ii) Find length using strlen() function.
(iii) Display length.
5. If choice=2, copy one string to another as follows:
(i) Accept string1.
(ii) Copy string 1 to string2 using strcpy() function.
(iii) Display the copied string string2.
6. If choice=3, concatenate two strings a follows:
(i) Accept string1, string2.
(ii) Concatenate the two strings using strcat() function.
(iii) Display the concatenated string1.
7. If choice=4, compare two strings as follows:
(i) Accept string1, string2.
(ii) Compare the two strings using strcmp() function.
(iii) If the result of strcmp() is greater than 0 then display “String1 is greater than
String2”.
(iv) Else If the result of strcmp() is greater than 0 then display “String2 is greater than
String1”. Else Display “The two strings are equal”.
8. Else display “Invalid choice”.
9. Stop.

PROGRAM:

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
char str[100], s1[100], s2[100];
char ch, temp;
int i, j, choice, length = 0, frequency = 0;

clrscr();
fflush(stdin);
printf("\n STRING OPERATIONS ");
printf("\n 1. String length");
printf("\n 2. Copy one string to another");
printf("\n 3. Concatenate two strings");
printf("\n 4. Compare two strings");
printf("\n Enter your choice (1 - 5): ");
scanf("%d", &choice);

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

68
fflush(stdin);
switch(choice)
{
case 1: printf("Enter a string: ");
scanf("%s",str);

length = strlen(str);
printf("Length of string: %d", length);
break;

case 2: printf("Enter string s1: ");


scanf("%s",s1);

strcpy(s2, s1);
printf("After copying, String s2= %s", s2);
break;

case 3: printf("Enter first string: ");


scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

strcat(s1, s2);
printf("After concatenation: %s", s1);
break;

case 4: printf("Enter first string: ");


scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

if (strcmp(s1, s2) > 0)


printf("%s is greater than %s", s1, s2);
else if (strcmp(s1, s2) < 0)
printf("%s is lesser than %s", s1, s2);
else
printf("%s is equal to %s", s1, s2);
break;

default: printf("\n Invalid choice..");


break;
}

getch();
return 0;
}

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

69
SAMPLE INPUT – OUTPUT:

STRING OPERATIONS
1. String length
2. Copy one string to another
3. Concatenate two strings
4. Compare two strings
5. Reverse a string
Enter your choice (1 - 6): 1
Enter a string: Annamalai
Length of string: 9

STRING OPERATIONS
1. String length
2. Copy one string to another
3. Concatenate two strings
4. Compare two strings
5. Reverse a string
Enter your choice (1 - 6): 2
Enter string s1: Python
After copying, String s2= Python

STRING OPERATIONS
1. String length
2. Copy one string to another
3. Concatenate two strings
4. Compare two strings
5. Reverse a string
Enter your choice (1 - 6): 3
Enter first string: Annamalai
Enter second string: University
After concatenation: AnnamalaiUniversity

STRING OPERATIONS
1. String length
2. Copy one string to another
3. Concatenate two strings
4. Compare two strings
5. Reverse a string
Enter your choice (1 - 6): 4
Enter first string: Abcd
Enter second string: Ab
Abcd is greater than Ab

STRING OPERATIONS
1. String length
2. Copy one string to another
3. Concatenate two strings
4. Compare two strings
5. Reverse a string

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

70
Enter your choice (1 - 6): 6

Invalid choice..

RESULT:
Thus the operations on strings have been carried out using the library functions in string.h.

Dr. AN. Sigappi, Dept. of Computer Science and Engineering, FEAT, AU

71
7. FUNCTIONS IN ‘C’
A function is a block of code that performs a specific task. Depending on whether a
function is defined by the user or already included in C compilers, there are two types of
functions in C programming. They are :
• Standard library functions
• User defined functions

Standard Library Functions:


The standard library functions are built-in functions in C programming to handle tasks
such as mathematical computations, I/O processing, string handling etc. These functions are
defined in the header file. When you include the header file, these functions are available for
use.
For example, printf() is a standard library function used to send formatted output to
the screen (display output on the screen. This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once we include "stdio.h" in our program, all these
functions are available for use.

User-Defined Functions:
Functions that are created by the user are called user-defined functions. The syntax
for a user-defined function is given as follows:

#include<stdio.h>
type functionname(); /*function declaration*/
type main() /*main function*/
{
.......
.......
functionname(); /* function call*/
.......
.......
}
type functionname() /* function definition*/
{
........
........
return value;
}

The execution of a C program begins from the main() function. When the compiler
encounters functionname() inside the main function, control of the program jumps to void
functionname(). Then the compiler starts executing the codes inside the user-defined
function. Once all the codes inside the function definition are executed, the function returns
the value to the main() and the control of the program jumps to the statement next
to functionname() in main(). Here, function name is an identifier and should be unique.
Types of Functions:
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference

Dr. A. Geetha, Dept. of Computer Science and Engineering, FEAT, AU

72
Call by Value:
• In call by value method, the value of the variable is passed to the function as parameter.
• The value of the actual parameter cannot be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters and hence only the
value of actual parameter is copied to formal parameter.
where
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition

Call by Reference:
• In call by reference method, the address of the variable is passed to the function as
parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used
by both parameters.

Dr. A. Geetha, Dept. of Computer Science and Engineering, FEAT, AU

73
Ex. No. 7(a) Conversion of Fahrenheit to Centigrade using Function
Aim :
To implement a ‘C’ program to for converting temperature in fahrenheit to centigrade
using a function that returns a value.

Algorithm:
1. Start the program
2. Read the value of fahrenheit
3. Call the function convert(fahrenheit)
4. Start the function
5. Convert fahrenheit to centigrade as c = (f-32)/1.8
6. End the function
7. Print the value of centigrade
8. End the program

Program:

#include<stdio.h>
/*convert function declaration*/
float convert(float f);
/*main() function definition*/
void main()
{
float temp_f,temp_c;
printf( "Enter Fahrenheit Value:");
scanf("%f",&temp_f);
/*convert function call*/
temp_c = convert(temp_f);
printf("Centigrade Value : %f", temp_c);
}
/*convert function definition*/
float convert(float f)
{
float c;
c=(f-32)/1.8;
return(c);
}

Sample Input and Output:

Enter Fahrenheit Value : 77.00


Centigrade Value : 25.00

RESULT:
Thus the C program for finding Conversion of Fahrenheit to Centigrade has been successfully
executed

Dr. A. Geetha, Dept. of Computer Science and Engineering, FEAT, AU

74
Ex. No. 7(b) Swapping of Two Numbers using Function Call by Value
Aim :
To implement a ‘C’ program to swap two numbers using a function call by value.

Algorithm :
1: Start the program
2: Read and print two numbers a and b
3: Call the function swap(a,b) by value
3a: Start the function
3b: Assign x to temp
3c: Assign y to x
3d: Assign temp to y
3e: Print x and y
3f: End the function
3g: Print a and b
4: End the program

Program :
#include <stdio.h>
/*swap function declaration*/
void swap(int, int);
/* main() function definition */
void main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
printf("Before swapping in main function: a =%d, b = %d\n", a, b);
/* swap function call */
swap(a,b);
printf("After swapping in main function: a=%d, b=%d\n",a, b);
}
/* swap function definition */
void swap(int x, int y)
{
int temp;
printf("Before swapping in swap function: x=%d, y= %d\n", x, y);
temp = x;
x=y;
y=temp;
printf("After swapping in swap function: x= %d, y= %d\n", x, y);
}

Sample Input and Output:


Enter two numbers : 20 55

Dr. A. Geetha, Dept. of Computer Science and Engineering, FEAT, AU

75
Before swapping in main function : a=20, b=55
Before swapping in swap function: x=20, y= 55
After swapping in swap function: x= 55, y= 20
After swapping in main function: a=20, b=55
}

RESULT:
Thus the C program for swapping of two numbers using function call by value has been
successfully executed

Ex. No. 7(c) Swapping of Two Numbers using Function Call by Reference
Aim :
To implement a ‘C’ program to swap two numbers using a function call by reference.

Algorithm :
1: Start the program
2: Read and print two numbers a and b
3: Call the function swap(a,b) by reference
3a: Start the function
3b: Assign x to temp
3c: Assign y to x
3d: Assign temp to y
3e: Print x and y
3f: End the function
3g: Print a and b
4: End the program

Program :
#include <stdio.h>
/*swap function declaration*/
void swap(int*, int*);
/* main() function definition */
void main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
printf("Before swapping in main function: a =%d, b = %d\n", a, b);
/* swap function call */
swap(&a,&b);
printf("After swapping in main function: a=%d, b=%d\n",a, b);
}
/* swap function definition */
void swap(int *x, int *y)
{

Dr. A. Geetha, Dept. of Computer Science and Engineering, FEAT, AU

76
int temp;
printf("Before swapping in swap function: x=%d, y= %d\n", *x, *y);
temp = *x;
*x=*y;
*y=temp;
printf("After swapping in swap function: x= %d, y= %d\n", *x, *y);
}

Sample Input and Output:


Enter two numbers : 20 55
Before swapping in main function : a=20, b=55
Before swapping in swap function: x=20, y= 55
After swapping in swap function: x= 55, y= 20
After swapping in main function: a=55, b=20
}

RESULT:

Thus, the C program for swapping of two numbers using function call by reference has been
successfully executed

Dr. A. Geetha, Dept. of Computer Science and Engineering, FEAT, AU

77
8. NUMERICAL METHODS (ROOT FINDING)

The bisection method in mathematics is a root-finding method that repeatedly bisects an


interval and then selects a subinterval in which a root must lie for further processing. It is a very
simple and robust method, but it is also relatively slow. Because of this, it is often used to obtain a
rough approximation to a solution which is then used as a starting point for more rapidly converging
methods. The method is also called the interval halving method, the binary search method, or the
dichotomy method.
Bisection method is used to find the real roots of a nonlinear equation. The process is based
on the ‘Intermediate Value Theorem‘. According to the theorem “If a function f(x)=0 is continuous
in an interval (a,b), such that f(a) and f(b) are of opposite nature or opposite signs, then there exists
at least one or an odd number of roots between a and b.”
The method is applicable for numerically solving the equation f(x) = 0 for the real variable x,
where f is a continuous function defined on an interval [a, b] and where f(a) and f(b) have opposite
signs. In this case a and b are said to bracket a root since, by the intermediate value theorem, the
continuous function f must have at least one root in the interval (a, b).
At each step the method divides the interval in two by computing the midpoint c = (a+b) / 2
of the interval and the value of the function f(c) at that point. Unless c is itself a root (which is very
unlikely, but possible) there are now only two possibilities: either f(a) and f(c) have opposite signs
and bracket a root, or f(c) and f(b) have opposite signs and bracket a root. The method selects the
subinterval that is guaranteed to be a bracket as the new interval to be used in the next step. In this
way an interval that contains a zero of f is reduced in width by 50% at each step. The process is
continued until the interval is sufficiently small.
Explicitly, if f(a) and f(c) have opposite signs, then the method sets c as the new value for b,
and if f(b) and f(c) have opposite signs then the method sets c as the new a. (If f(c)=0 then c may be
taken as the solution and the process stops.) In both cases, the new f(a) and f(b) have opposite signs,
so the method is applicable to this smaller interval.

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

78
Aim:
Write a C program for bisection method
Algorithm:
1. Start
2. Read x1, x2, e
*Here x1 and x2 are initial guesses, e is the absolute error i.e. the desired degree of accuracy*
3. Compute: f1 = f(x1) and f2 = f(x2)
4. If (f1*f2) > 0, then display initial guesses are wrong and goto (11).
Otherwise continue.
5. x = (x1 + x2)/2
6. If ( [ (x1 – x2)/x ] < e ), then display x and goto (11).
* Here [ ] refers to the modulus sign. *
7. Else, f = f(x)
8. If ((f*f1) > 0), then x1 = x and f1 = f.
9. Else, x2 = x and f2 = f.
10. Goto (5).
*Now the loop continues with new values.*
11. Stop

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

79
Program:
#include<stdio.h>
#include<math.h>
float fun (float x)
{
return (x*x*x - 4*x - 9);
}
void bisection (float *x, float a, float b, int *itr)
/* this function performs and prints the result of one iteration */
{
*x=(a+b)/2;
++(*itr);
printf("Iteration no. %3d X = %7.5f\n", *itr, *x);
}
int main ()
{
int itr = 0, maxmitr;
float x, a, b, allerr, x1;
printf("\nEnter the values of a, b, allowed error and maximum iterations:\n");
scanf("%f %f %f %d", &a, &b, &allerr, &maxmitr);
bisection (&x, a, b, &itr);
do
{
if (fun(a)*fun(x) < 0)
b=x;
else
a=x;
bisection (&x1, a, b, &itr);
if (fabs(x1-x) < allerr)
{
printf("After %d iterations, root = %6.4f\n", itr, x1);
return 0;
}
x=x1;
}
while (itr < maxmitr);
printf("The solution does not converge or iterations are not sufficient");
return 1;
}

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

80
Sample Input/Output:

Result
Thus, the C program for finding bisection method has been successfully executed

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

81
9(a). NUMERICAL DIFFERENTIATION
Differentiation is a basic mathematical operation with a wide range of applications in many
areas of science. It is therefore important to have good meth- ods to compute and manipulate
derivatives. You probably learnt the basic rules of differentiation in school — symbolic methods
suitable for pencil-and-paper calculations. Such methods are of limited value on computers since the
most common programming environments do not have support for symbolic computation.
In numerical analysis, numerical differentiation describes algorithms for estimating the
derivative of a mathematical function or function subroutine using values of the function and perhaps
other knowledge about the function.
NEWTON`S FORWARD INTERPOLATION FORMULA
Interpolation is the process of finding the values of y corresponding to the any value of x
between x0 and xn for the given values of y=f(x) for a set of values of x. Out of the many techniques
of interpolation, Newton’s Forward and Backward Interpolation are two very widely used formulas.
In this tutorial, we’re going to discuss a C program for Newton Forward Interpolation along with its
sample output.
Both of Newton’s formulas are based on finite difference calculus. These formulas are very
often used in engineering and related science fields. Before going through the source code for Newton
Forward Interpolation, let’s go through the forward interpolation formula and the variables used in
the C program.
Newton’s forward interpolation formula contains y0 and the forward differences of y0. This
formula is used for interpolating the values of y near the beginning of a set of tabulated values and
extrapolation the values of y a little backward (i.e. to the left) of y0. The formula is given below:

Compared to forward interpolation, the backward interpolation formula contains yn and the
backward differences of yn. This formula is used for interpolating the values of y near the end of a
set of tabulated values and also for extrapolating the values of y a little ahead (i.e. to the right) of yn.

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

82
Aim:
Write a C program for Newton Forward Interpolation.
Algorithm:
• Start
• Define and Declare function
• Making the difference table
• Calculating the 1st order of differences
• Afetr calculating the second and higher order differences
• Perform following operation in loop
x[i]=x0+i*h
y[i]=f(x[i])
print y[i]
• Initialize se=0, s0=0
• Do the following using loop
diff[i][j] = diff[i+1][j-1] – diff[i][j-1];
• Now finding x0
h=ax[1]-ax[0]
• Print the ans
• Stop

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

83
Program
#include<stdio.h>
#define MAXN 100
#define ORDER 4
int main()
{
float ax[MAXN+1], ay [MAXN+1], diff[MAXN+1][ORDER+1], nr=1.0, dr=1.0,x,p,h,yp;
int n,i,j,k;
printf("\nEnter the value of n:\n");
scanf("%d",&n);
printf("\nEnter the values in form x,y:\n");
for (i=0;i<=n;i++)
scanf("%f %f",&ax[i],&ay[i]);
printf("\nEnter the value of x for which the value of y is wanted: \n");
scanf("%f",&x);
h=ax[1]-ax[0];
//now making the difference table
//calculating the 1st order of differences
for (i=0;i<=n-1;i++)
diff[i][1] = ay[i+1]-ay[i];
//now calculating the second and higher order differences
for (j=2;j<=ORDER;j++)
for(i=0;i<=n-j;i++)
diff[i][j] = diff[i+1][j-1] - diff[i][j-1];
//now finding x0
i=0;
while (!(ax[i]>x))
i++;
//now ax[i] is x0 and ay[i] is y0
i--;
p = (x-ax[i])/h;
yp = ay[i];
//now carrying out interpolation
for (k=1;k<=ORDER;k++)
{
nr *=p-k+1;
dr *=k;
yp +=(nr/dr)*diff[i][k];
}
printf("\nWhen x = %6.1f, corresponding y = %6.2f\n",x,yp);
}

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

84
Sample Input/Output:

Result
Thus, the C program for Newton Forward Interpolation has been successfully executed

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

85
9(b). NUMERICAL INTEGRATION
Numerical integration is the approximate computation of an integral using numerical
techniques. The numerical computation of an integral is sometimes called quadrature.
In numerical analysis, numerical integration comprises a broad family of algorithms for
calculating the numerical value of a definite integral, and by extension, the term is also sometimes
used to describe the numerical solution of differential equations. This article focuses on calculation
of definite integrals. The term numerical quadrature (often abbreviated to quadrature) is more or less
a synonym for numerical integration, especially as applied to one-dimensional integrals. Some
authors refer to numerical integration over more than one dimension as cubature; others take
quadrature to include higher-dimensional integration.
The basic problem in numerical integration is to compute an approximate solution to a definite
integral to

a given degree of accuracy. If f(x) is a smooth function integrated over a small number of dimensions,
and the domain of integration is bounded, there are many methods for approximating the integral to
the desired precision.

TRAPEZOIDAL METHOD
Definite integral is replica of area under a curve within the certain limit. In order to calculate
such area, there have been developed a number of analytical methods but they are time-consuming,
laborious and chance of occurrence of error is also high. That is why, techniques of numerical methods
are very much popular in calculation numerical integration which can easily be programmed and
trapezoidal method is one of them.
In this tutorial, we’re going to discuss a simple algorithm and flowchart for trapezoidal method
along with a brief introduction to the method.
Trapezoidal method is based on the principle that the area under the curve which is to be
calculated is divided into number of small segments. The bounding curve in the segment is considered
to be a straight line as a result the small enclosed area becomes a trapezium.
The area of each small trapezium is calculated and summed up i.e. integrated. This idea is the
working mechanism in trapezoidal method algorithm and flowchart, even it source code.
Let us consider a function f(x) representing a curve as shown in above figure. You are to find
out the area under the curve from point ‘a’ to ‘b’. In order to do so, divide the distance between ab
into a number vertical strips of width ‘h’ so that each strip can be considered as trapezium.

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

86
The following formula is used to calculate the area under the curve:

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

87
Aim:
Write a C program for Trapezoidal Method

Algorithm:
1. Start
2. Define and Declare function
3. Input initial boundary value, final boundary value and length of interval
4. Calculate number of strips, n = (final boundary value –final boundary value)/length of interval
5. Perform following operation in loop
x[i]=x0+i*h
y[i]=f(x[i])
print y[i]
6. Initialize se=0, s0=0
7. Do the following using loop
If i %2 = 0
So=s0+y[i]
Otherwise
Se=se+y[i]
8. ans= h/3*(y[0]+y[n]+4*so+2*se)
9. print the ans
10. stop

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

88
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
float f(float x)
{
return(1/(1+pow(x,2)));
}
void main()
{
int i,n;
float x0,xn,h,y[20],so,se,ans,x[20];
printf("\n Enter values of x0,xn,h:\n");
scanf("%f%f%f",&x0,&xn,&h);
n=(xn-x0)/h;
if(n%2==1)
{
n=n+1;
}
h=(xn-x0)/n;
printf("\nrefined value of n and h are:%d %f\n",n,h);
printf("\n Y values \n");
for(i=0; i<=n; i++)
{
x[i]=x0+i*h;
y[i]=f(x[i]);
printf("\n%f\n",y[i]);
}
so=0;
se=0;
for(i=1; i<n; i++)
{
if(i%2==1)
{
so=so+y[i];
}
else
{
se=se+y[i];
}
}
ans=h/3*(y[0]+y[n]+4*so+2*se);
printf("\nfinal integration is %f",ans);
getch();

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

89
}
Sample Input/Output:

Result
Thus, the C program for finding Trapezoidal Method has been successfully executed

Dr. S.G. Santhi, Dept. of Computer Science and Engineering, FEAT, AU

90
10. RECURSION, STRUCTURE OF RECURSIVE CALLS

Recursion:

When a function calls itself, it is called a recursion. A recursive function always has to
say when to stop repeating itself. Recursive functions have a base case and a recursive case.

• Base case, which is the simplest, smallest instance of the problem, that can’t be
decomposed any further. Base cases often correspond to emptiness – the empty string, the
empty list, the empty set, the empty tree, zero, etc. The base case is when the function
stops calling itself.
• Recursive case, which decomposes a larger instance of the problem into one or simpler
or smaller instances that can be solved by recursive calls, and then recombines the
results of those sub problems to produce the solution to the original problem. The
recursive case is when the function calls itself.

Recursion Functions:

F(n) = 1 when n=0 or 1

= F(n-1) when n>1

Example: Calculating the 3!

F(n)=1 when n=0 or1

=nx F(n-1) when n>1

So, F(3)=3xf(3-1)=3xf(2)

And F(2)=2xF(2-1)=2xF(1)

Now, F(1)=1

F(2)=2xF(1)=2x1=2

F(3)=3xF(2)=3x2=6

Dr. R. Priya, Dept. of Computer Science and Engineering, FEAT, AU

91
Ex. No. 10 a) To find the factorial of a given number using recursive function

Aim:
To write a C program to find the factorial of a given number using recursive function.

Algorithm:

Step1: Start the program

Step 2: Read the value of n.

Step 3: Call the sub program as f=fact (n).

Step 4: Print the f value.

Step 5: Stop the program.

Sub program:

Step 1: Initialize the f value.

Step 2: If n==0 or n==1 return 1 to main program. Otherwise go to step 3.

Step 3: return n*fact (n-1) to main program.

Program:

//To find the factorial of a given number using recursive function

#include<stdio.h>
#include<conio.h>
int fact(int )
void main()
{
int n,rec;
clrscr();
printf(“Enter the number:”);
scanf(“%d”,&n);
rec=fact(n);
printf(“The factorial of a given number is=%d”,rec);
getch();
}
int fact(int n)
{
int r;

Dr. R. Priya, Dept. of Computer Science and Engineering, FEAT, AU

92
if(n==0)
return 1;
else
r=n*fact(n-1);
return(r);
}

Sample Input & Output:

Enter the number: 5

The factorial of a given number is=120

Result:

Thus the given program is successfully executed and the output was verified.

Ex. No. 10 b) To find the sum of natural numbers using the recursive function

Aim:

To write a C program to find the sum of natural numbers using the recursive function.

Description:

The value of the num is 4 initially. During next function call, 3 is passed to the sum ()
function. This process continues until num is equal to zero.

Example:

The Sum of 4 is 10.

Algorithm:

Main program:

Step1: Start the program.

Step 2: Read the number.

Step 3: Call the sub program sum ()

Dr. R. Priya, Dept. of Computer Science and Engineering, FEAT, AU

93
Step 4: Print the value.

Step 5: Stop the program.

Sub program:

Step 1: If n! =0 then return num + sum (num-1). Repeat the function till condition
satisfied. Return num value to the main function. Otherwise, go to step 2.

Step 2: If n==0 return num value.

Program :

//To find the sum of natural numbers using the recursive function

#include<stdio.h>
int sum(int n)
int main()
{
int number, result;
printf(“Enter the positive number:”);
scanf(“%d”,&number);
result=sum(number);
printf(“Sum of the %d positive numbers:%d”,num,result);
return 0;
}
int sum(int num)
{
if(num!=0)
return num=sum(num-1);
else
return num;
}

Sample Input & Output:

Enter the positive number: 3

Sum of the 3 positive numbers: 6

Result:

Thus, the given program is successfully executed and the output was verified.

Dr. R. Priya, Dept. of Computer Science and Engineering, FEAT, AU

94
11. STRUCTURES AND POINTERS
Structures :
Structure is a user-defined datatype, which allows to use to combine data of different types
together. Structure helps to construct a complex data type which is more meaningful. It is
somewhat similar to an Array, but an array holds data of similar type only.
Defining a Structure :
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows :
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition, before
the final semicolon, you can specify one or more structure variables but it is optional.

Accessing Structure Members :


To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that
we wish to access.
Structure variables.member definition

struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", record1.id);
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);
return 0;
}

Dr. A. Suhasini, Dept. of Computer Science and Engineering, FEAT, AU

95
Pointers to Structures :
You can define pointers to structures in the same way as you define pointer to any other variable.
struct struct variables *struct_pointer;
To access the members of a structure using a pointer to that structure, you must use the → operator.
struct_pointer->member definition;
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}

Dynamic Memory Allocation :

The process of allocating memory during program execution is called dynamic memory allocation.
C language offers 4 dynamic memory allocation functions. They are,

malloc()
calloc()
realloc()
free()
Function Syntax

malloc () malloc (number *sizeof(int));

calloc () calloc (number, sizeof(int));

realloc () realloc (pointer_name, number * sizeof(int));

free () free (pointer_name);

Dr. A. Suhasini, Dept. of Computer Science and Engineering, FEAT, AU

96
MALLOC( ) :
• malloc ( ) function is used to allocate space in memory during the execution of the program.
• malloc ( ) does not initialize the memory allocated during execution. It carries garbage
value.
• malloc ( ) function returns null pointer if it couldn’t able to allocate requested amount of
memory.

ptr = (cast-type*) malloc(byte-size)

example
ptr = (int*) malloc(100 * sizeof(int));

CALLOC( ) :
• calloc ( ) function is also like malloc ( ) function. But calloc ( ) initializes the allocated
memory to zero. But, malloc( ) doesn’t.

ptr = (cast-type*)calloc(n, element-size);

example
ptr = (float*) calloc(25, sizeof(float));

REALLOC( ) :
• realloc ( ) function modifies the allocated memory size by malloc ( ) and calloc ( ) functions
to new size.
• If enough space doesn’t exist in memory of current block to extend, new block is allocated
for the full size of reallocation, then copies the existing data to new block and then frees
the old block.

ptr = realloc(ptr, x);


Here, ptr is reallocated with new size x.

4. FREE( ) :
• free ( ) function frees the allocated memory by malloc ( ), calloc ( ), realloc ( ) functions
and returns the memory to the system.

free(ptr);

Dr. A. Suhasini, Dept. of Computer Science and Engineering, FEAT, AU

97
Ex.No.11 STRUCTURES AND POINTERS
Aim
To write a C Program to Generate salary slip of employees using structures and pointers.

Algorithm
1. Start
2. Declare variables1
3. Read the number of employees .
4. Read allowances, deductions and basic for each employee.
5. Calculate net pay= (basic+ allowances)-deductions
6. Display the output of the Pay slip calculations for each employee.
7. Stop

Program
#include<stdio.h>
#include<conio.h>
#include "stdlib.h"
struct emp
{
int empno ;
char name[10], answer ;
int bpay, allow, ded, npay ;
struct emp *next;
};
void main()
{
int i,n=0;

Dr. A. Suhasini, Dept. of Computer Science and Engineering, FEAT, AU

98
int more_data = 1;
struct emp e *current_ptr, *head_ptr;
clrscr() ;
head_ptr = (struct emp *) malloc (sizeof(struct emp));
current_ptr = head_ptr;
while (more_data)
{
{
printf("\nEnter the employee number : ") ;
scanf("%d", & current_ptr->empno) ;
printf("\nEnter the name : ") ;
scanf("%s",& current_ptr->name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", & current_ptr ->bpay, & current_ptr ->allow, & current_ptr -
>ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
n++;
printf("Would you like to add another employee? (y/n): ");
scanf("%s", answer);
if (answer!= 'Y')
{
current_ptr->next = (struct eme *) NULL;
more_data = 0;
}
else
{
current_ptr->next = (struct emp *) malloc (sizeof(struct emp));
current_ptr = current_ptr->next;

Dr. A. Suhasini, Dept. of Computer Science and Engineering, FEAT, AU

99
}
}
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
current_ptr = head_ptr;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", current_ptr->empno,
current_ptr->name, current_ptr->bpay, current_ptr->allow, current_ptr->ded,
current_ptr->npay) ;
current_ptr=current_ptr->next;
}
Free(current_ptr)
getch() ;
}

Sample Input and Output


Enter the number of employees : 2
Enter the employee number : 101
Enter the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102
Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750
Emp.No. Name Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750

Result
The C program using Structure and Pointers are executed successfully.

Dr. A. Suhasini, Dept. of Computer Science and Engineering, FEAT, AU

100
12. FILE HANDLING OPERATION IN ‘C’ PROGRAMMING
In C, a stream is associated with a file. Special functions have been designed for handling file
operations. The header file stdio.h is required for using these functions.

Opening a file

Before perform any operations on a file, we need to open it. do this by using a file pointer. The
type FILE defined in stdio.h allows us to define a file pointer. Then use the function fopen() for
opening a file. The fclose() function is used to explicitly close any opened file.

Opening or Creating file –


For opening a file, fopen function is used with the required access modes.

FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)

The second parameter can be changed to contain all the attributes listed in the above table.
• Reading from a file –
The file read operations can be perfomed using functions fscanf or fgets. Both the functions
performd the same operations as that of printf and gets but with an additional parameter,
the file pointer. So, it depends on want to read the file line by line or character by character.
And the code snippet for reading a file is as:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);

• Writing a file –:
The file write operations can be perfomed by the functions
The writing to a file is as :
FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);

• Closing a file –:
After every successful fie operations, you must always close a file. For closing a file, you
have to use fclose function. The snippet for closing a file is given as :

FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer)

Dr. R. Madhan Mohan, Dept. of Computer Science and Engineering, FEAT, AU

101
sample coding :

#include <stdio.h>
main ()
{
FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("File does not exist, please check!\n");
}
fclose(fp);
}

fopen()
The fopen() is a function accepts two arguments as strings.
The first argument denotes the name of the file to be opened and the second signifies the mode in
which the file is to be opened.

The second argument can be any of the following:

File Mode Description


r Open a text file for reading
w Create a text file for writing, if it exists, it is overwritten.
a Open a text file and append text to the end of the file.
rb Open a binary file for reading
wb Create a binary file for writing, if it exists, it is overwritten.
ab Open a binary file and append data to the end of the file.

fclose()
The fclose() function is used for closing opened files. The only argument it accepts is the file
pointer. If a program terminates, it automatically closes all opened files.
getc() and putc()
The functions getc() and putc() are equivalent to getchar() and putchar() functions on Input and
Output, except that these functions require an argument which is the file pointer.
Function getc() reads a single character from the file which has previously been opened using a
function like fopen().
Function putc() does the opposite, it writes a character to the file identified by its second
argument.

The format of both functions is as follows :


getc(in_file);
putc(c, out_file);

Dr. R. Madhan Mohan, Dept. of Computer Science and Engineering, FEAT, AU

102
Note: The second argument in the putc() function must be a file opened in either write or append
mode.
12. FILE HANDLING OPERATION IN ‘C’
12 (a). To Create a text file with file handling operation of fopen, fclose in ‘C’
programming.

Aim: To write a C program to create a text file using fopen, fclose file operations.

Algorithm
Step 1: Start
Step 2: Read a file name to create
Step 3: open a empty file in write mode.
Step 3: if the file is null , then the file does not created.
Step 4: if the file is not null , then file is successfully created.
Step 5: Stop
Program:
#include< stdio.h >
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("Enter file name to create :");
scanf("%s",fName);
/*creating (open) a file, in “w”: write mode*/
fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
return 0;
}

Dr. R. Madhan Mohan, Dept. of Computer Science and Engineering, FEAT, AU

103
Sample Input and Output:

Enter file name to create : file1.txt


File created successfully.

Enter file name to create : d:/file1.txt


File created successfully.

“file will be created in d: drive”.

Enter file name to create : h:/file1.txt


File does not created!!!

Results:
Thus, the program to create a text file with file handling operations has been executed
succesfully

12.(b) Write a C program for copying the content of a text file to another text file.

Aim:

To write a C program for copying the content of a text file to another text file.

Algorithm:
Step 1: Start
Step 2: open a empty file in write mode.
Step 3: if it is not end of file
Step 4: write data into that file.
Step 5: close the write mode operation
Step 6: now open that file in read mode.
Step 7: open a another empty file in write mode .
Read the content of the file1 with getc and store it in variable ‘c’.
Write the content in variable ‘c’ to file2.
Close the file1 , file2.

Dr. R. Madhan Mohan, Dept. of Computer Science and Engineering, FEAT, AU

104
Open the file2 in read mode.
the contents of the file will be displayed
Step 8: Stop

Program:

#include<stdio.h>
#include<conio.h>
FILE *fp1,*fp2;
char c;
void main()
{
clrscr();
printf("enter the text\n");
fp1 = fopen("abc.txt", "w");
while((c = getchar()) != EOF)
putc(c, fp1);
fclose(fp1);
fp1 = fopen("abc.txt","r");
fp2=fopen("xyz.txt","w");
while(!feof(fp1))
{
c = getc(fp1);
putc(c,fp2);
}
fclose(fp1);
fclose(fp2);
printf("after copying the data in file2.txt file is \n");
fp2 = fopen("xyz.txt", "r");
while(!feof(fp2))
{

Dr. R. Madhan Mohan, Dept. of Computer Science and Engineering, FEAT, AU

105
c = getc(fp2);
printf("%c", c);
}
getch();
}

Sample Input & Output:


enter the text
The best quote by APJ ABDUL KALAM,
“All birds find shelter during a rain. But the eagle avoids rain by flying above the clouds.
Problems are common, but attitude makes the difference! ”

^Z

after copying the data in file2.txt file is


The best quote by APJ ABDUL KALAM,
“All birds find shelter during a rain. But the eagle avoids rain by flying above the clouds.
Problems are common, but attitude makes the difference! ”

Result:

Thus the C program for file copying is executed and output is verified.

Dr. R. Madhan Mohan, Dept. of Computer Science and Engineering, FEAT, AU

106

Das könnte Ihnen auch gefallen