Programming For Problem Solving Lab Manual
Programming For Problem Solving Lab Manual
PROGRAMMING FOR
PROBLEM SOLVING LAB
MANUAL
LAB MANUAL
A2 REGULATION
(FROM 2019-2020 BATCH ONWARDS)
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.
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.
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.
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
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
Ex: vi filename.c
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
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.
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.
-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.
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:
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
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
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:
#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
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
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
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
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
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--);
}
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
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
}
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
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.
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.
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
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;
}
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
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;
}
Test Case 1:
Enter any number: 5
Factorial value of 5=120
Test Case 2:
Enter any number: 3
Factorial value of 3=6
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
For example,
Let the value of x be 30.
For example,
Let the value of x be 30.
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
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()
{
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);
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);
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.
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;
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
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
*/
*/
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
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");
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
{
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 */
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
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
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
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
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
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:
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
Test Case – 4
User Output
Enter the value of n and r : 18 10
The value of 18c10 = 43758
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);
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];
}
}
}
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
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.
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:
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;
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);
}
}
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
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;
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
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:
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;
}
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
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
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
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()
{
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++;
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
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
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;
}
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’.
stud1.rollno
stud1.marks
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);
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;
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++) {
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
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]
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.
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.
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
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.
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");
}
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;
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
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;
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+");
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>
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)
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) {
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
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
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;
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.
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
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.
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