Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
2K views

Programming For Problem Solving Lab Manual

The document provides information about programming environments for C programming such as Turbo C, GCC, and CodeBlocks IDE. It discusses the features of Turbo C including its integrated development environment, support for memory models and code optimization. It also describes how to create, edit, compile and execute C programs using GCC in Linux and the features of CodeBlocks IDE as a cross-platform C/C++ integrated development environment.

Uploaded by

kiran koda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views

Programming For Problem Solving Lab Manual

The document provides information about programming environments for C programming such as Turbo C, GCC, and CodeBlocks IDE. It discusses the features of Turbo C including its integrated development environment, support for memory models and code optimization. It also describes how to create, edit, compile and execute C programs using GCC in Linux and the features of CodeBlocks IDE as a cross-platform C/C++ integrated development environment.

Uploaded by

kiran koda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 149

PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

PROGRAMMING FOR
PROBLEM SOLVING LAB
MANUAL
LAB MANUAL
A2 REGULATION
(FROM 2019-2020 BATCH ONWARDS)

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS)


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

AUTHORS: Mr.P.R.S.Naidu - CSE

Dr.M.Chandra Sekhar - CSE

Mr.K.V.Subba Raju - CSE

Mrs.M.Priyanka - CSE

Ms.K.Prathyusha - CSE

Mrs.M.B.Rani - CSE
PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

I - SEMESTER L T P C
A2CIL001 PROGRAMMING FOR PROBLEM SOLVING LAB 0 0 3 2
Total Contact Hours: 56 (14 weeks)

COURSE OBJECTIVES:
1. To use basic data types, operators, expressions and expression evaluation
mechanisms using C Programming Language.
2. To implement control flow constructs in C Programming Language and
understands the syntax, semantics and usability contexts of these different
constructs.
3. To develop composite data types in C and constructs available to develop their data-
types, utilize them to model things and dealing with data from and to external files.
4. To design programs with different variations of the constructs available for
practicing modular programming and understand the pros and cons of using
different variants and apply optimization.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 1


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

UNIT – I
WEEK-1
Objective: Getting familiar with the programming environment on the computer and
writing the first program.
i) Exposure towards Turbo C, gcc, Code Blocks IDE
Turbo C:
It was a software development tool for writing programs in the C language. As an IDE, it
included a source code editor, a fast compiler, a linker and an offline help file for
reference. Version 2 included a built-in debugger. Turbo C was a follow-up product to
Borland's Turbo Pascal, which had gained widespread use in educational institutions
because the Pascal language was suited for teaching programming to students.
Although Turbo C was initially developed by a different company, it shared a lot of
features with Turbo Pascal, namely, the look-and-feel of the interface and the various
programming and debugging tools included.
However, it was not as successful as Turbo Pascal because of competition from other C
products such as Microsoft C, Watcom C, Lattice C, etc. Nevertheless, Turbo C still had
the advantage in compile speed and price.
The first version was released on May 13, 1987, and it offered the first-ever edit-compile-
run environment for software development on IBM PCs. Turbo C was not originally
developed by Borland but was bought from Bob Jervis and was initially called Wizard C.
Turbo Pascal did not have pull-down menus before this time, and it was only on its fourth
version that it received a face lift to look like Turbo C.
Borland as a company no longer develops and sells these products, but Turbo C still lives
on as a free download from various online repositories, although it is really an old
technology without real technical support and is no longer viable for modern software
development. Turbo C eventually evolved into Turbo C++, then into Borland C++ and,
finally, into C++ Builder.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 2


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Turbo C features:

Inline assembly with full access to the C language symbolic structures and names -- This
allowed programmers to write some assembly language codes right into their programs
without the need for a separate assembler.
Support for all memory models -- This had to do with the segmented memory architecture
used by 16-bit processors of that era, where each segment was limited to 64 kilobytes (Kb).
The models were called tiny, small, medium, large and huge, which determined the size of
the data used by a program, as well as the size of the program itself. For example, with the
tiny model, both the data and the program must fit within a single 64-Kb segment. In the
small model, the data and the program each used a different 64- Kb segment. So in order to
create a program larger than 64 Kb or one that manipulates data larger than 64 Kb, the
medium, large and huge memory models had to be used. In contrast, 32-bit processors used
a flat memory model and did not have this limitation.
Speed or size optimization -- The compiler could be configured to produce an executable
program that was either fast or small in size, but not both.
Constant folding -- This feature allowed the Turbo C compiler to evaluate constant
expressions during compile time rather than during run time.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 3


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Short cut Keys in Turbo C:

1. F1 For Help
2. F2 Save
3. F3 Open
4. F4 Go to cursor
5. F5 Zoom
6. F6 Next
7. F7 Trace into
8. F8 Step over
9. F9 Make
10. F10 Menu
11. Alt+X Quit
12. Alt+Bksp Undo
13. Shift+Alt+Bksp Redo
14. Shift+Del Cut
15. Ctrl+Ins Copy
16. Shift+Ins Paste
17. Ctrl+Del Clear
18. Ctrl+L Search again
19. Alt+F7 Previous error
20. Alt+F8 Next error
21. Ctrl+F9 Run
22. Ctrl+F2 Program reset
23. Alt+F9 Compile
24. Alt+F4 Inspect
25. Ctrl+F4 Evaluate/Modify
26. Ctrl+F3 Call stack
27. Ctrl+F8 Toggle breakpoint
28. Ctrl+F5 Size/Move
29. Alt+F3 Close

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 4


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

30. Alt+F5 User screen


