You are on page 1of 66

UNIVERSITY OF ENGINEERING & TECHNOLOGY, PESHAWAR

MARDAN CAMPUS

LAB MANUAL
Computer Programming

Prepared By: Engr. Sadia Jabeen Siddiqi

Telecommunication Engineering Department


Lab Manual for C Programming

Table of Contents
Lab Exercise#1: Title: Introduction to C Programming Language……………………………4

Lab Exercise#2: Title: Taking Input at Run-Time……………………………………………………..9

Lab Exercise# 3: Title: Conditional Statements (If/Else)…………………………………………14

Lab Exercise# 4: Title: Nested IF/Else Algorithms…………………………………………………..18

Lab Exercise# 5: Title: For Loops in C Programming……………………………………………….20

Lab Exercise# 6: Title: Decision Making in C Using Swithc/Case Statements…………. 24

Lab Exercise# 7: Title: While Loops in C Programming……………………………………………29

Lab Exercise# 8: Title: Programming in C Using Do-While Loops…………………………….32

Lab Exercise# 9: Title: Built-In Functions in C………………………………………………………….36

Lab Exercise# 10: Title: User-Defined Functions in C………………………………………………..41

Lab Exercise# 11: Title: More on User-Defined Functions…………………………………………45

Lab Exercise# 12: Title: Arrays in C Programming……………………………………………………..48

Lab Exercise# 13: Title: Array Search Algorithms………………………………………………………55

Lab Exercise# 14: Title: Strings in C Programming…………………………………………………….58

Lab Exercise# 15: Title: Pointer Basics………………………………………………………………………64

3
Lab Manual for C Programming

Lab Exercise #1
Title: Introduction to the C Programming Language

Previous Knowledge Review:

 What is Computer Programming?

 What is special about the C programming language?

 Difference between C and C++ programming languages.

Basic Ingredients for Every Program:

 The pre-processor directives (Standard Library Headers, Macros)

 Terminators at the end of statements ;

 // Comments

 The main() function

 Clrscr() function

 Getch() function

Flowcharts:
Flowchart is a diagrammatic representation of an algorithm. Flowcharts are very helpful in writing
program and explaining program to others.

Symbols Used In Flowchart


Different symbols are used for different states in flowchart, For example: Input/Output and decision
making has different symbols. The table below describes all the symbols that are used in making
flowchart

SYMBOL PURPOSE DESCRIPTION

Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Processing Used for arithmetic operations and data-manipulations.

4
Lab Manual for C Programming

Used to represent the operation in which there are two


Decision
alternatives, true and false.

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing one


Process/Function processing task.

An Example of flowcharts in programming

Draw a flowchart to add two numbers entered by user.

5
Lab Manual for C Programming

Write down the C program for the program flow given above and attach a screenshot of the
output.

Beginner's Basic Programs:

Task 1: Write a C program to find area of a rectangle.


Flowchart:

START

READ
LENGTH &
BREADTH

CALCULATE
AREA A = L*B

DISPLAY
AREA

STOP

6
Lab Manual for C Programming

Program:

/* Header Files */
#include<stdio.h>
#include<conio.h>
void main()
{
int length=0, breadth=0;
int area=0;
clrscr();
printf("Enter the length and breadth of a rectangle");
scanf("%d%d", &length,&breadth);
area=length * breadth;
printf("Area of the Rectangle : %d", area);
getch();
}

Output:
Enter the length and breadth of a rectangle
4
5
Area of the Rectangle : 20

Task 2: Write a C program to find area and circumference of a circle by defining the value of
PI.

Flowchart

7
Lab Manual for C Programming

START

DEFINE VALUE
OF PI

READ VALUE
OF RADIUS 'R'

CALCULATE
AREA A =

CALCULATE C
=2

DISPLAY A &
C

STOP

Program

/* Header Files */
#include<stdio.h>
#include<conio.h>
#define PI 3.147
void main( )
{
float radius=0;
float area=0, circumf=0;
clrscr();
printf("Enter the radius of the Circle");
scanf("%f", &radius);
area = PI * radius * radius;
circumf = 2 * PI * radius;
printf("\nArea of the Circle : %f\n", area);
printf("Circumference of the Circle : %f", circumf);

8
Lab Manual for C Programming

getch();
}

Output:

Enter the radius of the Circle

6.5
Area of the Circle : 132.728
Circumference of the Circle : 40.839

9
Lab Manual for C Programming

Lab Exercise #2