31. Alt+0 List all
32. Shift+F1 Index
33. Ctrl+F1 Topic search
34. Alt+F1 Previous topic
35. Ctrl+F7 Add watch
GCC:
The GNU Compiler Collection (GCC) is a compiler
(https://en.wikipedia.org/wiki/Compiler) system produced by the GNU Project
(https://en.wikipedia.org/wiki/GNU_Project) supporting various programming languages
(https://en.wikipedia.org wiki/ Programming_ language). GCC is a key component of the
GNU toolchain (https://en.wikipedia.org/wiki/GNU_toolchain) and the standard compiler
for most projects related to GNU (https://en.wikipedia.org/wiki/GNU) and Linux
(https://en.wikipedia. org/wiki/Linux), the most notable is the Linux kernel
(https://en.wikipedia.org/wiki/Linux_kernel). The Free Software Foundation
(https://en.wikipedia.org/wiki/Free_Software_Foundation) (FSF) distributes GCC under the
GNU General Public License
(https://en.wikipedia.org/wiki/GNU_General_Public_License)(GNUGPL). GCC has
played an important role in the growth of free software
(https://en.wikipedia.org/wiki/Free_software), as both a tool and an example.

When it was first released in 1987, GCC 1.0 was named the GNU C Compiler since it only
handled the C programming language (https://en.wikipedia.org/wiki/
C_(programming_language)). It was extended to compile C++ (https://en.wikipedia.org
/wiki/C%2B%2B) in December of that year. Front ends (https://en.wikipedia.org
/wiki/Compiler_frontend) were later developed for Objective-C

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 5


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Creating / Editing / Compiling and Executing C Programs in Linux:


Creating:

i. 1. Open any Text Editor like Vi/Emacs/Gedit from terminal

Ex: vi filename.c

ii. Enter the program in the file.

iii. Save the file: Go Last Line Mode (Esc + Shift :), type wq
Compiling:
Method 1:
$ gcc filename.c
If No syntactical errors it gives $ prompt.
If any syntactical errors are there in the program, it displays the errors.
Correct the errors by opening the file using vi filename.c
$
Method 2:
$ gcc –o filename filename.c
If No syntactical errors it gives $ prompt.
If any syntactical errors are there in the program, it displays the errors.
Correct the errors by opening the file using vi filename.c
$
Executing:
For Method 1:
$ ./a.out
For Method 2:
$ ./filename

Code Blocks IDE:


CodeBlocks is an open-source, cross-platform (Windows, Linux, MacOS), and free
C/C++ IDE. It supports many compilers, such as GNU GCC (MinGW and Cygwin) and
MS Visual C++. It supports interactive debugging (via GNU GDB or MS CDB).
CodeBlocks is surprisingly versatile, and in my opinion, much better than the Visual

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 6


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Studio suite. The mother site of CodeBlocks is www.codeblocks.org


(http://www.codeblocks. org/).
Code::Blocks is a free C, C++ and Fortran IDE built to meet the most demanding needs of
its users. It is designed to be very extensible and fully configurable.
Finally, an IDE with all the features you need, having a consistent look, feel and operation
across platforms. Built around a plugin framework, Code::Blocks can be extended with
plugins. Any kind of functionality can be added by installing/coding a plugin. For
instance, compiling and debugging functionality is already provided by plugins!

Writing Toy Programs (without Creating a Project):


To write toy programs (such as few-line simple programming exercises):
1. File ⇒ New ⇒ Empty File.
2. Enter (copy and paste) the following codes:
// First C++ program to say Hello #include <iostream>
using namespace std;
int main() {
cout << "Hello, world!" << endl; return 0;
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 7


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

1. Save the file as " Hello.cpp " in your project directory (e.g., " d:\project).
2. Build (Compile and Link): Select "Build" menu ⇒ Build (Ctrl-F9).
3. Run: Select "Build" menu ⇒ Run (Ctrl-F10).
The drawback is you cannot debug program without creating a project.
Writing Programs (under Project)
Other than the few-line toy programs, you shall create a project for each of your
application. A project contains related files such as source codes, header files, and relevant
resources. Also, under CodeBlocks, you can only debug your program under a project -
single-file program (in previous section) debugging is not supported.
1. File ⇒ New ⇒ Project... ⇒ Console Application ⇒ Go.
2. The "Console Application" wizard appears: Next Select "C++" ⇒ Next.
3. In "Project Title", enter " HelloProject ". In "Folder to create project in", set to
your working directory, e.g., " d:\project ". Accept the default for the rest ⇒ Next.
A project directory " HelloProject " will be created under " d:\project ", with a project
configuration filename of " HelloProject.cbp ". You could later create more projects
under this working directory " d:\project ".
In "Compiler" field, accept the defaults of "GNU GCC Compiler" ⇒ Finish.
4. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node "
HelloProject " ⇒
Expand "Source" node ⇒ Double-click " main.cpp ", which is a template program to
say "Hello, world!".
5. To build the program, select "Build" menu ⇒ Build.
6. To run the program, select "Build" menu ⇒ Run.
7. To create more source file or header file under the project: File ⇒ New File... ⇒
Select C/C++ source or C/C++ header. C++ ⇒ Next.
In "Filename with full path" ⇒ Click the "Navigate" (...) button to navigate to the
project directory and enter the new file name. Check both the "Debug" and "Release"
boxes (or "All") ⇒ Finish.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 8


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

ii. Familiarization of Editor - vi, OS Commands

Write different commands in vi editor.


Description/ Explanation:
Operating system (OS) command line interfaces are usually distinct programs supplied
with the operating system. A program that implements such a text interface is often called
a command-line interpreter, command processor or shell.
vi editor:
The default editor that comes with the UNIX operating system is called vi (visual editor).
The UNIX vi editor is a full screen editor and has two modes of operation:
Command mode commands which cause action to be taken on the file
Insert mode in which entered text is inserted into the file
vi always starts out in command mode. When you wish to move between the two modes,
keep these things in mind.
You can type i to enter the insert mode. If you wish to leave insert mode and return to the
command mode, hit the ESC key.
If you are not sure where you are, hit ESC a couple of times and that should put you back
in command mode.
A User can start using vi editor by using the commands like:
vi filename - Creates a new file if it does not exist, otherwise opens existing file
vi -R filename - Opens an existing file in read only mode
Commands of vi editor:
I - Insert text at the cursor
A - Append text at the end of the line
a - Append text after cursor
O - Open a new line of text above the cursor
o - Open a new line of text below the cursor
x - Delete a single character
dd - Delete an entire line
ndd - Delete n number of lines

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 9


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

d$ - Delete from cursor to end of line


yy - Copy a line in buffer
P - Paste text from buffer
nyy - Copy n number of lines to buffer
G - Go to last line of the file 1G - Go to first line in the file w - Move forward to
next word
b - Move backwards to next word
$ - Move to the end of line
OS Commands:
ls: ls is a command to list files in Unix and Unix-like operating systems.
The ls command lists all files in the directory that match the name. If name is left blank, it
will list all of the files in the directory.
ls with no option list files and directories in bare format where we won’t be able to view
details like file types, size, modified date and time, permission and links etc.

Syntax: ls [option] [names]


The most common options to reveal this information or change the list of files are:
-l - long format, displaying Unix file types, permissions, number of hard links, owner,
group, size, last-modified date and filename.
-f - do not sort. Useful for directories containing large numbers of files.
-F - appends a character revealing the nature of a file, for example, * for an executable, or /
for a directory. Regular files have no suffix.
-a - lists all files in the given directory, including those whose names start with "." (which are
hidden files in Unix). By default, these files are excluded from the list.
-R - recursively lists sub directories. The command ls -R / would therefore list all files.
-d - shows information about a symbolic link or directory, rather than about the link's target
or listing the contents of a directory.
-t - sort the list of files by modification time.
-h - print sizes in human readable format.
The cd command, which stands for "change directory", changes the shell's current working

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 10


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

directory. The cd command is one of the commands user will use the most at the command
line in Linux. It allows the user to change the working directory.
User use it to move around within the hierarchy of the file system.
Syntax: cd directory name
The pwd command prints the name of the working directory. pwd prints the full path name
of the current working directory.
Syntax: pwd
mkdir:
The mkdir command is used to create directories on a file system. If the specified directory
does not already exist, mkdir creates it.
Syntax: mkdir [option] directory_name(s)
This command has following options:
-m (mode) - Set file mode
-p (parent) - Create parent directories as necessary. When this option is used, no error is
reported if a specified directory already exists.
-v (verbose) - Verbose output; print a message for each created directory.
--help - Display a help message, and exit.
--version - Display version information, and exit.
The directory_name is the name of any directory that the user is asking mkdir to create. Any
number of directories can be created simultaneously.
cat:
The cat command is one of the most frequently used command in Linux/ Unix like
operating systems. The cat command allows us to create single or multiple files, view
contain of file, concatenate files and redirect output in terminal or files.
Syntax: cat [OPTIONS] [FILE]
To create a file syntax is : cat > filename
To view a file syntax is : cat filename
cat command has following options:
-e - $ is printed at the end of each line. This option must be used with -v.
-s - Suppress messages pertaining to files that do not exist.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 11


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

-t - Each tab will display as ^I and each form feed will display as ^L. This option
must be used with
-v.
-u - Output is printed as unbuffered.
-v - Display control characters and non-printing characters.
Some of the examples are:
cat file1.txt file2.txt - Reads the contents of file1.txt and file2.txt, and displays
them in order on the terminal screen.
cat file.txt > newfile.txt - Read the contents of file.txt and write them to
newfile.txt, overwriting anything newfile.txt previously contained. If newfile.txt
does not exist, it will be created.

cat file.txt >> another-file.txt - Read the contents of file.txt and append them to
the end of another-file.txt. If another-file.txt does not exist, it will be created.

cat -s file.txt - Display the contents of file.txt by omitting any repeated blank
lines.
cp: The cp command is used to make copies of files and directories.
Syntax: cp [OPTIONS] Source Destination
The cp command has the following options:
cp -a - archive files
cp -f - force copy by removing the destination file if needed
cp -i - interactive - ask before overwrite
cp -l - link files instead of copy cp -L - follow symbolic links cp -n - no file
overwrite
cp -R - recursive copy (including hidden files)
cp -u - update - copy when source is newer than destination
cp -v - verbose - print informative messages
Some of the examples are:
cpmain.c bak - Copy single file main.c to destination directory bak.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 12


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

cpmain.c def.h /home/usr/rapid/ - Copy 2 files main.c and def.h to destination


absolute path directory /home/usr/rapid/.
cp*.c bak - Copy all C files in current directory to sub directory bak.
cpsrc /home/usr/rapid/ - Copy directory src to absolute path directory
/home/usr/rapid/.
cp-R dev bak - Copy all files and directories in dev recursively to sub directory
bak. cp-i test.c bak - cp: overwrite 'bak/test.c'? y - Interactive prompt before file
overwrite. cp-u * bak - Update all files in current directory and copy only newer
files to destination directory bak.
mv: The mv command is used to move or rename files. mv command renames file
source to destination or moves the source file(s) to directory.
Syntax: mv [OPTIONS] Source Destination
The mv command has the following options:
mv -f - force move by overwriting destination file without prompt
mv -i - interactive prompt before overwrite
mv -u - update - move when source is newer than destination
mv -v - verbose - print source and destination files
man mv - help manual
Some of the examples are:
mvmain.c def.h /home/usr/rapid/ - Move main.c def.h files to /home/usr/rapid/
directory.
mv *.c bak -Move all C files in current directory to sub directory bak.
mv main.c main.bak - Rename file main.c to main.bak.
mv bak bak2 - Rename directory bak to bak2.
Mv -u main.c bak - Update and move when main.c is newer.
On Linux and other Unix like operating systems, man is the interface used to view the
system's reference manuals.
man is the system's manual viewer; it can be used to display manual pages, scroll up and
down, search for occurrences of specific text, and other useful functions.
The man command itself is extremely easy to use.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 13


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Syntax: man Command


Example: man ls

iii. Write a C program to print the Digit at ones place of a given number
Description:
At the time of execution, the program should print the message on the console as:
For example, if the user gives the input as:
Enter a number : 1987
Then the program should print the result as:
The digit at ones place of 1987 : 7
Note: Use the printf() function with a newline character (\n) at the end.
Algorithm:
Step 1: Start
Step 2: Read a Number
Step 3: Divide the number by 10 (Use the modulus operator for getting remainder (
Number % 10)
Step 4: Print the remainder.
Step 5: Stop.
Source Code:
#include <stdio.h>
void main() {
int num;
printf("Enter a number : ");
scanf("%d", &num);
printf("The digit at ones place of %d : %d\n", num, num % 10);
}
Test Case – 1:
Enter a number: 1993
The digit at ones place of 1993: 3
Test Case – 2:

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 14


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Enter a number: 1895


The digit at ones place of 189: 5

iv. Write a C program to perform Addition, Subtraction, Multiplication, and Division


of two numbers
Description:
During execution, the program should print the following message on the console:
Enter two integers :
For example, if the user gives the following as input:
Enter two integers : 24 15
Then the program should print the result as:
24 + 15 = 39
24 - 15 =9
24 * 15 = 360
24 / 15 =1
24 % 15 = 9
Note: Use the printf() function with a newline character (\n) at the end for every line being
printed.
Algorithm:
Step 1: Start
Step 2: Read Two Numbers a and b
Step 3: Print a + b
Step 4: Print a – b
Step 5: Print a * b
Step 6: Print a / b
Step 7: Print a % b
Step 8: Stop
Source Code:
#include <stdio.h>
//#include <math.h>

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 15


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

void main() {
int a, b;
printf("Enter two integers : ");
scanf("%d %d", &a, &b);
printf("%d + %d = %d\n", a, b, a + b);
printf("%d - %d = %d\n", a, b, a - b);
printf("%d * %d = %d\n", a, b, a * b);
printf("%d / %d = %d\n", a, b, a / b);
printf("%d %% %d = %d\n", a, b, a % b);
}
Test Case – 1:
Enter two integers: 12 -6
12 + -6 = 6
12 - -6 = 18
12 * -6 = -72
12 / -6 = -2
12 % -6 = 0
Test Case – 2:
Enter two integers : 15 3
15 + 3 = 18
15 - 3 = 12
15 * 3 = 45
15 / 3 =5
15 3 =0

v. Getting Familiar with variables


Write a C program to Swap Two numbers without using a third variable
During execution, the program should print the following message on the console:
Enter two integer values:
For example, if the user gives the input as 99 89

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 16


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Then the program should print the result as:


Before swapping the values are a = 99, b = 89
After swapping the values are a = 89, b = 99
Note: Use the printf() function with a newline character (\n) at the end.
Description:
Method 1 (Using Arithmetic Operators)
The idea is to get sum in one of the two given numbers. The numbers can then be swapped
using the sum and subtraction from sum.
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x + y;
// x now becomes 15
y = x - y;
// y becomes 10
x = x - y;
// x becomes 5
Method 2 (Using Bitwise XOR)
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x
and y returns a number which has all the bits as 1 wherever bits of x and y differ. For
example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7
(0111) and 5 (0101) is (0010).
Algorithm:
Algorithm for Method 1:
Step 1: Start
Step 2: input num1, num2
Step 3: num1 = num1 + num2
Step 4: num2 = num1 – num2
Step 5: num1 = num1 – num2
Step 6: Write num1, num2
Step 7: Stop

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 17


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Algorithm for Method 2:


Step 1: Start
Step 2: input num1, num2
Step 3: num1 = num1 ^ num2
Step 4: num2 = num1 ^ num2
Step 5: num1 = num1 ^ num2
Step 6: Write num1, num2
Step 7: Stop
Source code:
#include <stdio.h>
void main() {
int a , b;
printf("Enter two integer values : ");
scanf("%d %d", &a, &b);
printf("Before swapping the values are a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping the values are a = %d, b = %d\n", a, b);
}
Test Case-1:
Enter two integer values : 23 67
Before swapping the values are a = 23, b = 67
After swapping the values are a = 67, b = 23
Test Case-2:
Enter two integer values : 99 89
Before swapping the values are a = 99, b = 89
After swapping the values are a = 89, b = 99

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 18


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-2
Objective: Getting familiar with how to formally describe a solution to a problem in a
series of finite steps both using textual notation and graphic notation.
i. Write a C program to find Sum and Average of three numbers
Description:
During execution, the program should print the message on the console as:
Enter three integers :
For example, if the user gives the input as:
Enter three integers : 121 34 56
Then the result should be printed as:
Sum of 121, 34 and 56 : 211
Average of 121, 34 and 56 : 70.333336
Note: Use the printf() function with a newline character ( \n ) at the end.
Source Code:
#include <stdio.h>
void main()
{
int first, second, third, sum;
float avg;
printf("Enter three integers : ");
scanf("%d %d %d",&first, &second, &third);
sum = first + second + third;
avg = sum / 3.0;
printf("Sum of %d, %d and %d : %d\n", first, second, third, sum);
printf("Average of %d, %d and %d : %f\n", first, second, third, avg);
}
Test Case - 1
User Output
Enter three integers : 121 34 56
Sum of 121, 34 and 56 : 211

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 19


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Average of 121, 34 and 56 : 70.333336


Test Case - 2
User Output
Enter three integers : 5 8 3
Sum of 5, 8 and 3 : 16
Average of 5, 8 and 3 : 5.333333
Test Case - 3
User Output
Enter three integers : 11 33 55
Sum of 11, 33 and 55 : 99
Average of 11, 33 and 55 : 33.000000
Test Case - 4
User Output
Enter three integers : -1 5 -6
Sum of -1, 5 and -6 : -2
Average of -1, 5 and -6 : -0.666667

ii. Write a- C program to convert the temperature from Fahrenheit to Celsius


Description:
During execution, the program should print the following message on the console:
Enter the temperature in fahrenheit :
For example, if the user gives the following as input:
Enter the temperature in fahrenheit : 32.45
Then the program should print the result as:
Temperature in celsius = 0.250000
Algorithm for the given problem is:
START
Step-2: Read the temperature in fahrenheit .
Step-3: Convert the temperature to celsius as celsius ⟸ (5 / 9) * (fahrenheit - 32) .
Step-4: Display the temperature in celsius .

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 20


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

STOP
Source Code:
#include <stdio.h>
void main()
{
float c, f;
printf("Enter the temperature in fahrenheit : ");
scanf("%f", &f); c = (f - 32) * 5.0 / 9.0;
printf("Temperature in celsius = %f\n", c);
}
Test Case - 1
User Output
Enter the temperature in fahrenheit : 80.7799
Temperature in celsius = 27.099945
Test Case - 2
User Output
Enter the temperature in fahrenheit : 32.45
Temperature in celsius = 0.250000

iii. Write a C program to convert the given temperature from Celsius to Fahrenheit
Description:
During execution, the program should print the following message on the console:
Enter the temperature in celsius :
For example, if the user gives the input as 1.23 :
Enter the temperature in celsius : 1.23
Then the program should print the result as:
Temperature in fahrenheit = 34.214001
Note: Use the printf() function with a newline character ( \n ) at the end.
The formula to find fahrenheit is fahrenheit = celsius * (9.0 / 5.0) + 32.0 .
Source Code:

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 21


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

#include <stdio.h>
void main()
{
float c, f;
printf("Enter the temperature in celsius : ");
scanf("%f", &c);
f = c * (9.0 / 5.0) + 32;
printf("Temperature in fahrenheit = %f\n", f);
}
Test Case - 1
User Output
Enter the temperature in celsius : 27.1
Temperature in fahrenheit = 80.779999
Test Case - 2
User Output
Enter the temperature in celsius : 1.23
Temperature in fahrenheit = 34.214001

iv. Write a program to calculate Simple interest and Compound interest


Description:
During execution, the program should print the following message on the console:
Enter principle amount, rate of interest, time :
For example, if the user gives the input as:
Enter principle amount, rate of interest, time : 1000 6 4
Then the program should print the result as:
Simple interest = 240.000000
Compound interest = 262.476685
Note: Use the printf() function and ensure that the character '\n' is printed at the end of the
result.
The formula to find simple interest is simpleInterest = (principle * rate * time) / 100 .

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 22


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

The formula to find compound interest is compoundInterest = principle * pow(1 + (rate /


100), time) - principle .
Note: Use float data types for all the involved variables.
Source Code:
#include <stdio.h>
#include <math.h>
void main()
{
float principle, rate, time, simpleInterest, compoundInterest, interest;
printf("Enter principle amount, rate of interest, time : ");
scanf("%f %f %f", &principle, &rate, &time);
simpleInterest = (principle * rate * time) / 100;
interest = 1 + (rate / 100);
compoundInterest = principle * pow(interest, time) - principle;
printf("Simple interest = %f\n", simpleInterest);
printf("Compound interest = %f\n", compoundInterest);
}
Test Case - 1
User Output
Enter principle amount, rate of interest, time : 5000 7 5
Simple interest = 1750.000000
Compound interest = 2012.760376
Test Case - 2
User Output
Enter principle amount, rate of interest, time : 4500 12 2.5
Simple interest = 1350.000000
Compound interest = 1473.894897
Test Case - 3
User Output
Enter principle amount, rate of interest, time : 10000 4.5 3.5

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 23


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Simple interest = 1575.000000


Compound interest = 1665.596558
Test Case - 4
User Output
Enter principle amount, rate of interest, time : 1000 6 4
Simple interest = 240.000000
Compound interest = 262.476685

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 24


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-3
Objective: Learn how to define variables with desired data-type, initialize them with
appropriate values and how arithmetic operators can be used with variables and constants.
i. Write a program to find the Square root of a given number
Description:
During execution, the program should print the message on the console as:
Enter a number :
For example, if the user gives the input as 2 :
Enter a number : 2
Then the program should print the result as follows:
The square root is : 1.414214
Note - 1:Consider the input and output as double data type.
Note - 2: Use the printf() function with a newline character ( \n ) at the end.
Source Code:
#include <stdio.h>
#include <math.h>
int main()
{
double num;
printf("Enter a number : ");
scanf("%lf", &num);
printf("The square root is : %lf\n", sqrt(num));
return 0;
}
Test Case - 1
User Output
Enter a number : 25
The square root is : 5.000000
Test Case - 2
User Output

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 25


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Enter a number : 2
The square root is : 1.414214
Test Case - 3
User Output
Enter a number : 3.6
The square root is : 1.897367
Test Case - 4
User Output
Enter a number : 16.8
The square root is : 4.098780
Test Case - 5
User Output
Enter a number : 35
The square root is : 5.916080

ii. Write a C program to find Area of a Triangle using Heron's formula


Description:
During execution, the program should print the following message on the console:
Enter the length of three sides of triangle :
For example, if the user gives the following as input:
Enter the length of three sides of the triangle : 2.3 2.4 2.5
Then the program should print the result as:
Area of triangle : 2.485477
Note: Use the printf() function with a newline character ( \n ) at the end.
The area of a triangle is given by Area = √ p(p − a)(p − b)(p − c) , where p is half of
the perimeter, or (a + b + c) / 2 . Let a,b,c be the lengths of the sides of the given
triangle.
Source Code:
#include <stdio.h>
#include <math.h>

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 26


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

void main()
{
float side1, side2, side3, semiPerimeter = 0, area = 0;
printf("Enter the length of three sides of triangle : ");
scanf("%f %f %f",&side1, &side2, &side3);
semiPerimeter = (side1 + side2 + side3) / 2.0;
area = (sqrt)(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (s
emiPerimeter - side3));
printf("Area of triangle : %f\n", area);
}
Test Case - 1
User Output
Enter the length of three sides of triangle : 2.3 2.4 2.5
Area of triangle : 2.485477
Test Case - 2
User Output
Enter the length of three sides of triangle : 5 4 6.7
Area of triangle : 9.952600
Test Case - 3
User Output
Enter the length of three sides of triangle : 24.67 35.46 36.78
Area of triangle : 418.155121
Test Case - 4
User Output
Enter the length of three sides of triangle : 1 2 3
Area of triangle : 0.000000

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 27


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iii. Write a C program to find the Distance Travelled by an Object


Description:
Sample Input and Output:
Enter the acceleration value : 2.5
Enter the initial velocity : 5.7
Enter the time taken : 20
Distance travelled : 614.000000
Note - 1: Use the formula to find distance, distance = ut + (1/2) at .
Note: Use the printf() function with a newline character ( \n ) at the end.
Source Code:
#include <stdio.h>
void main()
{
float u, a, dist;
int t;
printf("Enter the acceleration value : ");
scanf("%f",&a);
printf("Enter the initial velocity : ");
scanf("%f",&u); printf("Enter the time taken : ");
scanf("%d",&t); dist = (u * t) + (a * t * t) / 2;
printf("Distance travelled : %f\n", dist);
}
Test Case - 1
User Output
Enter the acceleration value : 4
Enter the initial velocity : 5
Enter the time taken : 6
Distance travelled : 102.000000
Test Case - 2
User Output

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 28


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Enter the acceleration value : 5


Enter the initial velocity : 0
Enter the time taken : 10
Distance travelled : 250.000000
Test Case - 3
User Output
Enter the acceleration value : 2.5
Enter the initial velocity : 5.7
Enter the time taken : 20
Distance travelled : 614.000000
Test Case - 4
User Output
Enter the acceleration value : 50
Enter the initial velocity : 34.67
Enter the time taken : 6
Distance travelled : 1108.020020
Test Case - 5
User Output
Enter the acceleration value : 125.6
Enter the initial velocity : 45.8
Enter the time taken : 4
Distance travelled : 1188.000000

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 29


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

UNIT – II
WEEK-4
Objective: Explore the full scope of expressions, type-compatibility of variables &
constants and operators used in expression and how operator precedence works.
i. Write a Program that prints the results of all the Operators available in C
Description:
Read required operand values from standard input.
At the time of execution, the program should print the message on the console as:
Enter a and b values :
For example, if the user gives the input as:
Enter a and b values : 14 6
At the time of execution, the program should print the message on the console as:
Addition of a and b : 20
Substraction of a and b : 8
Multiplication of a and b : 84
Remainder of a and b : 2
Division of a and b : 2
Logical AND result : 1
Logical OR and NOT result : 1
Bitwise AND : 6
Bitwise OR : 14
Bitwise NOT : 0
Bitwise complement : -15
Bitwise XOR : 8
Bitwise shift right : 3
Bitwise shift left : 48
Integer size : 4, Floating point size : 4
Conditional expression : 200
Preincrement : 15
Postincrement : 6

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 30


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Predecrement : 14
Postdecrement : 7
Source Code:
#include <stdio.h>
void main() {
int a, b, result, result2;
printf("Enter a and b values : ");
scanf("%d %d", &a, &b);
printf("Addition of a and b : %d\n", a + b);
printf("Substraction of a and b : %d\n", a - b);
printf("Multiplication of a and b : %d\n", a * b);
printf("Remainder of a and b : %d\n", a % b);
printf("Division of a and b : %d\n", a / b);
result = (a > 0) && (b <= 10);
printf("Logical AND result : %d\n", result);
result2 = (a == b) || (b != 0);
printf("Logical OR and NOT result : %d\n",result2);
printf("Bitwise AND : %d\n", a & b);
printf("Bitwise OR : %d\n", a | b);
printf("Bitwise NOT : %d\n", !a);
printf("Bitwise complement : %d\n", ~a);
printf("Bitwise XOR : %d\n", a ^ b);
printf("Bitwise shift right : %d\n", a >> 2);
printf("Bitwise shift left : %d\n", b << 3);
printf("Integer size : %d, Floating point size : %d\n", sizeof(int), sizeof(float));
printf("Conditional expression : %d\n", ((a - b) > 50) ? 100 : 200);
printf("Preincrement : %d\n",++a);
printf("Postincrement : %d\n",b++);
printf("Predecrement : %d\n",--a);
printf("Postdecrement : %d\n",b--);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 31


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

}
Test Case – 1:
Enter a and b values : 14 6
Addition of a and b : 20
Substraction of a and b : 8
Multiplication of a and b : 84
Remainder of a and b : 2
Division of a and b : 2
Logical AND result : 1
Logical OR and NOT result : 1
Bitwise AND : 6
Bitwise OR : 14
Bitwise NOT : 0
Bitwise complement : -15
Bitwise XOR : 8
Bitwise shift right : 3
Bitwise shift left : 48
Integer size : 4, Floating point size : 4
Conditional expression : 200
Preincrement : 15
Postincrement : 6
Predecrement : 14
Postdecrement : 7
Test Case – 2:
Enter a and b values : 8 5
Addition of a and b : 13
Substraction of a and b : 3
Multiplication of a and b : 40
Remainder of a and b : 3
Division of a and b : 1

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 32


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Logical AND result : 1


Logical OR and NOT result : 1
Bitwise AND : 0
Bitwise OR : 13
Bitwise NOT : 0
Bitwise complement : -9
Bitwise XOR : 13
Bitwise shift right : 2
Bitwise shift left : 40
Integer size : 4, Floating point size : 4
Conditional expression : 200
Preincrement : 9
Postincrement : 5
Predecrement : 8
Postdecrement : 6
Test Case – 3:
Enter a and b values : 25 30
Addition of a and b : 55
Substraction of a and b : -5
Multiplication of a and b : 750
Remainder of a and b : 25
Division of a and b : 0
Logical AND result : 0
Logical OR and NOT result : 1
Bitwise AND : 24
Bitwise OR : 31
Bitwise NOT : 0
Bitwise complement : -26
Bitwise XOR : 7
Bitwise shift right : 6

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 33


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Bitwise shift left : 240


Integer size : 4, Floating point size : 4
Conditional expression : 200
Preincrement : 26
Postincrement : 30
Predecrement : 25
Postdecrement : 31

ii. Write a C program to find the Largest and Smallest of Three numbers using
Ternary operator
Description:
The Conditional operator the ternary operator (?:) is just like an if-else statement that can
be with in an expression. This operator is useful in situations, in which two or more
alternatives for an expression. They make the program code more compact.
The Syntax is :
exp1 ? exp2 : exp3
Here expression 1 is evaluated 1st. If it is true, then expression 2 is evaluated and
becomes the result of the expression, otherwise expression3 is evaluated and becomes the
output of the expression.
Ex1: To find the largest of two numbers
large = ( a > b) ? a : b
Since conditional operator is itself an expression, it can be used as an operand of another
conditional operation. This means you can have nested conditional expressions.
Ex2: To find the smallest of three numbers
int a = 5, b = 4, c = 7, small;
Small = ( a < b ? ( a < c ? a : c) : (b < c ? b : c) );
Algorithm 1:
Step 1: Start
Step 2: Input the 3 values of a, b, c
Step 3 : large = (a > b) ? a : b

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 34


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Step 4: large = (large > c) ? large : c)


Step 5: End.
Algorithm 2:
Step1: Start
Step 2: Input the 3 values of a, b, c
Step 3 :large= (a > b) && (a > c) ? a : (b > c) ? b : c)
Step 4: End.
Algorithm 3:
Step1: Start
Step 2: Input the 3 values of a, b, c
Step 3 :large= a > b ? ( a > c ? a : c) : (b > c ? b : c) ); //nested
Step 4: End.
Algorithm 2 Code:
#include <stdio.h>
void main() {
int a, b, c;
printf("Enter 3 integer numbers : ");
scanf("%d %d %d", &a, &b, &c);
printf("%d is the largest number\n", (a > b) && (a > c) ? a : (b > c) ? b : c); printf("%d is
the smallest number\n", (a < b) && (a < c) ? a : (b < c) ? b : c);
}
Test Case - 1
Enter 3 integer numbers : 34 56 48
56 is the largest number
34 is the smallest number
Test Case - 2
Enter 3 integer numbers : 99 9 999
999 is the largest number
9 is the smallest number

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 35


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iii. Write a C program to Total and average of subjects marks


Description
We have to find the sum as sum = m1 + m2 + m3 + m4 + m5
average = sum / 5.0
Note: Here the 5.0 is taken for getting float value of sum / 5 due to int / int returns int and
int / float return float.
Algorithm:
Step 1. Start
Step 2. Define variables: sub1, sub2, sub3, sub4, sub5, sum, average
Step 3. Take input from keyboard for all the input variables
Step 4. Calculate the sum of marks of 5 subjects
sum = sub1 + sub2 + sub3 + sub4 + sub5
average = sum / 5.0
Step 5. Display the sum and average.
Step 6. Stop
Enter 5 subjects marks : 55 56 57 54 55
Total marks : 277.000000
Average marks : 55.400002
Note: Use the printf() function with a newline character (\n) to print the output at the end.
Source Code:
#include<stdio.h>
void main() {
int first, second, third, fourth, fifth;
float sum, avg;
printf("Enter 5 subjects marks : ");
scanf("%d %d %d %d %d",&first, &second, &third, &fourth, &fifth);
sum = first + second + third + fourth + fifth;
avg = sum / 5.0;
printf("Total marks : %f\n", sum);
printf("Average marks : %f\n", avg);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 36


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

}
Test Case - 1
Enter 5 subjects marks : 45 67 89 57 49
Total marks : 307.000000
Average marks : 61.400002
Test Case - 2
Enter 5 subjects marks : 55 56 57 54 55
Total marks : 277.000000
Average marks : 55.400002
Test Case - 3
Enter 5 subjects marks : 90 97 95 92 91
Total marks : 465.000000
Average marks : 93.000000
Test Case - 4
Enter 5 subjects marks : 20 30 66 77 44
Total marks : 237.000000
Average marks : 47.400002
Test Case - 5
Enter 5 subjects marks : 56 78 88 79 64
Total marks : 365.000000
Average marks : 73.000000
Test Case - 6
Enter 5 subjects marks : 44 35 67 49 51
Total marks : 246.000000
Average marks : 49.200001

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 37


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iv. Evaluate the following expressions


a. A+B*C+(D*E)+F*G
b. A/B*C-B+A*D/3
Description:
Operators Precedence and Associativity are two characteristics of operators that
determine the evaluation order of sub-expressions in absence of brackets.
Operator precedence determines which operator is performed first in an expression with
more than one operators with different precedence.
For example: Solve 10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30
Operators Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left.
For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so
the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 38


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

For example: Solve


100 + 200 / 10 - 3 * 10

1. Associativity is only used when there are two or more operators of same precedence. The
point to note is associativity doesn’t define the order in which operands of a single
operator are evaluated.
2. All operators with the same precedence have same associativity. This is necessary,
otherwise, there won’t be any way for the compiler to decide evaluation order of
expressions which have two operators of same precedence and different associativity. For
example + and – have the same associativity.
3. Precedence and associativity of postfix ++ and prefix ++ are different Precedence of
postfix ++ is more than prefix ++, their associativity is also different. Associativity of
postfix ++ is left to right and associativity of prefix ++ is right to left.
4. Comma has the least precedence among all operators and should be used carefully.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 39


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

The following precedence and associativity table for reference.


OPERATOR DESCRIPTION ASSOCIATIVITY
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement (see Note 2)
++ — Prefix increment/decrement right-to-left
+– Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 40


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Problem Statement Analysis


A=1, B=2, C=3, D=4, E=5, F=6, G=7
a. A+B*C+(D*E)+F*G
= 1 + 2 * 3 + (4 * 5) + 6 * 7
= 1 + 2 * 3 + 20 + 6 * 7
= 1 + 6 + 20 + 6 * 7
= 1 + 6 + 20 + 42
= 7 + 20 + 42
= 27 + 42
= 69
b. A/B*C-B+A*D/3
=1/2*3–2+1*4/3
= 0 * 3 -2 + 1 * 4 / 3
=0-2+1*4/3
=0-2+4/3
=0–2+1
= -2 + 1
= -1
Problem Description / Analysis
If A = 1, B= 2
a). A+++B---A
= 1+++2---1
= 2+2---2 (A post incremented first due to left associativity)
= 2+1-2 (B post decremented and becomes +1 due to left associativity)
=3–2
=1
If i = 3
b). J=(i++)+(++i)
j = (3++) + (++3)
J = (4) + (4)
J=8

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 41


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-5
Objective: Explore the full scope of different variants of “if construct” namely if-else, null-
else, if-else if*-else, switch and nested-if including in what scenario each one of them can be
used and how to use them. Explore all relational and logical operators while writing
conditionals for “if construct”.
a. Write a C program to find the max and min of four numbers using if.else
Description:
Given four numbers, print the maximum of the 4 entered numbers
Examples:
Input: 4 8 6 5
Output: 8
Input: 11 17 8 17
Output: 17
Algorithm:
START
Step 2: Declare variables a, b, c, d, min and max.
Step 3: Read variables a, b, c, d, min and max.
Step 4: Assign ‘a’ value to both min and max.
Step 4: If b>max
Display b is the largest number.
Else if b<min
Display b is the smallest number.
If c>max
Display b is the largest number.
Else if c<min
Display b is the smallest number.
If d>max
Display b is the largest number.
Else if d<min
Display b is the smallest number.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 42


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

STOP
Source Code:
#include<stdio.h>
int main()
{
int a, b, c, d,min,max;
printf("Enter 4 intgeres to find largest and smallest: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
max = min = a;
if (b > max)
max = b;
else if (b < min)
min = b;
if (c > max)
max = c;
else if (c < min)
min = c;
if (d > max)
max = d;
else if (d < min)
min = d;
printf("max: %d min : %d\n", max, min);
return 0;
}
Test Case 1:
Enter 4 intgeres to find largest and smallest: 4 7 1 9
max: 9 min : 1
Test Case 2:
Enter 4 intgeres to find largest and smallest: 45 22 81 28
max: 81 min :22

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 43


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

ii. Write a C program to generate electricity bill


Procedure:
1. Input unit consumed by customer in some variable say unit.
2. If unit consumed less or equal to 50 units. Then amt = unit * 0.50.
3. If unit consumed more than 50 units but less than 100 units. Then add the first 50units
amount i.e. 25 to final amount and compute the rest 50 units amount. Which is given by
amt = 25 + (unit-50) * 0.75. I have used units-50, since I already calculated first 50 units
which is 25.
4. Similarly check rest of the conditions and calculate total amount.
5. After calculating total amount. Calculate the surcharge amount i.e. sur_charge =
total_amt * 0.20. Add surcharge amount to net amount. Which is given by net_amt =
total_amt + sur_charge.
Source Code:
#include <stdio.h>
int main()
{
int unit;
float amt, total_amt, sur_charge;
/* Input unit consumed from user */
printf("Enter total units consumed: ");
scanf("%d", &unit);
/* Calculate electricity bill according to given conditions */
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 44


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

else if(unit <= 250)


{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}
/*
* Calculate total electricity bill
* after adding surcharge
*/
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %.2f", total_amt);
return 0;
}
Test Case 1:
Enter total units consumed: 50
Electricity Bill = Rs. 30
Test Case 2:
Enter total units consumed: 200
Electricity Bill = Rs. 192

iii. Find the roots of quadratic equation


Description:
The standard form of a quadratic equation is: ax2 + bx + c = 0, where a, b and c are real
numbers and a ≠ 0
The term b2-4ac is known as the discriminant of a quadratic equation.
The discriminant tells the nature of the roots.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 45


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

✓ If discriminant is greater than 0, the roots are real and different.


✓ If discriminant is equal to 0, the roots are real and equal.
✓ If discriminant is less than 0, the roots are complex and different.
Algorithm:
START
Step-1: Enter the value of a, b and c.
Step-3: Calculate determinant as D= b2-4ac
Step-4: If (D> 0) then continue else ‘GOTO Step 9
Step-5: Calculate root1= -b + √D/2a
Step-6: Calculate root2= -b – √D/2a
Step-7: Print value of root1 and root2 these are Real and different
Step-8: GOTO END
Step-9: If (D==0) then continue else GOTO Step 13
Step-10: Calculate root1 = root2 = -b/2*a
Step-11: Print value of root1 and root2 the roots are real and equal.
Step-12: GOTO END
Step-13: Calculate RealPart = -b/2a
Step-14: Calculate imaginaryPart = √(-D)/2a
Step-15: Print value of root1= RealPart + i imaginaryPart
Step-16: Print value of root2= RealPart – i imaginaryPart the roots are complex and different
STOP
Source Code:
#include <stdio.h>
#include <math.h> /* Used for sqrt() */
int main()
{
float a, b, c;
float root1, root2, imaginary;
float discriminant;
printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 46


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

scanf("%f%f%f", &a, &b, &c);


/* Find discriminant of the equation */
discriminant = (b * b) - (4 * a * c);
/* Find the nature of discriminant */
if(discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);
}
else if(discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
}
else if(discriminant < 0)
{
root1 = root2 = -b / (2 * a);
imaginary = sqrt(-discriminant) / (2 * a);
printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f",
root1, imaginary, root2, imaginary);
}
return 0;
}
Test Case 1:
Enter values of a, b, c of quadratic equation (aX^2 + bX + c): 4 4 1
Two equal and real roots exists: -0.50 and -0.50
Test Case 2:
Enter values of a, b, c of quadratic equation (aX^2 + bX + c): 8 -4 -2
Two distinct and real roots exists: 0.81 and -0.31

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 47


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iv. Write a C program to simulate a calculator using switch case


Description:
This calculator program in C helps the user to enter the Operator (+, -, *, or /) and two
values. Using those two values and operand, it will perform Operations. For this C
calculator program example, we used the Switch case to check which operand is inserted
by the user. Next, based on the Operand result will be displayed
Algorithm:
Step 1: Start the program
Step 2: Read the two variable num1 and num2
Step 3: Display menu
Step 4: Enter the option code
Step 5: Evaluate option code with case statements
Step 5.1: case ‘+’ result=num1+num2, print result. goto step 7
Step 5.2: case ‘-’ result =num1-num2, print result. goto step 7
Step 5.3: case ‘*’ result =num1*num2, print result. goto step 7
Step 5.4: case ‘/’ result =(float)num1/num2, print result. goto step 7
Step 5.5: case ‘%’ result =(float)num1/num2, print result. goto step 7
Step 6: Entered case option is invalid code the print “Wrong Choice”
Step 7: Stop the program
Source Code:
#include <stdio.h>
int main()
{
int num1,num2;
float result;
char ch; //to store operator choice
printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 48


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf("Choose operation to perform (+,-,*,/,%): ");


scanf(" %c",&ch);
result=0;
switch(ch)
{
case '+':
result=num1+num2;
break;

case '-':
result=num1-num2;
break;

case '*':
result=num1*num2;
break;
case '/':
result=(float)num1/(float)num2;
break;
case '%':
result=num1%num2;
break;
default:
printf("Invalid operation.\n");
}
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
return 0;
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 49


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case-1:
//OUTPUT FOR ADDITION
Enter first number: 55
Enter second number: 66
Choose operation to perform (+,-,*,/,%): +
Result: 55+66=121.0
Test Case-2:
//OUTPUT FOR SUBTRACTION
Enter first number: 50
Enter second number: 6
Choose operation to perform (+,-,*,/,%): -
Result: 50-6=44.0

v. Write a C program to find the given year is leap year or not


Description:
If the year entered by the user is firstly divided by 4. If it is divisible by 4 then it is divided
by 100 and then 400. If year is divisible by all 3 numbers then that year is a leap year. If the
year is divisible by 4 and 100 but not by 400 then it is not a leap year. If the year is divisible
by 4 but not by 100, then it is a leap year. (Remember that if the year is divisible by 4 and not
by hundred then the program does not check the last condition, i.e., whether the year is
divisible by 400). If the year is not divisible by 4 then no other conditions are checked and
the year is not a leap year.
Source Code:
#include <stdio.h>
int main()
{
int yr;
printf ("Enter a year \n");
scanf ("%d", &yr);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 50


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

if (yr%4 == 0 && yr%100 == 0 && yr%400 == 0)


printf("\n It is LEAP YEAR.");
else if (yr%4==0 && yr%100!=0)
printf("\n It is LEAP YEAR.");
else
printf ("\n It is NOT LEAP YEAR.");
return 0;
}
Test Case 1:
Enter a year
1600
It is LEAP YEAR.
Test Case 2:
Enter a year
2900
It is NOT LEAP YEAR.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 51


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-6
Objective: Explore the full scope of iterative constructs namely while loop, do-while loop
and for loop in addition to structured jump constructs like break and continue including
when each of these statements is more appropriate to use.
i. Find the factorial of given number using any loop
Description:
Factorial of a non-negative integer is multiplication of all integers smaller than or equal to n.
For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Algorithm:
Step-1:Start
Step-2: Read the number n
Step-3: [Initialize]
i=1, fact=1
Step-4: Repeat step 4 through 6 until i=n
Step-5: fact=fact*i
Step-6: i=i+1
Step-7: Print fact
Step-8: Stop
Source Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,fact=1;
printf("Enter any number : ");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact = fact * i;
printf("Factorial value of %d = %d",n,fact);
return 0;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 52


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

}
Test Case 1:
Enter any number: 5
Factorial value of 5=120
Test Case 2:
Enter any number: 3
Factorial value of 3=6

ii. Find the given number is a prime or not


Description:
A prime number is a whole number greater than 1, which is only divisible by 1 and itself.
First few prime numbers are : 2 3 5 7 11 13 17 19 23 …..
Some interesting fact about Prime numbers
1. Two is the only even Prime number.
2. Every prime number can represented in form of 6n+1 or 6n-1 except 2 and 3, where n is
natural number.
3. Two and Three are only two consecutive natural numbers which are prime too.
Algorithm:
Step 1: Start
Step 2: Read number n
Step 3: Set f=0
Step 4: For i=2 to n-1
Step 5: If n mod 1=0 then
Step 6: Set f=1 and break
Step 7: Loop
Step 8: If f=0 then
print 'The given number is prime'
else
print 'The given number is not prime'
Step 9: Stop

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 53


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Source Code:
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr();
int n,i,f=0;
printf("Enter the number: ");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
{
f=1;
break;
}
}
if(f==0)
printf("The given number is prime");
else
printf("The given number is not prime");
getch();
}
Test Case 1:
Enter the number : 5
The given number is prime
Test Case 2:
Enter the number : 20
The given number is not prime

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 54


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iii. Compute sine and cos series


Description:
Sine Series:
Sine Series is a series which is used to find the value of Sin(x). where, x is the angle in
degree which is converted to Radian.
The formula used to express the Sin(x) as Sine Series is

Expanding the above notation, the formula of Sine Series is

For example,
Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Sin(30) is 0.5.


Program code for Sine Series in C:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
clrscr();
printf(" Enter the value for x : ");
scanf("%f",&x);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 55


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf(" Enter the value for n : ");


scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for (i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
getch();
}
Output:
Enter the value for x : 45
Enter the value for n : 5
The value of Sin(0.785398) = 0.7071
Working:
First the computer reads the value of ‘x’ and ‘n’ from the user.
Then ‘x’ is converted to radian value.
Then using for loop the value of Sin(x) is calculate.
Finally the value of Sin(x) is printed.
Cosine Series:
Cosine Series is a series which is used to find the value of Cos(x).where, x is the angle in
degree which is converted to Radian.
The formula used to express the Cos(x) as Cosine Series is

Expanding the above notation, the formula of Cosine Series is

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 56


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

For example,
Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Cos(30) is 0.8660.


Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum=1, t=1;
clrscr();
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
/* Loop to calculate the value of Cosine */
for(i=1;i<=n;i++)
{
t=t*(-1)*x*x/(2*i*(2*i-1));
sum=sum+t;
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 57


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf(" The value of Cos(%f) is : %.4f", x, sum);


getch();
}
Output:
Enter the value for x : 30
Enter the value for n : 5
The value of Cos(0.523598) is: 0.8660
Working:
✓ First the computer reads the value of ‘x’ and ‘n’ from the user.
✓ Then ‘x’ is converted to radian value.
✓ Then using for loop the value of Cos(x) is calculate.
✓ Finally the value of Cos(x) is printed.

iv. Checking a number palindrome


Description:
Palindrome number in C language: A palindrome number is which remains the same on
reversal. For example, some palindrome numbers are 8, 121, 212, 12321, -454. To check
whether a number is a palindrome or not first we reverse it and then compare the number
obtained with the original number, if both are same then the number is palindrome
otherwise not.
Algorithm:
To test if a number is palindrome or not, do the following steps:
1. Get the number from a user.
2. Reverse it.
3. Compare it with the number entered by the user.
4. If both are the same then print palindrome number else print not a palindrome number.
Source Code:
#include <stdio.h>
int main()
{

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 58


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

int n, reversedInteger = 0, remainder, originalInteger;


printf("Enter an integer: ");
scanf("%d", &n);
originalInteger = n;
// reversed integer is stored in variable
while( n!=0 )
{
remainder = n%10;
reversedInteger = reversedInteger*10 + remainder;
n /= 10;
}

// palindrome if orignalInteger and reversedInteger are equal


if (originalInteger == reversedInteger)
printf("%d is a palindrome.", originalInteger);
else
printf("%d is not a palindrome.", originalInteger);
return 0;
}
Test Case 1:
Enter an integer: 1001
1001 is a palindrome.
Test Case 2:
Enter an integer: 1234
1234 is not a palindrome.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 59


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

v. Construct a pyramid of numbers


Description:
The sequence will be printed as specified in the below triangle format. If user enters number
of rows as 5 then following output will be produced.
1
23
456
7 8 9 10
11 12 13 14 15
Source Code:
#include<stdio.h>
#include<conio.h>
void main( )
{
int r, c, num=1 ,len;
clrscr( );
printf("Enter the required no. of rows:");
scanf("%d", &len);
for( r=1; r<=len; r++ )
{
printf("\n");
for(c=1 ; c<=r; c++)
{
printf("%2d ", num);
num++;
}
}
getch( );
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 60


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case 1:
Enter the required no. of rows:5
1
23
456
7 8 9 10
11 12 13 14 15
Test Case 2:
Enter the required no. of rows:3
1
23
456

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 61


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

UNIT – III
WEEK-7
Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D
and 2-D and more generically n-D arrays and referencing individual array elements from
the defined array. Using integer 1-D arrays, explore search solution linear search.
i. Find the min and max of 1-D integer array
Description:
first we assume that maximum element occurs at the beginning of the array and then we
compare it with other array elements one by one, if any one element is greater than our
assumed maximum, then the maximum value and the index at which it occurs are
updated. This process is repeated till complete array is compared. Similarly, Assumes the
first element as minimum and compare this minimum with other elements if an element is
smaller than it then it becomes the new minimum. Process is repeated till complete array
is compared.
Algorithm:
START
Step 1: first we assume that maximum element occurs at the beginning of the array and
stores that value in a variable.
Step 2: Then we compare it with other array elements one by one,
i) if any element is greater than our assumed maximum, then the maximum value
and the index at which it occurs are updated.
Step 3: Step 2 is repeated till complete array is compared.
Step 4: Assumes the first element as minimum
Step 5: Compare this minimum with other elements if an element is smaller than it then it
becomes the new minimum
Step 6: Step 5 is repeated till complete array is scanned.
STOP
Source Code:
#include <stdio.h>
int main()

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 62


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

{
int array[100], maximum, minimum, size, i,j maxloc = 1,minloc=1;
printf("Enter the number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
maximum = array[0];
minimum= array[0];
//to find max among all the list
for (i = 1; i < size; i++)
{
if (array[i] > maximum)
{
maximum = array[i];
maxloc = i+1;
}
}
// to find min among all the list
for (j = 1; j < size; j++)
{
if (array[j] <minimum)
{
minimum = array[j];
minloc = j+1;
}
}
printf("Maximum element is present at location %d and it's value is %d.\n", maxloc,
maximum);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 63


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf("Minimum element is present at location %d and it's value is %d.\n", minloc,


minimum);
return 0;
}
Test Case-1
Enter the number of elements in array
4
Enter 4 integers
3
5
6
7
Maximum element is present at location 4 and it’s value is 7
Maximum element is present at location 1 and it’s value is 3
Test Case-2
Enter the number of elements in array
5
Enter 5 integers
3
5
6
7
8
Maximum element is present at location 5 and it’s value is 8
Maximum element is present at location 1 and it’s value is 3

ii. Perform linear search on 1D array


Description:
Linear search is used to check 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. Here, we

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 64


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

keep on comparing each element with the element to search until it is found or the list
ends.
Algorithm:
START
Step 1: Read size of an array (A) as n, and read array of integers
Step 2: Set i to 1
Step 3: if i > n then go to step 8
Step 4: if A[i] = x then go to step 7
Step 5: Set i to i + 1
Step 5: Go to Step 3
Step 6: Print Element x Found at index i and go to step 9
Step 7: Print element not found
Step 8: Exit
STOP
Source Code:
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 65


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
Test Case-1:
Enter the number of elements in array
5
Enter 5 integer(s)
2
4
6
8
9
Enter a number to search
8
8 is present at location 4.

iii. Reverse of 1D integer array


Description: Firstly read the size of an array and read the set of elements to array with
given size n where n is provided by user and display the array elements in reverse
order.This method is used to access array element in reverse and copy it to a new reverse
array. Which means last element of original array becomes the first element for reverse
array.
Algorithm:
START
Step 1: Input size and elements in an array. Store it in some variable say size and arr
respectively.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 66


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Step 2: Declare another array that will store reversed array elements of original array with
same size, say reverse[size].
Step 3: Initialize two variables that will keep track of original and reverse array. Here we
will access original array from last and reverse array from first. Hence, initialize arrIndex
= size - 1 and revIndex = 0.
Step 4: Run loop from size - 1 to 0 in decremented style. The loop structure should look
like while(arrIndex >= 0).
Step 5: Inside loop copy original array to reverse array i.e. reverse [revIndex] =
arr[arrIndex];.
Step 6: After copy, increment revIndex and decrement arrIndex.
Step 7: Finally after loop print reverse array.
STOP
Source Code:
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE], reverse[MAX_SIZE];
int size, i, arrIndex, revIndex;
/* Input size of the array */
printf("Enter size of the array: ");
scanf("%d", &size);
/* Input array elements */
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
revIndex = 0;
arrIndex = size - 1;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 67


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

while(arrIndex >= 0)
{
/* Copy value from original array to reverse array */
reverse[revIndex] = arr[arrIndex];
revIndex++;
arrIndex--;
}
/*
* Print the reversed array
*/
printf("\nReversed array : ");
for(i=0; i<size; i++)
{
printf("%d\t", reverse[i]);
}
return 0;
}
Test Case-1:
Enter size of the array: 4
Enter elements in array: 3
4
6
7
Reversed array : 7 6 4 3

iv. Addition of two matrices


Description:
Taking a Binary Number as a string, print its 1’s and 2’s complements.
1’s complement of a binary number is another binary number obtained by toggling all
bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 68


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

1's complement of "0111" is "1000"


1's complement of "1100" is "0011"
2’s complement of a binary number is 1 added to the 1’s complement of the binary
number.
Examples:
2's complement of "0111" is "1001"
2's complement of "1100" is "0100"
For one’s complement, we simply need to flip all bits.
For 2’s complement, we first find one’s complement. We traverse the one’s complement
starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until
we find a 0. Finally, we flip the found 0. For example, 2’s complement of “01000” is
“11000” (Note that we first find one’s complement of 01000 as 10111). If there are all
1’s (in one’s complement), we add an extra 1 in the string. For example, 2’s complement
of “000” is “1000” (1’s complement of “000” is “111”).
Algorithm:
START
Step 1: Input a binary string from user. Store it in a variable say binary.
Step 2: Find ones complement of the binary string. Store the result in some variable say
onesComp.
Step 3: Declare and initialize another binary string variable to store twos complement,
say twosComp = "".
Step 4: Initialize a variable to store carry bit during addition, say carry = 1.
we need to add only 1 to the binary string hence, I have initially assumed carry bit as the
bit to be added.
Step 5: Run a loop from length of binary string to 1, decrement 1 in each iteration. The
loop structure should look like for(i=SIZE-1; i>=1; i--) (where SIZE is length of the
binary string).
Step 6: Inside the loop there can be three cases.
A. If both current binary bit and carry bit are 1 then, put 0 to twos complement.
Which is if(onesComp[i]=='1' && carry==1) then, twosComp[i] = '0', carry is still
preserved to 1.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 69


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

B. If current binary bit is 0 and carry bit is 1 then, put 1 to twos complement and set
carry bit to 0. Which is if(onesComp[i]=='0' && carry==1) then, twosComp[i] =
'1' and carry = 0.
C. If carry bit is 0, then assign the value of onesComp to twosComp.
STOP
Source Code:
#include <stdio.h>
#define SIZE 8
int main()
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1];
int i, carry=1;
printf("Enter %d bit binary value: ", SIZE);
/* Input 8-bit binary string */
gets(binary);
/* Find ones complement of the binary number */
for(i=0; i<SIZE; i++)
{
if(binary[i] == '1')
{
onesComp[i] = '0';
}
else if(binary[i] == '0')
{
onesComp[i] = '1';
}
}
onesComp[SIZE] = '\0';
/*
* Add 1 to the ones complement
*/

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 70


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

for(i=SIZE-1; i>=0; i--)


{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';
printf("Original binary = %s\n", binary);
printf("Ones complement = %s\n", onesComp);
printf("Twos complement = %s\n", twosComp);
return 0;
}
Test Case-1
Enter 8 bit binary value: 01101100
Original binary = 01101100
Ones complement = 10010011
Twos complement = 10010100

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 71


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

v. Eliminate duplicate elements in an array


Description:
To delete duplicate elements from an array. For example, if an array contains following
five elements: 1, 6, 2, 1, 9; in this array '1' occurs two times. After deleting duplicate
element we get the following array: 1, 6, 2, 9.
Algorithm:
START
Step 1: Input size and elements in array from user. Store it in some variable say size and
arr.
Step 2: To find duplicate elements in given array we need two loops. Run an outer loop
from 0 to size. Loop structure must look like for(i=0; i<size; i++). This loop is used to
select each element of array and check next subsequent elements for duplicates using
another nested loop.
Step 3: Run another inner loop to find first duplicate of current element. Run an inner
loop from i + 1 to size. The loop structure should look like for(j=i+1; j<size; j++).
Step 4: Inside the inner loop check for duplicate element. If a duplicate element is found
then delete that array element. Also if a duplicate element is found then decrement size of
array i.e. size = size - 1.
STOP
Source Code:
#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the array
int main()
{
int arr[MAX_SIZE]; // Declares an array of size 100
int size; // Total number of elements in array
int i, j, k; // Loop control variables
/* Input size of the array */
printf("Enter size of the array : ");
scanf("%d", &size);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 72


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

/* Input elements in the array */


printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Find duplicate elements in array
*/
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
/* If any duplicate found */
if(arr[i] == arr[j])
{
/* Delete the current duplicate element */
for(k=j; k<size; k++)
{
arr[k] = arr[k + 1];
}
/* Decrement size after removing duplicate element */
size--;
/* If shifting of elements occur then don't increment j */
j--;
}
}
}
/*
* Print array after deleting duplicate elements

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 73


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

*/
printf("\nArray elements after deleting duplicates : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
Test Case-1
Enter size of the array : 10
Enter elements in array : 10 20 10 1 100 10 2 1 5 10
Array elements after deleting duplicates : 10 20 1 100 2 5

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 74


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-8
Objective: Explore the difference between other arrays and character arrays that can be
used as Strings by using null character and get comfortable with string by doing
experiments that will reverse a string and concatenate 2 strings. Explore sorting solution
bubble sort using integer arrays.
i. Addition of two matrices
Description:
Matrix Addition Matrix addition is the operation of adding two matrices by adding the
corresponding entries together. The usual matrix addition is defined for two matrices of
the same dimensions. The sum of two m by n matrices A and B, denoted by A + B, is
again m by n matrix computed by adding corresponding elements.
Algorithm:
START
Step 1: Read the total number of rows &columns for the matrix
Step 2: Read the elements for A Matrix and store it in to two dimensional arrays.
Step 3: Read the elements for B Matrix and store it into other two dimensional array.
Step 4: Add the elements of 2 matrixes namely A& B through the nested for Loops and store
the result into a resultant 2-dimesional array C.
Step 5: Display the result
STOP
Source Code:
#include<stdio.h>
void main()
{
int m, n, i, j, a[10][10], b[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
if(m==n)
{
printf("Enter the elements of first matrix\n");

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 75


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

for (i=0;i<m;i++)
for (j =0;j< n;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of second matrix\n");
for (i= 0;i<m;i++)
for (j=0;j< n;j++)
scanf("%d",&b[i][j]);
printf("Sum of 2 matrices: \n");
for (i=0;i<m;i++)
{
for (j=0;j< n;j++)
{
sum[i][j] = a[i][j] + b[i][j];
printf("%d\t", sum[i][j]);
}
printf("\n");
}
}
else
{
printf("Addition not possible");
}
getch();
}
Test Case-1
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
1234

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 76


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Enter the elements of second matrix


1234
Sum of 2 matrices:
2 4
6 8
Test Case-2
Enter the number of rows and columns of matrix
3
4
Addition not possible

ii. Multiplication two matrices


Description:
Matrix is the operation of two matrices multiplying a matrix with either a scalar or another
matrix. The product of two matrices A and B is defined as c ik = aij bik Where j is
summed over for all possible values if I and k. In order for matrix multiplication to be
defined, the dimensions pf the matrices must satisfy (n X m)(m X p) = (n X p). Where (a
X b) denotes a matrix with a rows and b columns.
Algorithm:
START
Step 1: Read the total number of rows &columns for the matrix
Step 2: Read the elements for A Matrix and store it into two dimensional arrays.
Step 3: Read the elements for B Matrix and store it into other two dimensional array.
Step 4: Multiply the elements of 2 matrixes namely A & B through the nested for Loops and
store the result into a resultant 2-dimesional array C.
Step 5: Display the result
STOP
Source Code:
# include<stdio.h>
void main( )

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 77


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

{
int a[10][10],b[10][10],c[10][10],m,n,p,q,i,j,k;
clrscr();
printf("Enter the rows and columns of matrix A\n");
scanf("%d%d",&m,&n);
printf("Enter the rows and columns of matrix B\n");
scanf("%d%d",&p,&q);
if(n!=p)
printf("Matrix multiplication is not possible\n");
else
{
/* loop to read values of A matrix */
printf("Enter the elements of matrix A\n");
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
/* loop to read values of B matrix */
printf("Enter the elements of matrix B\n");
for(i=0;i<p;i++)
{
for (j=0;j<q; j++)
{
scanf("%d", &b[i][j]);
}
}
/* loop to multiply two matrices */

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 78


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

for(i=0;i<m; i++)
{
for(j=0;j<q; j++)
{
c[i][j]=0;
for(k=0;k<p; k++)
c[i][j] = c[i][j]+a[i][k]*b[k][j];
}
}
/* loop to print resultant matrix */
printf("Resultant matrix is\n");
for( i=0; i<m; i++)
{
for( j=0; j<q; j++)
{
printf(" %6d ",c[i][j]);
}
printf("\n");
}
getch( ) ;
}
}
Test Case-1
Enter the rows and columns of matrix A
23
Enter the rows and columns of matrix B
32
Enter the elements of matrix A
234234
Enter the elements of matrix B

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 79


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

322322
Resultant matrix is
20 21
20 21
Test Case-2
Enter the rows and columns of matrix A
22
Enter the rows and columns of matrix B
12
Matrix multiplication is not possible

iii. Sort an array elements using bubble sort


Description:
Bubble sort is the simplest and oldest sorting technique. This method takes two elements at a
time. It compare these two elements. If first element is less than second one, they are left
undisturbed. If the first element is greater than second one then they are swapped. The
procedure continues with the next two elements goes and ends when all the elements are
sorted. But bubble sort is an inefficient algorithm. The order of bubble sort algorithm is
O(n2).
Algorithm:
START
Step 1: Read n
Step 2: initialize i=0
Step 3: if i<n go to step 5, otherwise go to step 5
Step 4: Read a[i], go to step3
Step5: initialize i=0
Step 6: if i<n go to
Step 7: otherwise go to step 12
Step 8: initialize j=0
Step9: if j<n-i-1 go to step10, otherwise go to step12

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 80


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Step10: if a[j]>a[j+1], otherwise go to step 11 i) temp=a[i]; ii) a[i]=a[j+1]; iii) a[j+1]=temp;


go to step11
Step11: increment j, go to step9
Step12: increment i, go to step7
Step13: initialize i=0
Step14: if i<n go to step15, otherwise go to step16
Step15: Print a[i], go to step14
STOP
Source Code:
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{ scanf("%d", &array[i]); }
printf("Input array is \n");
for (i = 0; i < num; i++)
{ printf("%d\n", array[i]); }
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{ if (array[j] > array[j + 1])
{ temp = array[j];
array[j] = array[j + 1];

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 81


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

array[j + 1] = temp; }
} }
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{ printf("%d\n", array[i]); }}
Test Case-1
Enter the value of num 5
Enter the elements one by one 45 12 34 2 25
Input array is 45 12 34 2 25
Sorted array is... 2 12 25 34 45

iv. Concatenate two strings without built-in functions


Description:
If str1 and Str2 are two strings, then concatenation operation produces a string which
contains characters of Str1 followed by Str2. Ex: Str1= MVGR, Str2=COLLEGE
Mystr_concatenate(Str1,Str2) forms a new string Str3 which consists MVGR COLLEGE.
Source Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str1[30],str2[20];
int i,length=0,temp;
clrscr();
printf("Enter String1 : ");
gets(str1);
printf("Enter String2 : ");
gets(str2);
for(i=0;str1[i]!='\0';i++)

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 82


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

length++;
temp=length;
for(i=0;str2[i]!='\0';i++)
{
str1[temp] = str2[i];
temp++;
}
str1[temp] = '\0';
printf("Without using string function the concatenated string is %s :\n",str1);
strcat(str1,str2);
printf("Using string function the concatenated string is %s : ",str1);
getch();
}
Test Case-1
Enter String1 : hello
Enter String2 : hai
Without using string function the concatenated string is : hellohai
Using string function the concatenated string is : hellohaihai

v. Reverse a string using built-in and without built-in string functions


Description:
Reverse a string in C: This program reverses a string that a user inputs. For example, if a user
enters a string "hello" then on reversing it will be "olleh".
Source Code:
#include<stdio.h>
#include<string.h>
int main() {
char str[100],temp,arr[100];
int i, j = 0;
printf(“ Enter a string to reverse \n”);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 83


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

gets(arr);
strrev(arr);
printf(“Reverse of the string is \t %s \n”,arr);
printf("\nEnter the string :");
\*with out using string handling function*\
gets(str);
i = 0;
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("\nReverse string is :%s", str);
return (0);
}
Test case-1
Enter a string to reverse
Hello
Reverse of thr string is olleH
Enter the string
Mvgr
Reverse string is rgvM

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 84


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

UNIT – IV
WEEK-9
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some
experiments by parameter passing using call by value. Basic methods of numerical
integration
i. Write a C function to calculate ncr value
Description:
The recursive formula for factorial is:
n! = n * (n - 1)!; if n > 0 (Recursive criteria)
n! = 1; if n = 0 (Base criteria)
At the time of execution, the program should print the message on the console as:

Enter the value of n and r :


For example, if the user gives the input as:
Enter the value of n and r : 5 3
then the program should print the result as:
The value of 5c3 = 10
Note: Write the recursive function factorial() in RecursiveFactorial.c
Problem Solution:
The algorithm used in this program is nCr = n! /((n-r)!r!). Here we need to find all the
possible combination of the value n and r. A combination is one or more elements
selected from a set without regard to the order. The “without regard” means that the
collection matters rather than order in combinations, so in the above example, the fact we
ABC, ACB, BAC, BCA, CAB, CBA… for combinations, these are all 1 combination of
letters A, B and C.
Source Code:
FindingNcr.c
#include <stdio.h>
#include"RecursiveFactorial.c"
void main() {

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 85


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

long int n, r;
printf("Enter the value of n and r : ");
scanf("%ld%ld", &n, &r);
printf("The value of %ldc%ld = %ld\n", n, r, FindNcr(n, r));
}
RecursiveFactorial.c
long int factorial(long int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
long int FindNcr(long int n, long int r) {
long result;
result = factorial(n) / (factorial(r) * factorial(n - r));
return result;
}
Test Case – 1
User Output
Enter the value of n and r : 6 2
The value of 6c2 = 15
Test Case – 2
User Output
Enter the value of n and r : 5 3
The value of 5c3 = 10
Test Case – 3
User Output
Enter the value of n and r : 15 6
The value of 15c6 = 5005

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 86


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case – 4
User Output
Enter the value of n and r : 18 10
The value of 18c10 = 43758

ii. Write a C function to find length of a string


Description:
The Number of characters in the string constitutes the length of the string. We have to note
that even blank spaces are also counted as characters in the string. Every string is
terminated by „\0‟ (NULL) character.
Problem Solution:
1. Take a string as input and store it in the array.
2. Using for loop count the number of characters in the array and store the result in a
variable.
3. Print the variable as output.
Algorithm:
START
Step 1: Length = 0
Step 2: Repeat step 3 while S1 [Length] ≠ NULL
Step 3: Length = Length + 1
Step 4: Return Length
STOP
Source Code:
StrLength.c
#include <stdio.h>
#include "StrLength1.c"
void main() {
char str[30];
printf("Enter the string : ");
scanf("%s", str);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 87


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf("Length of %s : %d\n", str, myStrLen(str));


}
StrLength1.c
int myStrLen(char str1[30]) {
int Length = 0;
while (str1[Length] != '\0')
Length++;
return Length;
}
Test Case-1
User Output
Enter the string : CodeTantra
Length of CodeTantra : 10
Test Case-2
User Output
Enter the string : IndoUsUk
Length of IndoUsUk : 8
Test Case-3
User Output
Enter the string : MalayalaM
Length of MalayalaM : 9
Test Case-4
User Output
Enter the string : Oh!MyGod
Length of Oh!MyGod : 8

iii. Write a C function to transpose of a matrix


Description:
This C program prints transpose of a matrix. It is obtained by interchanging rows and
columns of a matrix. For example, consider the following 3 X 2 matrix:

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 88


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

12
34
56
Transpose of the matrix:
135
246
When we transpose a matrix then its order changes, but for a square matrix it remains the
same.
Algorithm:
START
Step 1: Declare matrix a[m][n] of order mxn
Step 2: Read matrix a[m][n] from User
Step 3: Declare matrix b[m][n] of order mxn
Step 4: // Transposing the Matrix
4.1: Declare variables i, j
4.2: Set i=0, j=0
4.3: Repeat until i < n
4.3.1: Repeat until j < m
b[i][j] = a[j][i]
j=j+1 // Increment j by 1
i=i+1 // Increment i by 1
4.4: Print matrix b
// The matrix b is the transpose of a and can be printed now
STOP
Source Code:
TransposeFunction.c
#include <stdio.h>
#include "TransposeFunction1.c"
void main() {
int a[5][5], b[5][5], m, n, p, q; printf("Enter the size of matrix : "); scanf("%d%d", &m, &n);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 89


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

read(a, m, n);
printf("The given matrix is\n"); display(a, m, n); transposeMatrix(a,b, m, n);
printf("The transpose matrix is\n");
display(b, n, m);
}
TransposeFunction1.c
void read(int x[5][5], int m, int n) {
int i, j;
printf("Enter %d elements : ", m*n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &x[i][j]);
}
}
}
void display(int y[5][5], int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", y[i][j]);
}
printf("\n");
}
void transposeMatrix(int a[5][5], int b[5][5], int m, int n)
{
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
b[j][i] = a[i][j];
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 90


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

}
}
Test Case-1
User Output
Enter the size of matrix : 2 2
Enter 4 elements : 1 2 3 4
The given matrix is
12
34
The transpose matrix is
13
24
Test Case-2
User Output
Enter the size of matrix : 2 3
Enter 6 elements: 22 33 44 55 66 77
The given matrix is
22 33 44
55 66 77
The transpose matrix is
22 55
33 66
44 77
Test Case-3
User Output
Enter the size of matrix : 3 3
Enter 9 elements : 11 22 55 66 44 77 88 99 33
The given matrix is
11 22 55
66 44 77

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 91


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