Title: Taking Input at Run Time

Introduction to the scanf() function

The scanf function allows you to accept input from standard in, which for us is generally the keyboard.
The scanf function can do a lot of different things, but it is generally unreliable unless used in the
simplest ways. It is unreliable because it does not handle human errors very well. But for simple
programs it is good enough and easy-to-use. The simplest application of scanf looks like this:

scanf("%d", &b);

The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is
printf, so b must be declared as an int) and place that value into b.

The scanf function uses the same placeholders as printf:

 int uses %d

 float uses %f

 char uses %c

 character strings (discussed later) use %s

You MUST put & in front of the variable used in scanf. The reason why will become clear once you learn
about pointers.

10
Lab Manual for C Programming

Task1: Write a C program that takes two numbers as input from the user and displays their
sum.
Flowchart:

11
Lab Manual for C Programming

Task2: Write a C program to find area of a rectangle.


Flowchart:

START

Printf("plz enter
length & breadth")
Scanf("%d \n %d",
&l, &b)

CALCULATE
AREA A = L*B

DISPLAY
AREA

STOP

12
Lab Manual for C Programming

Task 3: Write a C program to find area and circumference of a circle by defining the value of
PI.
Flowchart

START

DEFINE VALUE
OF PI

READ VALUE
OF RADIUS 'R'

CALCULATE
AREA A =

CALCULATE C
=2

DISPLAY A &
C

STOP

13
Lab Manual for C Programming

Lab Exercise# 3
Title: Conditional Statements (If/ Else)

Introduction
C programming provides two styles of flow control:

 Branching

 Looping

Branching is deciding what actions to take and looping is deciding how many times to take a certain
action. Branching is the topic under consideration and practice for today's tasks; while looping will be
dealt with in the upcoming exercises.

Branching/ Conditional Statements:


Branching is so called because the program chooses to follow one branch or another.

if statement:
This is the simplest form of the branching statements.

14
Lab Manual for C Programming

Task#1: Write a C program to find out if a number entered by the user, is positive or negative
number.
Flowchart:

START

READ ONE
NUMBER

TRUE FALSE
IS
NUMBER
>= 0?

WRITE WRITE
"NUMBER IS "NUMBER IS
POSITIVE" NEGATIVE"

STOP

15
Lab Manual for C Programming

Task 2: Write a C program that finds out whether a number is even or odd.
Flowchart:

START

READ A NUM

TRUE IS FALSE
NUM%2
= 0?

WRITE "IT'S WRITE "IT'S


AN EVEN AN ODD
NUMBER" NUMBER"

STOP

16
Lab Manual for C Programming

Task# 3: Write a program that reads the three sides of a triangle and tells the type of
triangle.
Flowchart:

START

READ THREE
SIDES A,B,C OF
TRIANGLE

IS A=B and YES WRITE


B=C and "TRIANGLE IS
C=A? EQUILATERAL"

NO

IS (A=B OR A=C)
YES WRITE
OR
(B=A OR B=C) "TRIANGLE IS
OR
(C=A OR C=B) ?
ISCOSCELES"

NO

WRITE
"TRIANGLE IS
SCALENE"

STOP

17
Lab Manual for C Programming

Lab Exercise # 4
Title: Nested If/Else Algorithms

Introduction:
Getting more involved in C programming, you will find out that you have to deal with problems that
require extensive logical reasoning and decision making. For this, at times you need to apply conditional
logic within an already applied if/else structure.

This will be illustrated with the help of the following tasks, developing the logic of which will help you
understand the phenomenon.

Task 1: Write a C Program to find the biggest of three numbers.


Flowchart:

START

READ THREE
NUMBERS A, B & C

NO NO YES YES
B>C A>B A>C
? ? ?

YES NO

WRITE WRITE
"B is greatest" "A is greatest"

WRITE WRITE
"C is greatest" "C is greatest"

END

18
Lab Manual for C Programming

Task 2: Write a C program to find grade based on percentage of 5 subjects.


Flowchart:

START

READ MARKS OF 5
SUBJECTS

Perc = (S1+S2+S3+S4+S5)* 100/500

DISPLAY
PERCENTAGE

YES
WRITE
IS perc>= 90?
"A+ Grade"
?
NO
YES WRITE
IS perc>= 85?
"A Grade"
?
NO
YES
WRITE
IS perc>= 70?
"B Grade"
?
NO
YES
WRITE
IS perc>= 60?
"C Grade"
?

YES
WRITE
IS perc>= 50?
"D Grade"
?
NO

WRITE
"FAIL !"

END

19
Lab Manual for C Programming

Lab Exercise # 5
Title: For Loops in C Programming

Introduction:

Loops cause program to execute the certain block of code repeatedly until test condition is false. Loops
are used in performing repetitive task in programming. Consider these scenarios:

 You want to execute some code/s 100 times.


 You want to execute some code/s certain number of times depending upon input from user.

These types of task can be solved in programming using loops.

There are 3 types of loops in C programming:

1. for loop
2. while loop
3. do...while loop

for Loop Syntax


for(initialization statement; test expression; update statement) {
code/s to be executed;
}

20
Lab Manual for C Programming

Task1: Take your name and roll number as inputs and display them 7 times on the screen
using for loop.
Flowchart:

START

i=0
char name[10]
int roll_no

READ name &


roll_no

DISPLAY name and


roll_no

i++

YES
IS
i < 7?

NO

END

21
Lab Manual for C Programming

Task 2: Display the first ten positive integers, using for loop.
Flowchart:

START

int i = 1

DISPLAY i

i++

YES
IS
i <= 10?

NO

END

22
Lab Manual for C Programming

Task 3: Write a program that calculates the factorial of a number.


Flowchart:

START

int i = 1
int fact = 1
int N

READ N

Fact = fact* i

i++

IS YES
i <= N?

NO

DISPLAY fact

END

23
Lab Manual for C Programming

Lab Exercise # 6
Title: Decision-Making in C using Switch-Case Statements

Introduction:
The switch and case statements help control complex conditional and branching operations.
The switch statement transfers control to a statement within its body.
Control passes to the statement whose case constant-expression matches the value of switch
( expression ). The switch statement can include any number of case instances, but no two case
constants within the same switch statement can have the same value. Execution of the statement body
begins at the selected statement and proceeds until the end of the body or until a break statement
transfers control out of the body.

Use of the switch statement usually looks something like this:


switch ( expression )
{
declarations
.
.
.
case constant-expression :
statements executed if the expression equals the
value of this constant-expression
.
.
.
break;
default :
statements executed if expression does not equal
any case constant-expression
}

24
Lab Manual for C Programming

Task1: Write a C program to perform a desired arithmetic operation using switch statement
and declaring choice as char data type.
Flowchart:

START

READ 2
NUMBERS A & B

READ OPCODE
(+ for addition, - for
subtraction, * for
multiplication, / for
division)

+ /
OPCODE

- *
YES
RESULT= B=0
A +B ?
RESULT= RESULT=
NO
A-B A *B
RESULT=
A/B
WRITE
"RESULT"
WRITE
"ERROR:
END
Denominator is 0"

25
Lab Manual for C Programming

Task 2: Write a C program to find roots of a quadratic equation using switch.


Flowchart:

START

READ a,b and c

NO YES
disc =
0?

YES flag = 0
disc >
0?

NO
flag = 1

flag = 2

26
Lab Manual for C Programming

Flag=?

1
0
2

√ ⁄ real = -b/2a root1 = -b/2a

√ ⁄ root2 = root1
√ ⁄

DISPLAY
root1 and root2

END

27
Lab Manual for C Programming

Task 3: Write a C program to find area of a triangle/square/circle using switch


statement.
Flowchart:

START

DECLARE radius, length, base


and hieght

READ choice
(1 for area of triangle
2 for area of square
3 for area of circle)

1 Choice
2
?
READ READ
3
Base & hieght length
READ
radius
Area =
(1/2)*base*hieght Area = pi*radius*radius
Area = pi*radius*radius

DISPLAY
"Area of DISPLAY
DISPLAY "Area of Circle"
Triangle"
"Area of Circle"

END

28
Lab Manual for C Programming

Lab Exercise # 7
Title: While Loops in C Programming

Introduction:
while (test expression) {

statement/s to be executed.

The whi l e loop checks whether the test expression is true or not. If it is true, code/s inside the body
of while loop is executed,that is, code/s inside the braces { } are executed. Then again the test
expression is checked whether test expression is true or not. This process continues until the test
expression becomes false.

29
Lab Manual for C Programming

Task 1: Write a c program that uses while loop to find the factorial of a number.
Flowchart:

START

Fact = 1

READ
N

i =N

i >0
NO
?

YES

Fact = fact * i
i--

WRITE
"fact"

STOP

30
Lab Manual for C Programming

Task 2: Convert the given for-loop code to while-loop code.

// a program to show the nested for loops


#include <stdio.h>
int main()
{
// variables for counter…
int i, j;
// outer loop, execute this first...
// for every i iteration, execute the inner loop
for(i=15; i>0;)
{
// display i==
printf("%d==", i);
// then, execute inner loop with loop index j,
// the initial value of j is i - 1
for(j=i-1; j>0; )
{
// display #
printf("#");
// decrement j by 1 until j>10, i.e j = 9
j = j - 1;
}
// go to new line, new row
printf("\n");
// decrement i by 1, repeat until i > 0 that is i =
1
i = i - 1;
}
return 0;
}

31
Lab Manual for C Programming

Lab Exercise 8
Title: Programming in C with Do-While Loops

Introduction:
In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in
while loops, test expression is checked at first but, in do...while loop code is executed at first then the
condition is checked. So, the code are executed at least once in do...while loops.

do {

some code/s;

while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s
inside body of do are executed again and the process continues until test expression becomes
false(zero).

Notice, there is semicolon in the end of while (); in do...while loop.

32
Lab Manual for C Programming

Task 1: Write a C program to enter all numbers entered by a user until user enters 0.
Flowchart:

START

int sum = 0
int num

READ
num

Sum+= num

num YES

0?

NO

WRITE
"sum"

STOP

33
Lab Manual for C Programming

Task 2:
Write a program to find the HCF and LCM of two numbers.
Algorithm:

HCF:
In mathematics, the greatest common divisor (gcd), also known as the greatest common factor (gcf),
or highest common factor (hcf), of two or more integers (at least one of which is not zero), is the largest
positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4.

LCM:
In arithmetic and number theory, the least common multiple (also called the lowest common
multiple or smallest common multiple) of two integers a and b, usually denoted by LCM(a, b), is the
smallest positive integer that is divisible by both a and b

Flowchart:

START

READ 2
NUMBERS A & B

TEMP1 = A
TEMP2 = B

REM = A%B
A =B
B = REM

34
Lab Manual for C Programming

REM > 0? YES

NO

WRITE
"HCF = A"

LCM =
(TEMP1*TEMP2)/A

WRITE
"LCM"

STOP

35
Lab Manual for C Programming

Lab Exercise # 9
Title: Built-in Functions in C

Introduction:
#include<ctype.h>

Task1: Write a C program to demonstrate use of Size of operator.

START

int a
float b
char c
double d
long int q

DISPLAY
SIZEOF a

DISPLAY
SIZEOF b

DISPLAY
SIZEOF c

DISPLAY
SIZEOF d

DISPLAY
SIZEOF q

STOP

36
Lab Manual for C Programming

Task 2: Write a C program to find whether a entered character is a number or digit using
both ASCII values and built-in functions.

START

char ch

READ ch

YES
('a' <= ch <= 'z')
OR WRITE
('A' <= ch <= 'Z') "ch is alphabet"
?

NO

YES WRITE
48 <= ch <= 56
? "ch is number"

NO

WRITE
"Invalid Character"

STOP

37
Lab Manual for C Programming

With Built-in Functions of isalpha() and isdigit()


Flowchart:

START

char ch

READ ch

YES
Isalpha(ch) > 0 WRITE
? "ch is alphabet"

NO

YES WRITE
Isdigit(ch) < 0
? "ch is number"

NO

WRITE
"Invalid Character"

STOP

38
Lab Manual for C Programming

Task 3: Write a C program to convert a lower case alphabet to uppercase and vice-versa
using both ASCII values and built-in functions.
Flowchart:

START

char ch

READ ch

YES
('a' <= ch <= 'z')
ch = ch - 32
?

WRITE
"Uppercase: ch"

NO

('A' <= ch <= 'Z')


ch = ch + 32
?

NO WRITE
"Lowercase: ch"
WRITE
"Invalid Character"

STOP

39
Lab Manual for C Programming

With Built-in Functions of islower() and isupper()


Flowchart:

START

char ch

READ ch

YES WRITE
Islower(ch)
"Uppercase",
? toupper(ch)

NO

WRITE
YES
Isdigit(ch) < 0 "Lowercase",
? tolower(ch)

NO

WRITE
"Invalid Character"

STOP

40
Lab Manual for C Programming

Lab Exercise # 10
Title: User-Defined Functions in C

Introduction:
Function prototype (declaration):
Every function in C programming should be declared before they are used. These type of declaration are
also called function prototype. Function prototype gives compiler information about function name,
type of arguments to be passed and return type.

Syntax of function prototype


return_type function_name(type(1) argument(1),....,type(n) argument(n));

In the example, int add(int a, int b); is a function prototype which provides following information
to the compiler:

 name of the function is add()

 return type of the function is int.

 two arguments of type int are passed to function.

Function prototype are not needed if user-definition function is written before main() function.

Function call
Control of the program cannot be transferred to user-defined function unless it is called (invoked).

Syntax of function call


function_name(argument(1),....argument(n));

In the above example, function call is made using statement add(num1,num2); from main(). This make
the control of program jump from that statement to function definition and executes the codes inside
that function.

Function definition
Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{

Body of the function

41
Lab Manual for C Programming

Example:

/*Program to demonstrate the working of user defined function*/


#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}

42
Lab Manual for C Programming

Task 1: Write a program with a function named swap() that takes input in two variables a
and b, and swaps their values.
Flowchart:

START

DECLARE void swap()

READ a, b

DISPLAY a, b
BEFORE
SWAPPING

swap(a,b)

DEFINE void swap()

END

43
Lab Manual for C Programming

Definition of the function swap()

START

int temp

temp = num2
num2 = num1
num1 = temp

DISPLAY a, b
AFTER
SWAPPING

STOP

44
Lab Manual for C Programming

Lab Exercise # 11
Title: More on User Defined Functions

Task 1: Write a C program in which define a function that returns greater of two numbers
inputted by user.
Flowchart:

START

DECLARE int larger(int a, int b)

Int I,j,k

READ i,j

Call
Larger(int a, int b)

DISPLAY k

END

45
Lab Manual for C Programming

Flowchart for larger(int a, int b) function definition

Larger(a,b)

YES
Is
RETURN a
a> b?

NO

RETURN b

END

Task 2: Write a C program that uses pre-defined functions to convert celcius temperateure to
farenheit and vice versa.

The functions shall be able to perform the following calculations on the temperatures read as F in
farehnheit and C in celcius.

 Separate functions shall be made for the two conversions.

For conversion:
F=9.0/5.0*c+32
C=5.0/9.0*(F-32)

Algorithm:

1. Read the temperature in degree Centigrade.

2. Convert the Centigrade to Fahrenheit using the conversion function you defined outside the
main block.

3. Print the Celsius and Fahrenheit value.

4. Read the temperature in degree Fahrenheit.

46
Lab Manual for C Programming

5. Convert the Fahrenheit to Centigrade using the second function.

6. Print the Fahrenheit and Celsius value.

7. Stop

Task 3: Special Type of Functions - Recursive Functions

Write a program to calculate the factorial of a number using recursive functions.

Flowchart:

START

Factorial (N)
READ N

Call
F = factorial(N) Is RETURN
N<2? N*factorial(N-1)

B RETURN N

DISPLAY F
B

END

47
Lab Manual for C Programming

Lab Exercise # 12
Title: Arrays in C Programming

Introduction:
There are times while writing C code, you may want to store multiple items of same type as contiguous
bytes in memory so that searching and sorting of items becomes easy. For example:

 Storing a string that contains series of characters, like storing a name in memory.

 Storing multiple strings, like storing multiple names.

C programming language provides the concept of arrays to help you with these scenarios. An array is a
collection of same type of elements which are sheltered under a common name. An array can be
visualised as a row in a table, whose each successive block can be thought of as memory bytes
containing one element. Look at the figure below:

An Array of four elements:

+===================================================+
| elem1 | elem2 | elem3 | elem4 |
+===================================================+
The number of 8 bit bytes that each element occupies depends on the type of array. If type of array is
‘char’ then it means the array stores character elements. Since each character occupies one byte so
elements of a character array occupy one byte each.

An array is defined as following :

<type-of-array> <name-of-array> [<number of elements in array>];

For example, an array of five characters can be defined as:

char arr[5];

An array can be initialized in many ways as shown in the code -snippets below.

Initializing each element separately

int arr[10];

int i = 0;

for(i=0;i<sizeof(arr);i++)

48
Lab Manual for C Programming

arr[i] = i; // Initializing each element seperately

Initializing array at the time of declaration

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

Initializing array with a string (Method 1):

Strings in C language are nothing but a series of characters followed by a null byte. So to store a string,
we need an array of characters followed by a null byte. This makes the initialization of strings a bit
different. Let us take a look:

Since strings are nothing but a series of characters so the array containing a string will be containing
characters

char arr[] = {'c','o','d','e','\0'};

In the above declaration/initialization, we have initialized array with a series of character followed by a
‘\0′ (null) byte. The null byte is required as a terminating byte when string is read as a whole.

Initializing array with a string (Method 2):

char arr[] = "code";

Now we know how to declare and initialize an array. Let's understand, how to access array elements. An
array element is accessed as:

int arr[10];

int i = 0;

for(i=0;i<sizeof(arr);i++)

arr[i] = i; // Initializing each element separately

int j = arr[5]; // Accessing the 6th element of integer array arr and assigning
its value to integer 'j'.

As we can see above, the 6th element of array is accessed as ‘arr*5+‘.

Note that for an array declared as int arr[5]. The five values are represented as: arr[0] arr[1] arr[2] arr[3]
arr[4] and not arr[1] arr[2] arr[3] arr[4] arr[5]

The first element of array always has a subscript of ’0′

49
Lab Manual for C Programming

Task 1: Write a program that declares an array of 5 integers and displays the elements of the
array using a loop.
Flowchart:

START

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

For (i=0; i<=5; i++)

DISPLAY
"Element I of array is
arr[i]"

END

Task 2: Write a C program that uses array and for loop and does the following jobs:
 Takes the size of the array

 Takes the values of array elements according to the size

 Displays the values back

 And Sums the values and displays the result

The code should have an output like this:


Enter the size of the array
6
Enter 6 elements into Array
5 8 46 2 1

50
Lab Manual for C Programming

Array Elements are :


5 8 46 2 1
Sum of Array Elements : 26

Task 3: Read 3 subject marks of 4 students. Write a program to calculate and display the
total marks of each student. Use a 2D (two-dimensional) array to

Algorithm:
1. Define main Function.
2. Declare all variables in specified data type.
3. Get the details for 4 students. R.no & Name of the students using a
single dimensional array.
4. And a inner for loop is to be used to get 3 marks of each students.
5. Calculate the total marks and store it in a 2-D array variable marks[i][j];
6. Display all the details of 4 students.

The inputs/ out puts should be like this:


Student Detail No : 0
Enter the Student Rno 1001
Enter the Student Name abc
Enter the Mark 0 89
Enter the Mark 1 78
Enter the Mark 2 82
Student Detail No : 1
Enter the Student Rno 1002
Enter the Student Name xyz
Enter the Mark 0 76
Enter the Mark 1 80
Enter the Mark 2 83
Student Detail No : 2
Enter the Student Rno 1003
Enter the Student Name rst
Enter the Mark 0 89
Enter the Mark 1 90
Enter the Mark 2 91
Student Detail No : 3
Enter the Student Rno 1004
Enter the Student Name pqr
Enter the Mark 0 86
Enter the Mark 1 56
Enter the Mark 2 73
--------------OUTPUT------------------
Student No 0
Rno : 1001

51
Lab Manual for C Programming

Name : abc
Sub0 89
Sub1 78
Sub2 82
Total Marks :249
Average :83.00
Student No 1
Rno : 1002
Name : xyz
Sub0 76
Sub1 80
Sub2 83
Total Marks :239
Average :79.66
Student No 2
Rno : 1003
Name : rst
Sub0 89
Sub1 90
Sub2 91
Total Marks :270
Average :90.00
Student No 3
Rno : 1004
Name : pqr
Sub0 86
Sub1 56
Sub2 73
Total Marks :215
Average :71.66

Flowchart:

52
Lab Manual for C Programming

START

For i=0 to 3

Sum[1] = 0

READ regno[i],
name[i]

For j= 0 to 3

READ mark[i][j]

Sum = sum + mark[i][j]

Avg = sum/10

For i=0 to 3

DISPLAY regno[i]

A
C B

53
Lab Manual for C Programming

C A B

For j= 0 to 3

PRINT mark[i][j]

PRINT sum[i], avg[i]

END

54
Lab Manual for C Programming

Lab Exercise # 13
Title: Array Search Algorithms

Introduction:
Linear Search:
is used to find whether a given number is present in an array and if it is present then at what
location it occurs. It is also known as sequential search. It is very simple and works as follows:
We keep on comparing each element with the element to search until the desired element is
found or list ends.
Linear Search:
Binary Search:
A binary search or half-interval search algorithm finds the position of a specified input value (the
search "key") within an array sorted by key value. For binary search, the array should be
arranged in ascending or descending order. In each step, the algorithm compares the search key
value with the key value of the middle element of the array. If the keys match, then a matching
element has been found and its index, or position, is returned. Otherwise, if the search key is
less than the middle element's key, then the algorithm repeats its action on the sub-array to the
left of the middle element or, if the search key is greater, on the sub-array to the right. If the
remaining array to be searched is empty, then the key cannot be found in the array and a special
"not found" indication is returned.

Task 1: Linear Search in an Array in C


Flowchart:

55
Lab Manual for C Programming

START

B
Int arr[20], int i=0, size = 0,
key = 0, flag =0

Is NO PRINT
"ELEMENT
Flag NOT
READ ARRAY SIZE
== 1 ? FOUND"

For I = 0 to size YES

PRINT "KEY FOUND


READ ARRAY AT POSITION i"
ELEMENTS

READ IN KEY, THE END


ELEMENT TO SEARCH

FOR I = 0 to size

NO YES
Is Flag = 1
Key == arr[i] ?

56
Lab Manual for C Programming

Binary Search:
Implement the Binary Search technique on an array using the following steps:

START
B

Int arr[20], I = 0, size =0,


key, flag, high, low, mid IS HIGH = MID
KEY < +1
ARR[MID] ?

READ ARRAY SIZE &


ELEMENTS

IS
SHOW THE ELEMENTS
KEY == FLAG = 1
READ ELEMENT TO
ARR[MID] ?
SEARCH: KEY

HIGH = SIZE -1 PRINT


LOW = 0 ELEMENT
IS FOUND:
FLAG KEY AT
== 1 POSITION
While (low < high) ? MID + 1

MID = (HIGH + LOW) / 2


PRINT
ELEMENT
NOT
FOUND
IS
KEY > LOW =
ARR[MID]? MID + 1

END

57
Lab Manual for C Programming

Lab Exercise # 14
Title: Strings in C Programming

Introduction:

 string: array of characters terminated by NULL character


 string in/output: printf("%s",S), scanf("%s",S)
 string.h: collection of functions for string manipulation
 no standard operators for string assignment and comparisons! (remember: strings are arrays!)

Task 1: To Caluclate the number of vowels in a string


Aim:
Write a C program to find the number of vowels present in the string.
[Assume your string contains both uppercase and lowercase characters]

Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define main Function & Declare all variables required.
4. Assign the vowels to an array variable A* + = “aeiouAEIOU”
5. Get the String and store it in a variable in a nested for Loop
6. Check the given string is equal to the value assigned in the array variable.
7. This is done until the string becomes NULL(\o)
8. If the character in a string is equal increment the COUNT variable by 1.
9. Print the Count variable which gives the result.

Flowchart:

58
Lab Manual for C Programming

START

a[] = {"aeiouAEIOU"}
count = 0

READ STRING STR

len = strlen (str)

For i=0 to len-1

FALSE
For j =0 to 9

TRUE
FALSE
IS
Str[1] = a[j]
?

TRUE

Count ++
A

PRINT THE
COUNT

END

59
Lab Manual for C Programming

Task 2: Write a program that finds out whether a string is a palindrome or not.

A string is said to be a palindrome if the string read from left to right is equal to the string read from
right to left. For example, ignoring the difference between uppercase and lowercase letters, the
string"iTopiNonAvevanoNipoti" is a palindrome, while the string "iGattiNonAvevanoCugini" is not so.

The following is an inductive characterization of a palindrome string:

 The empty string is a palindrome;


 A string constituted only by a single character is a palindrome;
 A string c s d is a palindrome, if s is a palindrome and c is a character equal to d;
 Nothing else is a palindrome.

Algorithm:
1. Define main Function & Declare all variables required.
2. Let flag =0
3. Read a String and Find the Length of the String as n.
4. Using a for loop check the character str[i] and str[n-1-i].
5. if equal continue the for loop until i=n/2
6. else set flag=1 and break the for loop.
7. If flag =0, Print “The string is Palindrome”
8. Else, Print “The string is not palindrome”
9. Stop

60
Lab Manual for C Programming

Flowchart:

START

Flag = 0

READ STRING

N = length (str)

For i=0 to N/2

FALSE
IS
Str{i] !=
str[n-1-i]

TRUE

Flag = 1

FALSE PRINT
IS "NOT
Flag = 0? PALINDROME"

TRUE

PRINT
"PALINDROME
"

END

61
Lab Manual for C Programming

Task 3: Read a string, which consists of both lower case characters and upper case
characters. Convert the lowercase character into upper case and vice versa. Display the new
string

Algorithm:
1. Define main Function & Declare all variables required.
2. Read a String and Find the Length of the String.
3. Check the characters ASCII value whether it lies between 97 and 122.
4. If the Condition is true
5. Change the ASCII value of the character by subtracting 32
6. Else check the ASCII value lies between 65 and 90
7. If the condition becomes true
8. Add 32 to the value for the character.
9. Repeat the step 4 & step 5 until the length of the string becomes NULL.
10. Print the result.
11. Stop.

Flowchart:

62
Lab Manual for C Programming

START

READ STRING STR

Len = strlen(str)

FALSE
For i=0 to len-1
TRUE

IS
FALSE
Str[i] >= 65
&&
Str[i] <= 90

TRUE
IS FALSE
Str[i] = str[i] + 32 Str[i] >= 97
A &&
Str[i] <= 122

TRUE

Str[i] = str[i] - 32

PRINT THE
STTRING

END

63
Lab Manual for C Programming

Lab Exercise # 15
Title: Pointer Basics

Introduction:
To better understand pointers, it sometimes helps to compare a “normal variable” with a pointer.
When a “normal variable” is declared, memory is claimed for that variable. Let’s say you declare an
integer variable MYVAR. Four bytes of memory is set aside for that variable. The location in memory is
known by the name MYVAR. At the machine level that location has a memory address.

A pointer differs in the way that a pointer is a variable that points to another variable. A pointer holds
the memory address of that variable. That variable contains a value. Pointers are also called address
variables because they contain the addresses of other variables.
Example: We have a piece of memory with a start address of 0×2000. That piece of memory contains a
value and is named MYEXAMPLE.
(This is in fact a variable). We also have a pointer MYPOINT. In this case, our pointer MYPOINT contains
the address 0×2000. This is the address of MYEXAMPLE so we say MYPOINT points to MYEXAMPLE. So
there is the pointer and the value pointed to. (You can use a pointer in a certain way to get the value at
the address to which the pointer points). Many novice programmers get pointers and their contents
confused.
So from now on it's advisable that you start every pointer name with the extension ptr_ . (for example:
ptr_MYPOINT).

Pointer Declaration and types:


To declare a pointer you have to put an * in front of its name. A pointer can be typed or untyped. (A
typed pointer points to a particular variable type such as an integer. An untyped pointer points to any
data type).
See the following example of a declaration of a typed pointer and an untyped pointer:

// Typed/ untyped pointers


#include <stdio.h>
int main()
{
int *ptr_A; /* A typed pointer */
void *ptr_B; /* An untyped pointer */
return 0;
}

The &/ Address Operator:


Put the address of an integer into a “pointer to an integer” by using the & operator (address operator)
in front of the integer, to get the integer’s address.

Let’s take a look at an example:

int x;
int *ptr_p;

64
Lab Manual for C Programming

x =5;
ptr_p = &x;

Note: The integer x contains the value 5 on a specific address. The address of the integer x is copied in
the pointer ptr_p. So ptr_p points to the address of x. In short: ptr_p = &x; means, “Assign to ptr_p the
address of x.”

Pointer Dereferencing:
To access the value of the integer that is being pointed to, you have to dereference the pointer. The *
is used to dereference a pointer.

Take a look at the following example:

// Pointer Dereferencing
x = 5;
ptr_p = &x;
y = *ptr_p;
printf("%d\n", y);

Note: The integer x has a value of five. The pointer ptr_p gets the address of integer x.
The value pointed to is *ptr_p. (in this case five). So the integer y now contains the value of five.

Task 1:
Write a program to illustrate use of pointers in expressions.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p, *q;
int m, n;
int res, res1;
clrscr();
printf("\nEnter two numbers");
scanf("%d%d",&m,&n);
p = &m;
q = &n;
res = (m + n) * (m * n);
printf("Result (using numbers) : %d\n",res);
res1 = (*p + *q) * (*p * *q);
printf("Result (using pointers) : %d\n",res1);
getch();
}
Output:

65
Lab Manual for C Programming

Enter two numbers


46
Result (using numbers) : 240
Result (using pointers) : 240

Task 2: Write a program that uses an int pointer and an int variable and displays the
variable's address.

Task 3: Write a program that takes user input into a variable and displays what the user
entered, via the variable's address.

66

You might also like