88 99 33
The transpose matrix is
11 66 88
22 44 99
55 77 33
Test Case -4
User Output
Enter the size of matrix : 3 2
Enter 6 elements : 111 222 333 444 555 666
The given matrix is
111 222
333 444
555 666
The transpose matrix is
111 333 555
222 444 666
Additional Program:
Aim: Write a C function to demonstrate numerical integration of differential equations using
Eulers’s method
Description:
In Euler’s method, one can find a clear expression for y in terms of a finite number of
elementary functions represented with x. The initial values of y and x are known, and for
these an ordinary differential equation is considered. Now, let us look at the mathematics
and algorithm behind the Euler’s method. A sequence of short lines is approximated to
find the curve of solution; this means considering tangent line in each interval. Using the
information obtained from here, the value of ‘yn’ corresponding to the value of ‘xn‘ is to
determine by dividing the length (xn – x) into n intervals or strips.
So, strip width= (xn – x)/n and xn=x0+ nh.
Again, if m be the slope of the curve at point, y1= y0 + m(x0 , y0)h.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 92


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Now, from this all the intermediate ‘y’ values can be found. This method was developed by
Leonhard Euler.
Algorithm:
START
Step-1: Define function
Step-2: Get the values of x0, y0, h and xn
*Here x0 and y0 are the initial conditions
h is the interval
xn is the required value
Step-3: n = (xn – x0)/h + 1
Step-4: Start loop from i=1 to n
Step-5: y = y0 + h*f(x0,y0)
x=x+h
Step-6: Print values of y0 and x0
Step-7: Check if x < xn
If yes, assign x0 = x and y0 = y
If no, goto 9.
Step-8: End loop i
STOP
Flowchart:

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 93


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Source Code:
#include<stdio.h>
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 94


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 95


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-10
Objective: Explore how recursive solutions can be programmed by writing recursive
functions that can be invoked from main by programming at-least 5 distinct problems that
have naturally recursive solutions.
i. Write a recursive function to generate Fibonacci series
Description:
A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0
and 1. Subsequent terms are found by adding the preceding two terms in the sequence.
Algorithm for Main
START
Step 2: Declare n,i=0, c
Step 3: Read terms to n
Step 4: Set Loop counter c with 1 to n Step 4.1: call fib_rec(i)
Step 4.2: c++, i++
Step 5 call fib_nonrec(n)
STOP
Algorithm for the Recursive Function
START
Step 1: int fib_rec(int n)
Step 2: if(n==0)
return(0) else if(n==1)
retuen(1) else
return(fib_rec(n-1)+fib_rec(n-2))
STOP
Algorithm for the Non_Recursive Function
START
Step 1: int fib_nonrec(n)
Step 2: Declare i=0,first=0;second=1;fib=0
Step 3: Set loop Counter i from 0 to n)
begin

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 96


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

if(i<=1)
fib=i
else
fib=first + second
first = second
second=fib
end if
print fib
increment i with 1
end
STOP
Source Code :
#include<stdio.h>
int fib_rec(int);
int fib_non_rec(int); int main()
{
int n, i = 0, c;
printf("\nEnter No. of Terms: ");
scanf("%d",&n);
printf("Fibonacci series with recursion: \n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%3d", fib_rec(i)); i++;
}
fib_non_rec(n);
return 0;
}
int fib_non_rec(int n)
{
int i=0,first=0,second=1,fib=0;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 97


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf("\nFibonocci series with Non_recursion: \n");


for(i=0;i<n;i++)
{
if(i<=1)
fib=i;
else
{
fib=first + second;
first=second;
second=fib;
}
printf("%3d",fib);
}
return 0;
}
int fib_rec(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( fib_rec(n-1) +fib_rec(n-2) );
}
Test Case-1
Enter No. of Terms: 5
Fibonocci series with recursion: 0 1 1 2 3
Fibonocci series with Non-recursion: 0 1 1 2 3
Test Case-2
Enter No. of Terms: 8

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 98


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Fibonocci series with recursion: 0 1 1 2 3 5 8 13


Fibonocci series with Non-recursion: 0 1 1 2 3 5 8 13

ii. Write a recursive function to find the lcm of two numbers


Source code:
#include<stdio.h>
int lcm(int a, int b)
{
static int multiple = 0;
multiple+=a;
if((multiple % a == 0) && (multiple % b == 0))
return multiple;
else
return lcm(a,b);
}
void main()
{
int a,b;
printf("Enter two numbers a,b:");
scanf("%d%d",&a,&b);
printf("LCM of %d,%d = %d",a,b,lcm(a,b));
}
Test Case-1
Enter two numbers a,b:
45, 81
LCM of 45,81 = 405
Enter two numbers a,b:
63, 72
LCM of 45,81 = 504

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 99


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iii. Write a recursive function to find the factorial of a number


Description:
A recursive function is a function that calls itself directly or indirectly (or) a function is said
to be recursive if the function refers to itself. Every recursive function must satisfy two
properties.
✓ Base Criteria
✓ Recursive Step
Base Criteria:
There must be certain criteria in recursive function called based criteria, in which the
function does not call itself.
Recursive step:
In this condition, each time the function call itself directly or indirectly. But the arguments of
the function must be closer to the intial condition or base criteria.
The operation of recursive factorial function is as follows:
Start out with some natural number N. The recursive definition is :

N = 0, 0! = 1…………………..Base Case
N > 0, N! = N * (N-1)!..............Recursive Case
Algorithm:
START
Step 1: Declare fact=1
Step 2: Read any integer(n)
Step 3: if (n==0) then write factorial as 1 else begin
end
STOP
Algorithm for Recursive Function
START
Step 1: int rec_fact(int n)
Step 2: return (n>=1) ? n* rec_fact(n-1) : 1
Step 3: Exit

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 100


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

STOP
Algorithm for Non-Recursive Function
START
Step 1: int nonrec_fact(int n)
Step 2: for(i=1;i<=n;i++)
fact*=i; return fact;
Step 3: Exit
STOP
Flowchart
Flowchart of main program:

Flowchart of sub programs

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 101


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("\nEnter any integer: ");
scanf("%d",&n);
if(n==0)
printf("Factorial of 0 is 1");
else
{
printf("\nFactorial of %d using Recursive method is %d",n,rec_fact(n)); printf("\nFactorial of
%d using Non-Recursive method is %d",n,nonrec_fact(n));
}
getch();
}
int rec_fact(int n)
{
return (n>=1) ? n* rec_fact(n-1) : 1;
}
int nonrec_fact(int n)
{
int fact=1;
int i;
for(i=1;i<=n;i++)
{
fact*=i;
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 102


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

return fact;
}
Test Case-1
Enter any integer: 0
Factorial of 0 is 1
Test Case-2
Enter any integer: 5
Factorial of 5
using Recursive method is 120 Factorial of 5
using Non-Recursive method is 120

iv. Write a C Program to implement Ackermann function using recursion


Ackermann Function:
Ackermann-Peter function is defined as follows for non-negative integers m, n :
A(m,n) = n+1 if m=0.
A(m-1,1) if m>0 and n=0.
A(m-1,A(m,n-1) if m>0 and n>0.
Source code:
#include<stdio.h>
unsigned int ack(unsigned int m, unsigned int n)
{
if(m==0)
return n+1;
else if(n==0)
return ack(m-1,1);
else
return ack(m-1,ack(m,n-1));
}
void main()
{

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 103


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

unsigned int m,n;


printf("Enter values for m,n:");
scanf("%u%u",&m,&n);
printf("ack(%u,%u)=%u",m,n,ack(m,n));
}
Test Case-1
Enter values for m,n:
2, 3
ack(2,3)=9
Enter values for m,n:
0, 1
ack(0,1)=2

v. Write a recursive function to find the sum of series.


ex = 1+x1/1!+x2/2!+x3/3!+........+xn/n!
Source code:
#include<stdio.h>
#include<math.h>
unsigned int fact(unsigned int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
float ex(int x, int n)
{
if(n==0)
return 1;
else

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 104


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

return ((float)pow(x,n)/fact(n))+ex(x,n-1);
}

void main()
{
int x,n;
printf("Enter values for x,n:");
scanf("%d%d",&x,&n);
printf("e%d upto %d terms = %f",x,n,ex(x,n));
}
Test Case-1
Enter values for x,n:
3, 10
e3 upto 10 terms = 20.079666
Enter values for x,n:
5, 15
e5 upto 10 terms = 168.743668

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 105


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-11
Objective: Explore the basic difference between normal and pointer variables, Arithmetic
operations using pointers and passing variables to functions using pointers
i. Write a C program to swap two numbers using call by reference
Source Code:
#include<stdio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a, *a=*b, *b=temp;
}
void main()
{
int a,b;
printf("Enter values into a,b:");
scanf("%d%d",&a,&b);
printf("Before swap: a=%d, b=%d\n",a,b);
swap(&a,&b);
printf("After swap: a=%d, b=%d",a,b);
}
Test Case 1:
Enter values into a,b:
2, 42
Before swap: a=2, b=42
After swap: a=42, b=2
Enter values into a,b:
3, 57
Before swap: a=3, b=57
After swap: a=57, b=3

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 106


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

ii. Demonstrate Dangling pointer problem using a C program


Description: A pointer pointing to a location that has been deleted (freed) already.
Source Code:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr1,*ptr2;
ptr1=(int*)malloc(sizeof(int));
if(ptr1!=NULL)
{
*ptr1=42;
ptr2=ptr1;
printf("the value being pointed by ptr2 = %d",*ptr2);
free(ptr1);
printf("\nthis is a dangling pointer now: %d",*ptr2);
}
else
printf("memory not allocated for ptr1");
}

Test Case 2:
the value being pointed by ptr2 = 42
this is a dangling pointer now: 0

iii. Write a C program to copy one string into another using pointers
Source Code:
#include<stdio.h>
void main()
{

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 107


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

char str1[20],str2[20],*ptr,i=0;
printf("Enter a string:");
gets(str1);
ptr=str1;
while(*ptr!='\0')
str2[i++]=*ptr++;
str2[i]='\0';
printf("str2 = %s",str2);
}
Test Case-1
Enter string1: MVGR College of Engineering
string2 = MVGR College of Engineering
Enter string1: IT Department
string2 = IT Department

iv. Write a C program to find no of lowercases, uppercase, digits and other characters
using pointers.
Source Code:
#include<stdio.h>
void main()
{
char str[20],ch;
int i=0,upper=0,lower=0,digits=0,others=0;
printf("Enter a string:");
gets(str);
while((ch=str[i++])!='\0')
if(ch>=48&&ch<=57)
digits++;
else if(ch>=65&&ch<=90)
upper++;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 108


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

else if(ch>=97&&ch<=122)
lower++;
else
others++;
printf("upper case=%d, lower case=%d, digits=%d,
others=%d",upper,lower,digits,others);
}
Test Case-1
Enter a string: MVGR_College@Vzm-535005
upper case=6, lower case=8, digits=6, others=3
Enter a string: Pack: 1L, B28
upper case=3, lower case=3, digits=3, others=4

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 109


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

UNIT – V
WEEK-12
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation & value initialization, resizing changing and reordering the contents of an array
and memory de-allocation using malloc(), calloc(), realloc() and free() functions. Gain
experience processing command-line arguments received by C
i. Write a C program to find sum of 1D array using malloc()
Description:
Dynamic memory allocation is an aspect of allocating and freeing memory according to your
needs. Dynamic memory is managed and served with pointers that point to the newly
allocated space of memory in an area which we call the heap.
The <stdlib.h> library has functions responsible for dynamic memory management.
malloc: Allocates the memory of requested size and returns the pointer to the first byte of
allocated space.
Syntax: ptr = (cast_type *) malloc (byte_size);
This program is used to find the sum of array elements by allocating memory using malloc()
function. malloc() is a function which is used to create the memory dynamically at run
time for the given ‘n’ value by using the concept of pointers. The malloc() function is
present in stdlib.h header file.
Algorithm:
START
Step 1: Declare pointer variable, n.
Step 2: Read ‘n’ value.
Step 3: Call allocate memory function() for allocation of memory.
Step 4: Read the values by calling read() function.
Step 5: Calculate total by calling sum function.
Step 6: Print sum of array elements.
STOP

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 110


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include "UsingMalloc.c"
void main() {
int *p, n, i;
printf("Enter n value : ");
scanf("%d", &n);
p = allocateMemory(n);
printf("Enter %d values : ", n);
read(p, n);
printf("The sum of given array elements : %d\n", sum(p, n));
}
int* allocateMemory(int n) {
return (int *)malloc(n * sizeof(int));
}
void read(int *p, int n) {
int i;
for (i = 0; i < n; i++) {
scanf("%d", p + i);
}
}
int sum(int *p, int n) {
int i, total = 0;
for (i = 0; i < n; i++) {
total = total + *(p + i);
}
return total;
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 111


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case - 1
User Output
Enter n value: 4
Enter 4 values: 1 4 5 2
The sum of given array elements: 12
Test Case - 2
User Output
Enter n value: 4
Enter 4 values: -5 -6 -4 -2
The sum of given array elements: -17
Test Case - 3
User Output
Enter n value: 3
Enter 3 values: 10 20 30
The sum of given array elements: 60

ii. Write a C program to find the total, average of n students using structures
Description:
A structure is a composition of variables possibly of different data types, grouped together
under a single name. Each variable within the structure is called a ‘member’.

Operations performed Syntax / Description Example


struct structure-name
{
struct student
type member-1 ;
{
type member-2;
char name[20];
Declaring a structure .
int rollno;
.
int marks;
type member-n ;
};
};

Creating structure variables struct structurename variable; struct student stud1;

Accessing structure members variable.member stud1.name

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 112


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

stud1.rollno
stud1.marks

the initialization values have to struct student stud1 =


initializing a structure variable
be given in {} and in order {“ABCD”,10,95};

This program can be written using the concept of structures. A structure is a collection of
elements of different datatypes. we can create structure, declare structure variables and
accessing of members can be done using dot operator. The size of the structure is the sum of
the datatype size.
Algorithm:
START
Step 1: Create a student structure with roll number, name and marks as fields.
Step 2: Read n value.
Step 3: Read n students data.
Step 4: Calculate the sum of n students.
Step 5: Calculate the average marks of the students.
Step 6: Print the details of the students whose marks are above and below the average marks.
STOP
Source Code:
#include <stdio.h>
struct student {
int roll;
char name[50];
int marks;
};
void main() {
struct student s[10];
int i, n, sum = 0;
float average = 0;
printf("Enter the number of students : ");
scanf("%d", &n);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 113


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

for (i = 0; i < n; i++) {


printf("Enter the details of student - %d\n", i+1);
printf("Enter the roll number : ");
scanf("%d", &s[i].roll);
printf("Enter the name : ");
scanf("%s", s[i].name);
printf("Enter total marks : ");
scanf("%d", &s[i].marks);
}
for (i = 0; i < n; i++) {
sum = sum + s[i].marks;
}
average = (float)sum / n;
printf("Class average : %f\n", average);
printf("RollNo\tStudentName\tTotalMarks\tAboveAverage(Y/N)\n");
for (i = 0; i < n; i++) {
printf("%4d", s[i].roll);
printf("%15s", s[i].name);
printf("%15d", s[i].marks);
if(s[i].marks >= average)
printf("\tYes");
else
printf("\tNo");
printf("\n");
}}
Test Case - 1
User Output
Enter the number of students : 3
Enter the details of student - 1 101
Enter the roll number : 101

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 114


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Enter the name : Ganga


Enter total marks : 78
Enter the details of student - 2 102
Enter the roll number : 102
Enter the name : Saraswathi
Enter total marks : 83
Enter the details of student - 3 103
Enter the roll number : 103
Enter the name : Lakshmi
Enter total marks : 79
Class average : 80.000000
RollNo StudentName TotalMarks AboveAverage(Y/N)
101 Ganga 78 No
102 Saraswathi 83 Yes
103 Lakshmi 79 No
Test Case - 2
User Output
Enter the number of students : 2
Enter the details of student - 1 501
Enter the roll number : 501
Enter the name : Sindhu
Enter total marks : 68
Enter the details of student - 2 502
Enter the roll number : 502
Enter the name : Saina
Enter total marks : 68
Class average : 68.000000
RollNo StudentName TotalMarks AboveAverage(Y/N)
501 Sindhu 68 Yes
502 Saina 68 Yes

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 115


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

iii. Enter n students data using calloc() and display failed students list
Description:
calloc: Allocates the space for elements of an array. Initializes the elements to zero and
returns a pointer to the memory.
Syntax: ptr = (cast_type *) calloc (n, size);
This program can be written by using structures and the memory allocation for n students can
be done using calloc() function. calloc() function is dynamic memory allocation function
which is used to allocate blocks of memory dynamically at runtime for n students. This
function is present in stdlib.h header file.
Algorithm:
START
Step 1: Create a student structure with roll number,name,marks.
Step 2: Read ‘n’ value.
Step 3: Allocate memory for n students using allocateMemory() function.
Step 4: Read n students data using read() function.
Step 5: Calculate sum of the marks using calculatemarks() function.
Step 6: Calculate the average marks of n students.
Step 7: Print the details of the students with fail and pass status.
STOP
Source Code:
#include <stdio.h>
#include <stdlib.h>
struct student {
int roll;
int marks[6], sum;
float avg;
};
#include "FailedList1.c"
void main() {
struct student *s;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 116


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

int i, n;
printf("Enter the number of students : ");
scanf("%d", &n);
s = allocateMemory(s, n);
read(s, n);
calculateMarks(s, n);
displayFailedList(s, n);
}
struct student* allocateMemory(struct student *s, int n) {
s = (struct student *)calloc(n, sizeof(struct student));
return s;
}
void read(struct student *s, int n) {
int i;
for (i = 0; i < n; i++) {
printf("Enter the details of student - %d\n", i+1);
printf("Enter the roll number : ");
scanf("%d", &s[i].roll);
printf("Enter 6 sujects marks : ");
scanf("%d%d%d%d%d%d", &s[i].marks[0], &s[i].marks[1], &s[i].marks[2], &s[i].marks
[3], &s[i].marks[4], &s[i].marks[5]);
}
}
void calculateMarks(struct student *s, int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < 6; j++)
s[i].sum = s[i].sum + s[i].marks[j];
}
for (i = 0; i < n; i++) {

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 117


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

s[i].avg = (float)s[i].sum / 6;
}
}
void displayFailedList(struct student *s, int n) {
int i;
printf("RollNo\tTotalMarks\tAverageMarks\tStatus\n");
for (i = 0; i < n; i++) {
printf("%d\t", s[i].roll);
printf("%d\t", s[i].sum);
printf("%f\t", s[i].avg);
if(s[i].marks[0] < 35 || s[i].marks[1] < 35 || s[i].marks[2] < 35 || s[i].marks
[3] < 35 || s[i].marks[4] < 35 || s[i].marks[5] < 35)
printf("Fail");
else
printf("Pass");
printf("\n");
}
Test Case - 1
User Output
Enter the number of students : 3
Enter the details of student - 1 101
Enter the roll number : 101
Enter 6 sujects marks : 45 67 58 36 59 63
Enter the details of student - 2 102
Enter the roll number : 102
Enter 6 sujects marks : 34 56 98 39 78 89
Enter the details of student - 3 103
Enter the roll number : 103
Enter 6 subjects marks : 35 67 89 98 76 56
RollNo TotalMarks AverageMarks Status

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 118


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

101 328 54.666668 Pass


102 394 65.666664 Fail
103 421 70.166664 Pass
Test Case-2
User Output
Enter the number of students : 2
Enter the details of student - 1 1001
Enter the roll number : 1001
Enter 6 subjects marks : 26 57 68 67 67 65
Enter the details of student - 2 1002
Enter the roll number : 1002
Enter 6 subjects marks : 58 67 58 89 87 76
RollNo TotalMarks AverageMarks Status
1001 350 58.333332 Fail
1002 435 72.500000 Pass

iv. Read student name and marks from the command line and display the student
details along with total.
Description:
Command line arguments are passed to the main() method. Here argc counts the number of
arguments on the command line and argv[] is a pointer array which holds pointers of type
char which points to the arguments passed to the program.
Syntax: int main(argc c, char *argv[])
This program can be written using the concept of command line arguments.Command line
arguments are used to take input from the command line.main() function conatins 2
arguments argc and char*argv[] which receives the data only in the form of strings only
from the command line.the numeric sring scxan be converted using atoi() function.
Algorithm:
START
Step 1: Read Student name by taking input from command line as argv[1]

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 119


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Step 2: Read marks1 by taking input from command line as argv[2]


Step 3: Read marks2 by taking input from command line as argv[3]
Step 4: Read marks3 by taking input from command line as argv[4]
Step 5: calculate sum of marks1,marks2, marks3 by converting them into integers
Step 6: Print sum
STOP
Source Code:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 5) {
printf("Arguments passed through command line are not equal to 4\n");
return 1;
}
printf("Student name : %s\n", argv[1]);
printf("Subject-1 marks : %s\n", argv[2]);
printf("Subject-1 marks : %s\n", argv[3]);
printf("Subject-1 marks : %s\n", argv[4]);
int sum;
sum = atoi(argv[2]) + atoi(argv[3]) + atoi(argv[4]);
printf("Total marks : %d\n", sum);
return 0;
}
Test case-1
If the arguments passed as $./TotalMarksArgs.c Sachin 67 89 58, then the program should
print the output as:
Cmd Args : Sachin 67 89 58
Student name : Sachin
Subject-1 marks : 67
Subject-1 marks : 89
Subject-1 marks : 58

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 120


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Total marks : 214


Test case-2
If the arguments passed as $./TotalMarksArgs.c Johny 45 86 57 48 , then the program
should print the output as:
Cmd Args : Johny 45 86 57 48
Arguments passed through command line are not equal to 4

v. Write a C program to implement realloc()


Description:
realloc :It is used to modify the size of previously allocated memory space.
Syntax: ptr = realloc (ptr,newsize);
free: Frees or empties the previously allocated memory space.
Syntax: free(ptr);
This program can be written using malloc() and relloc() dynamic memory allocation
functions.malloc() is used to allocate the memory dynamically at run time for given n
value where as realloc() is used to reallocate the memory for n values ,both are available
in stdlib.h header file.
Algorithm:
START
Step 1: Allocate memory of an array with size 2 by using malloc()
Step 2: Assign the values 10 and 20 to the array
Step 3: Rellocate the size of the array to 3 by using realloc()
Step 4: Assign the value 30 to the newly allocated block
Step 5: Display all the 3 values
STOP
Source Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int) * 2);

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 121


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

int i;
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
// Reallocate the *ptr size to 3
//Assign the value 30 to newly allocated memory
ptr_new = (int *)realloc(ptr, sizeof(int) * 3);
*(ptr_new + 2) = 30;
for (i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
}
Test Case - 1
User Output
10 20 30
Additional Programs for practice:
vi. Write a C program to check the given string is palindrome or not allocate memory
using malloc() function.
vii. Write a C program to read and print employee details using calloc() function.
viii. Write a C program to display the names whose name starting with the letter ‘R’ by
taking input from the command line.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 122


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-13
Objective: Experiment with C Structures, Unions, bit fields and self-referential
structures (Singly linked lists) and nested structures
i. Read and print a date using dd/mm/yyyy format using bit-fields and differentiate
the same without using bit-fields
Description:
Suppose your C program contains a number of TRUE/FALSE variables grouped in a
structure called status, as follows:
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual we are going to store either
0 or 1 in each of the variables. The C programming language offers a better way to utilize
the memory space in such situation. If you are using such variables inside a structure then
you can define the width of a variable which tells the C compiler that you are going to
use only those numbers of bytes.
For example, above structure can be re-written as follows:
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
Now, the above structure will require 4 bytes of memory space for status variable but
only 2 bits will be used to store the values. If you will use up to 32 variables each one
with a width of 1 bit, then also status structure will use 4 bytes, but as soon as you will
have 33 variables, then it will allocate next slot of the memory and it will start using 8
bytes.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 123


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Algorithm:
START
Step 1: Create a structure date with bit fields
Step 2: Assign the day, month and year to the members
Step 3: Display the structure member values along with size of the structure
STOP
Source Code:
#include <stdio.h>
struct date {
unsigned int day : 5; unsigned int month : 4; unsigned int year;
};
struct date1 { unsigned int day; unsigned int month; unsigned int year;
};
void main() { struct date d; struct date1 d1;
printf("Enter a date : ");
scanf("%d%d%d", &d1.day, &d1.month, &d1.year);
d.day = d1.day; d.month = d1.month; d.year = d1.year;
printf("The size of the structure without bit-fields : %zu\n", sizeof(struct date
1));
printf("Date stored without bit-fields : %d/%d/%d\n", d1.day, d1.month, d1.year);
printf("The size of the structure uses bit-fields : %zu\n", sizeof(struct date)); printf("Date
stored in bit-fields : %d/%d/%d\n", d.day, d.month, d.year);
}
Test Case - 1
Enter a date : 23 8 1998
The size of the structure without bit-fields : 12
Date stored without bit-fields : 23/8/1998
The size of the structure uses bit-fields : 8
Date stored in bit-fields : 23/8/1998

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 124


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case - 2
Enter a date : 29 02 2016
The size of the structure without bit-fields : 12
Date stored without bit-fields : 29/2/2016
The size of the structure uses bit-fields : 8
Date stored in bit-fields : 29/2/2016
Test Case - 3
User Output
Enter a date : 1 1 2020
The size of the structure without bit-fields : 12
Date stored without bit-fields : 1/1/2020
The size of the structure uses bit-fields : 8
Date stored in bit-fields : 1/1/2020
Test Case - 4
User Output
Enter a date : 31 12 2018
The size of the structure without bit-fields : 12
Date stored without bit-fields : 31/12/2018
The size of the structure uses bit-fields : 8
Date stored in bit-fields : 31/12/2018

ii. Create and display a singly linked list using self-referential structure
Description:
Linked List is a linear data structure and it is very common data structure which consists
of group of nodes in a sequence which is divided in two parts. Each node consists of its
own data and the address of the next node and forms a chain. Linked Lists are used to
create trees and graphs.
Advantages of Linked Lists:
➢ They are a dynamic in nature which allocates the memory when required.
➢ Insertion and deletion operations can be easily implemented.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 125


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

➢ Stacks and queues can be easily executed.


➢ Linked List reduces the access time.
Disadvantages of Linked Lists:
➢ The memory is wasted as pointers require extra memory for storage.
➢ No element can be accessed randomly; it has to access each node sequentially.
➢ Reverse Traversing is difficult in linked list.
Applications of Linked Lists
➢ Linked lists are used to implement stacks, queues, graphs, etc.
➢ Linked lists let you insert elements at the beginning and end of the list.
➢ In Linked Lists we don’t need to know the size in advance.
Singly Linked List: Singly linked lists contain nodes which have a data part as well as an
address part i.e. next, which points to the next node in sequence of nodes. The operations
we can perform on singly linked lists are insertion, deletion and traversal.

Algorithm for addNodes(NODE first, int x) is as follows:


START
Step-1: Allocate memory to the node temp .
Step-2: Store an integer value into data field of node temp .
Step-3: If the first is referenced to NULL then assign temp to first node, otherwise
traverse the list up to the last node (meaning the next field of a
node contains Null ) and then assign the temp node to next field of the
lastNode .
Step-4: Finally return the first node.
STOP

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 126


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Algorithm for traverseList(NODE first) is as follows:


START
Step-1: Assign the address contained in first node to temp node. Step-2: Print the data
field of the temp .
Step-3: Move to the next node by placing the address of the next node into the temp
node.
Step-4: Repeat Stet-2 and Step-3 until temp is NULL .
Step-5: Finally print "NULL" at the end of the list.
STOP
Source Code:
SingleLL1.c
#include<stdio.h>
#include<stdlib.h>
#include "CreateAndAddNodes.c" void main() {
NODE first = NULL;
int x;
printf("Enter elements up to -1 : ");
scanf("%d", &x);
while (x != -1) {
first = addNodes(first, x);
scanf("%d", &x);
}
if (first == NULL) {
printf("Single Linked List is empty\n");
} else {
printf("The elements in SLL are : ");
traverseList(first);
}
}
CreateAndAddNodes.c

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 127


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

struct node {
int data;
struct node *next;
};
typedef struct node *NODE;
NODE createNode() { NODE temp;
temp = (NODE) malloc(sizeof(struct node));
temp -> next = NULL;
return temp;
}
NODE addNodes(NODE first, int x) { NODE temp, lastNode = first; temp =
createNode();
temp -> data = x;
if (first == NULL) {
first = temp;
} else {
while (lastNode -> next != NULL) {
lastNode = lastNode -> next;
}
lastNode -> next = temp;
}
return first;
}
void traverseList(NODE first) { NODE temp = first;
while (temp != NULL) {
printf("%d --> ",temp -> data);
temp = temp -> next;
}
printf("NULL\n");
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 128


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case - 1
User Output
Enter elements up to -1 : 9 18 27 36 45 -1
The elements in SLL are : 9 --> 18 --> 27 --> 36 --> 45 --> NULL
Test Case - 2
User Output
Enter elements up to -1 : 12 14 19 23 -1
The elements in SLL are : 12 --> 14 --> 19 --> 23 --> NULL

iii. Demonstrate the differences between structures and unions using a C program
Operations Syntax Example
performed
Creating a nested struct structure1 struct student
structure { {
... int rollno; char name[20];
struct structure2 struct date
{ {
... int dd, mm, yy;
} variable; } bdate, admdate;
... };
};
struct date
Method 2 {
struct structure2 int dd, mm, yy;
{ };
...
}; struct student
{
struct structure1 int rollno; char name[20];
{ struct date bdate, admdate;
... };
struct structure2 variable;

Accessing nested structure members can be stud1.bdate.dd,


nested structure accessed using the (.) operator stud1.bdate.mm
members repeatedly.
self referential A structure containing a pointer struct node
structure to the same structure {
int info;
struct node *next;
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 129


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Unions A union is a variable that contains union u


multiple members of possibly {
different data types grouped char a;
together under a single name.
int b;
However, only one of
};
the members can be used at a
time. They occupy the same
memory area.

A structure is a composition of variables possibly of different data types, grouped together under
a single name. Each variable within the structure is called a ‘member’.
Operations Syntax / Description Example
performed

Declaring a structure struct structure-name struct student


{ {
type member-1 ; char name[20];
type member-2; int rollno;
. int marks;
. };
type member-n ;
};
Creating structure struct structurename variable; struct student stud1;
variables
Accessing structure variable.member stud1.name stud1.rollno
members stud1.marks

initializing a structure the initialization values have to be struct student stud1 =


variable given in {} and in order {“ABCD”,10,95};

Pointer to a structure struct structure-name * pointer- struct student *ptr;


name; ptr = &stud1;
Accessing members pointer-name -> member-name; ptr->name; ptr->rollno;
using Pointer

Array of structures struct structure-name array- struct student stud[10];


name[size];
passing Structures to return-type function-name ( struct void display(struct student
Functions structure-name variable); s);

pass an array of return-type function-name ( struct void display(struct student


structures to a structure-name array[size]); stud[10]);
function

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 130


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Algorithm:
START
Step 1: Create a structure student-1 with members rollno, m1, m2, m3, total of int type
and avg of float type
Step 2: Read rollno, m1, m2 and m3 of student-1
Step 3: Find and display total and average marks of student-1
Step 4: Display the size of struct student-1
Step 5: Create a union student-2 with members rollno, m1, m2, m3, total of int type and
avg of float type
Step 6: Read rollno, m1, m2 and m3 of student-2
Step 7: Find and display total and average marks of student-2
Step 8: Display the size of union student-2
STOP
Source Code:
#include <stdio.h>
struct student1 {
int rollno;
int m1, m2, m3, total;
float avg;
};
union student2 {
int rollno;
int m1, m2, m3, total;
float avg;
};
void main() {
union student2 u;
struct student1 s;
int sum = 0;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 131


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

printf("Enter rollno and 3 subjects marks of student - 1 : "); scanf("%d%d%d%d",


&s.rollno, &s.m1, &s.m2, &s.m3); s.total = s.m1 + s.m2 + s.m3;
s.avg = s.total/3.0;
printf("Total and average marks of student - 1 : %d %f\n", s.total, s.avg);
printf("Size of struct student - 1 : %zu\n", sizeof(struct student1));
printf("Enter rollno of student - 2 : ");
scanf("%d", &u.rollno);
printf("Enter first subject marks of student - 2 : ");
scanf("%d", &u.m1);
sum = u.m1;
printf("Enterl second subject marks of student - 2 : ");
scanf("%d", &u.m2);
sum = sum + u.m2;
printf("Enter third subject marks of student - 2 : ");
scanf("%d", &u.m3);
sum = sum + u.m3;
u.total = sum;
printf("Total marks of student - 2 : %d\n", u.total); u.avg = u.total/3.0;
printf("Average marks of student - 2 : %f\n", u.avg);
printf("Size of union student - 2 : %zu\n", sizeof(union student2));
}
Test Case - 1
Enter rollno and 3 subjects marks of student - 1 : 101 76 58 67
Total and average marks of student - 1 : 201 67.000000 102
Size of struct student - 1 : 24 102
Enter rollno of student - 2 : 102
Enter first subject marks of student - 2 : 76
Enter second subject marks of student - 2 : 87
Enter third subject marks of student - 2 : 69
Total marks of student - 2 : 232

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 132


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Average marks of student - 2 : 77.333336


Size of union student - 2 : 4
Test Case - 2
Enter rollno and 3 subjects marks of student - 1 : 105 66 65 68
Total and average marks of student - 1 : 199 66.333336 106
Size of struct student - 1 : 24 106
Enter rollno of student - 2 : 106
Enter first subject marks of student - 2 : 88
Enter second subject marks of student - 2 : 89
Enter third subject marks of student - 2 : 79
Total marks of student - 2 : 256
Average marks of student - 2 : 85.333336
Size of union student - 2 : 4
Test Case - 3
Enter rollno and 3 subjects marks of student - 1 : 501 76 85 84
Total and average marks of student - 1 : 245 81.666664 502
Size of struct student - 1 : 24 502
Enter rollno of student - 2 : 502
Enter first subject marks of student - 2 : 99
Test Case - 3
Enterl second subject marks of student - 2 : 57
Enter third subject marks of student - 2 : 69
Total marks of student - 2 : 225
Average marks of student - 2 : 75.000000
Size of union student - 2 : 4
Test Case - 4
Enter rollno and 3 subjects marks of student - 1 : 201 75 46 59
Total and average marks of student - 1 : 180 60.000000 201
Size of struct student - 1 : 24 201
Enter rollno of student - 2 : 201

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 133


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Enter first subject marks of student - 2 : 66


Enter second subject marks of student - 2 : 57
Enter third subject marks of student - 2 : 61
Total marks of student - 2 : 184
Average marks of student - 2 : 61.333332
Size of union student - 2 : 4
Additional Programs for practice:
iv. Write a C program to shift rotate using bit fields
v. Write a C program to copy one structure variable to another structure of same type.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 134


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

WEEK-14
Objective: To Understand data files and file handling with various file I/O functions.
Explore the differences between text and binary files.
i. Write a C program to write and read text into a file
Description:
There are two library functions involve in writing the data into a file. They are fopen and
fwrite. Each of them are explained with their syntax below as :
FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode. It returns a pointer to
the stream upon success and NULL on failure.
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
writes data from the array pointed to, by ptr to the given stream. It returns the number of
elements successfully written, which may be less than nitems if a write error is
encountered. If size or nitems is 0, fwrite() shall return 0 and the state of the stream
remains unchanged. Otherwise, if a write error occurs, the error indicator for the stream
shall be set.
Algorithm:
START
Step 1: Store the contents to be written in a string.
Step 2: Open the source file in write mode using fopen.
Step 3: Write the contents of the string in to the file using fwrite.
STOP
Source Code:
/*string to file*/
#include<stdio.h>
void main(){
FILE *fp;
int i;
char *wbuf = "Hi\nWelcom to Files\nThis is just a start\n",rbuf[100];
fp=fopen("f2string","w+");

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 135


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

if(fp != NULL){
fwrite(wbuf,strlen(wbuf),1,fp);
printf("success\n");
}
else{
printf("failed to write\n");
}
}
Test Case-1
if the file f2string exists and writes successfully, then “success” is displayed
Test Case-2
if the file f2string exists and writes unsuccessfully, then “failed to write” is displayed
ii. Write a C program to write and read text into a binary file using fread() and
fwrite()
Description:
There are two library functions involve in writing the data into a binary file.
FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode. As we operate on a
binary file, we need to specify either of 'rb','wb' etc in modes.
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
writes data from the array pointed to, by ptr to the given stream.
Algorithm:
START
Step 1: Store the data to be written in to the binary file.
Step 2: Open the source binary file in write mode using fopen( )
Step 3: write the contents of the string in to the file using fwrite( )
STOP
Source Code:
#include <stdio.h>
#include <stdlib.h>

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 136


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

int main( ){
int n,a[5];
FILE *fptr;
if ((fptr = fopen("data.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
//Writing 5 numbers into binary file
for(n = 1; n < 5; ++n){
fwrite(&a[0],10, 1, fptr);
}
fclose(fptr);
return 0;
}
Test Case-1
if the file data.bin does not exist, then it displays "Error! Opening file"
Test Case-2
if the file data.bin exist and writing is successful, then data.bin must contain the numbers
in binary format.
iii. Copy the contents of one file to another file
Description:
There are four library functions involve in writing the data into a file.
FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode. As we operate on a file,
we need to specify either of 'r','w' etc in modes.
size_t fread(void *buffer, size_t size, size_t nmemb, FILE *stream)
reads data into the buffer from given stream.
size_t fwrite(const void *buffer, size_t size, size_t nmemb, FILE *stream)

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 137


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

writes data from the buffer array pointed, to the given stream. int fclose(FILE *stream),
closes the file I/O streams.
Algorithm:
START
Step 1: open source file in read mode
Step 2: open destination file in write mode
Step 3: read the contents of source file and write it into the destination file
Step 4: close both of the files
STOP
Source Code:
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdlib.h>
main (int argc,char *argv[]) {
int fd1,fd2,count;
char buf[512];
if(argc!=3) {
printf("provide sufficient file names");
exit(1);
}
else {
fd1=fopen(argv[1],O_RDONLY);
if(fd1==-1) {
printf("source file does not exist");
exit(1);
}
fd2=fopen(argv[2],O_WRONLY);
if(fd2==-1) {

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 138


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

fd2=creat(argv[2],0666);
}
while((count=fread(fd1,buf,sizeof(buf)))>0) {
fwrite(fd2,buf,count);
}
}
fclose(fd1);
fclose(fd2);
}
TEST CASE 1:
If both the source and destination file exists, then on successful execution destination file
contains the data as of source file.
TEST CASE 2:
If the source file exists and destination does not exist, then destination file is created and
on successful execution destination file contains the data as of source file.
iv. Write a C program to merge two files into the third file using command line
arguments
Description:
There are four library functions invole in writing the data into a file.
FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode. As we operate on a file,
we need to specify either of 'r','w' etc in modes.
int fgetc(FILE *pointer),
used to obtain input from a file single character at a time.
int fputc(int char, FILE *pointer),
used to write a single character at a time to a given file.
int fclose(FILE *stream),
closes the file I/O streams.
Algorithm:
START

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 139


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Step 1: open source files in read mode


Step 2: open destination file in write mode
Step 3: read the contents of source files and write them into the destination file
Step 4: close all the opened the files
STOP
Source Code:
#include <stdio.h>
#include <stdlib.h>
int main( ){
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);
printf("Enter name of file which will store contents of the two files\n");
gets(file3);
fs1 = fopen(file1, "r");
fs2 = fopen(file2, "r");
if(fs1 == NULL || fs2 == NULL){
perror("Error! Source file(s) does not exist ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
ft = fopen(file3, "w"); // Opening in write mode
if(ft == NULL){
perror("Error! Destination file does not exist");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 140


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

while((ch = fgetc(fs1)) != EOF)


fputc(ch,ft);
while((ch = fgetc(fs2)) != EOF)
fputc(ch,ft);
printf("The two files were merged into %s successfully.\n", file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
Test Case-1
Enter name of first file
Source file1
Enter name of second file
Source file2
Enter name of file which will store contents of the two files
Destination file
The two files were merged into Destination file successfully.
Test Case-2
If either of source file exists or destination does not exist, then “Error! Source file(s) does
not exist" or "Error! Destination file does not exist" would be displayed respectively.
v. Find no. of lines, words and characters in a file
Description:
There are four library functions invole in writing the data into a file.
FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode. As we operate on a file,
we need to specify either of 'r','w' etc in modes.
char *fgets(char *str, int n, FILE *stream),
used to read a string at a time from a file.
int getc(FILE *stream),

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 141


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

used to read a character at time from a string.


int fclose(FILE *stream),
closes the file I/O streams.
Algorithm:
START
Step 1: initialize the line, word and character counts to be zero
Step 2: open the source file
Step 3: get the contents into a string
Step 4: if that string contains a '\n', then increment the line count
Step 5: if string contains a ' '(space),then increment wordcount
Step 6: If the character in the string is neither a ' ' nor '\n\, then increment character count.
Step 7: After processing till the EOF, display the values of line, word and character
counts.
STOP
Source Code:
#include <stdio.h>
int main( ){
FILE *fp;
char filename[100];
char ch;
int linecount, wordcount, charcount;
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Enter a filename :");
gets(filename);
// Open file in read-only mode
fp = fopen(filename,"r");
// If file opened successfully, then write the string to file

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 142


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

if ( fp ) {
//Repeat until End Of File character is reached.
while ((ch=getc(fp)) != EOF) {
// Increment character count if NOT new line or space
if (ch != ' ' && ch != '\n') { ++charcount; }
// Increment word count if new line or space character
if (ch == ' ' || ch == '\n') { ++wordcount; }
// Increment line count if new line character
if (ch == '\n') { ++linecount; }
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failed to open the file\n");
}
printf("Lines : %d \n", linecount);
printf("Words : %d \n", wordcount);
printf("Characters : %d \n", charcount);
//getchar();
return(0);
}
Test Case-1
Enter a filename : source.txt
Lines: 1
Words: 2
Characters: 11

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 143


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Test Case-2
If either of source file does not exist, then the programs returns 0 and exits.
vi. Write a C program to print last n characters of a given file.
Description:
There are four library functions involve in writing the data into a file.
FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode. As we operate on a file,
we need to specify either of 'r','w' etc in modes.
int fseek(FILE *stream, long int offset, int whence),
used to set the file pointer at beginning, current and last positions for file operations.
long ftell(FILE *pointer),
used to find out the position of file pointer in the file with respect to starting of the file.
int fclose(FILE *stream),
closes the file I/O streams.
Algorithm:
START
Step 1: Open source file in the read mode.
Step 2: Set the file pointer to the end using fseek( ).
Step 3: Take the position number to start reading from that position.
Step 4: Using ftell, current position of the file pointer is stored to move the pointer from
the end.
Step 5: read last n characters from the file and move pointer to (length-n) character back
on the file.
Step 6: Display the contents read from the file.
STOP
Source Code:
#include<stdio.h>
int main() {
FILE *fp;
char ch;

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 144


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

int num;
long length;
printf("Enter the value of num : ");
scanf("%d", &num);

fp = fopen("test.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - num), SEEK_SET);
do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);
fclose(fp);
return(0);
}
Test Case-1
(File Contains “C Programming”)
Enter the value of n : 3
ing
Test Case-2
(File Contains “C Programming”)
If either of source file does not exist, cannot open this file.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 145


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

TEXTBOOKS:
1. Ajay Mittal, Programming in C: A practical approach, Pearson.
2. Byron Gottfried, Schaum's Outline of Programming with C, McGraw-Hill

REFERENCES:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language,
Prentice-Hall of India
2. C Programming, A Problem Solving Approach, Forouzan, Gilberg, Prasad,
CENGAGE

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 146


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

COURSE OUTCOMES:
CO1: Have the ability to describe a formal algorithmic solution for the given problem, list
the features of C including scalar & vector data types, operators, Outline
expressions, expression evaluation, operator precedence, sequential, conditional &
iterative constructs.
CO2: Have the ability to describe one and two-dimensional arrays, outline loops and
arrays for searching and describe various sorting techniques.
CO3: Have the ability to outline the purpose of functions, pointers, command line
arguments, dynamic memory allocation. Define storage classes. Describe command
like arguments, structures, unions, and enumeration. Have a knowledge of handling
files.
CO4: Have the ability to solve complex expressions, design algorithms and develop
programs in C language using the basic constructs, data types, operators, control &
iterative statements, and arrays.
CO5: Have the ability to apply arrays to solve complex matrix related problems and
strings. Compare and contrast various searching and sorting techniques for
complexity.
CO6: Have the ability to distinguish between function call types. Draw inferences on
command line arguments, storage classes, and pre-processor directives. Use pointers
with functions, arrays, strings, to solve complex problems. Give example and solve
classical recursion problems. Compare and contrast static and dynamic memory
allocation, and apply them. Use structures and unions to implement and solve real-
time problems. Apply file related functions to process files.
CO7: Have the ability to Fully appreciate the art of procedural programming in C and
develop programs optimally using the full feature set of C language.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 147


PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL

Course Title: Programming for problem solving lab (Common to ALL Branches)
Course Code: A2CIL001
Course Designed by Dept. of Computer Science and Engineering
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSOM PSON PSOO
CO1 3 3 1 2 3 1 1 1 2 2 2 2 2
CO2 3 3 1 2 3 1 1 1 2 2 2 2 2
CO3 3 3 2 3 3 2 1 1 2 2 3 3 3
CO4 3 3 2 3 3 3 1 1 2 2 3 3 3
CO5 3 3 3 3 3 3 1 1 2 2 3 3 3
CO6 3 3 3 3 3 3 1 1 3 3 3 3 3 3

Levels of Correlation: High-3, Medium-2, Low-1

Course designed by DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Approved by: Meeting of Board of Studies held on 29.06.2019
Approval
Ratified by: 5th Meeting of Academic Council, 13-07-2019.

MVGR COLLEGE OF ENGINEERING (AUTONOMOUS) Page 148

You might also like