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

c Programming Lab Record 23-24

Pathfinder communication
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

c Programming Lab Record 23-24

Pathfinder communication
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB

Exercise – 1: Explore different platforms


1. Explore different platforms?
(a) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
(b) Exposure to Turbo C, gcc
(c) Explore to Hacker Rank or any other Online coding platform and compiler environment.
(d) “Hello World” in C
(e) Write a simple program to read int, float, char and string using scanf() and display using printf()
in all the above given platforms.
A. Basic Linux environment and its editors like Vi, Vim & Emacs etc.
For Linux users, text editors are essential tools that play a crucial role in various tasks, from
coding and writing to system administration and configuration management. Linux offers a wide
range of text editors, catering to different preferences and use cases. In this article, we will delve
into the world of Linux text editors, exploring their features, strengths, and popular choices
among the community.

Vi Text Editor:
Vi is an old but popular text editor for Linux and other Unix systems. It works differently than
most modern text editors. Instead of just typing directly, Vi has different “modes” for different
tasks. One mode is for moving the cursor around and making edits. Another mode is for inserting
new text. There are also modes for running commands. While Vi can be tricky to learn at first
with all its modes and keyboard shortcuts, many experienced programmers love using Vi because
it allows them to edit files very quickly and efficiently without using a mouse or menus once they
get the hang of it. Vi is extremely lightweight and available on virtually every Unix system,
making it a reliable choice.

How to Copy, Cut and Paste in Vi Editor:


• First go to normal mode by hitting Esc key
• To cut/delete text, go to normal mode, move cursor and type “dd” to delete a line or
“d” plus movement keys to delete text
• To copy text, go to normal mode, move cursor to start of text to copy, type “y” plus
movement keys (e.g. “yw” to copy a word)
• To paste, go to normal mode, move cursor to paste location, and type “p” to paste after
cursor or “P” to paste before cursor

How to Delete Multiple Lines in Vi Editor:
• Go to normal mode by hitting Esc key
• To delete a range of lines, type “x,yd” where x is the line number to start and y is the
line number to end
• E.g. “5,8d” will delete lines 5 through 8

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 1


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
How to Enter in Editing Mode in Vi Editor:
• First make sure you are in normal mode by hitting Esc key
• From normal mode, hit “i” to enter insert mode to start editing at the cursor
• Or hit “a” to enter insert mode after the cursor
• Or hit “o” to start a new line below in insert mode

How to Save a File in Vi Editor & Quit:


• First go to normal mode by hitting Esc key
• To save, hit Esc to ensure normal mode, then type “:w” and hit Enter
• To quit, type “:q” and hit Enter
• To quit without saving, type “:q!” (adds ! to force without saving)

Navigation in Vi Editor:
• Go to normal mode first by hitting Esc key
• Use h,j,k,l keys to move cursor left, down, up, right
• Or use arrow keys
• Word movement with w (next word) or b (prev word)
• Go to start/end of lines with 0 or $

Mastering Search and Replace in Vi Editor:


• Ensure you are in normal mode by hitting Esc first
• To search, hit “/” then type the pattern to find, hit Enter
• To substitute/replace, type “:s/pattern/replacement”
• Use “:s/pattern/replacement/g” to replace all

Undo and Redo in Vi Editor:


• Go to normal mode by hitting Esc key
• To undo, hit “u” in normal mode
• To redo after undo, hit Ctrl+R

Quit Vi Editor Without Saving Changes in Linux:


• If file is open, hit Esc to go to normal mode first
• Type “:q!” (colon, q, !, then Enter) to quit without saving

Vim Editor :
Vim is a popular text editor program used on Linux and other Unix operating systems. It is an
improved and updated version of the old vi editor. While vim looks basic, it is actually a very
powerful tool for editing files efficiently, especially for programmers and developers. What
makes vim unique is that it has different “modes” for different tasks like navigating files, editing
text, and running commands. This modal approach with keyboard shortcuts allows very fast and
precise text editing once you learn it. Though vim has a learning curve at first, many Linux users
prefer it over regular text editors because it provides more control and capabilities through its
modes and key combinations. Vim also supports adding extra features through plugins.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 2


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Basic Vim Commands:
How to Delete Multiple Lines in Vim Editor:
• Go to normal mode by hitting Esc
• To delete a single line, type “dd”
• To delete multiple lines, type “nd” where n is the number of lines (e.g. 5d deletes 5
lines)
• To delete a range of lines, type “x,yd” where x is start line and y is end line (e.g. 5,8d)

Editing Mode | Insert Mode in Vim Editor:


• From normal mode, enter insert mode by typing “i” to insert before the cursor
• Or type “a” to insert after the cursor position
• Or type “o” to start a new line below in insert mode
• Hit Esc to go back to normal mode when done inserting

How to Save a File in Vim Editor & Quit:


• To save, go to normal mode and type “:w” then hit Enter
• To quit, type “:q” and hit Enter
• To save and quit, type “:wq”
• To force quit without saving, type “:q!”

How to Search and Replace in Vim Editor:


• Go to normal mode
• To search, type “/pattern” where pattern is the text to find, hit Enter
• To replace, type “:s/pattern/replacement” where replacement is the new text
• Add “g” to replace all, like “:s/pattern/replacement/g”

The Six Modes of Vim Editor:


• Normal – For navigation and manipulating text
• Insert – For inserting new text
• Command – For running Vim commands (e.g. :q to quit)
• Visual – For selecting blocks of text
• Replace – For overwriting existing text
• Operator-pending – For operating on areas of text

How to Display Line Number in Vim Editor:


• Go to normal mode
• Type “:set number” to enable line numbers
• Or “:set nonumber” to disable line numbers

How to Highlight Text in Vim Editor


• Go to normal mode
• Move cursor to start of text to highlight
• Type “v” to start character-wise visual mode
• Use movement keys to select/highlight the desired text

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 3


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Vim Text Buffers in Linux:
• Buffers are temporary storage areas for files you have open in Vim
• You can have multiple buffers open at once
• Use “:ls” to list open buffers
• Switch between buffers with “:bn” for next or “:bp” for previous

How to Comment Multiple Lines in Vim Editor:


• Go to normal mode at start of lines to comment
• Type “Ctrl+v” to enter visual block mode
• Move cursor to cover desired lines to comment
• Type “I” (uppercase i) to enter insert mode
• Type the comment characters (like # or //)
• Hit Esc to apply commenting to selected lines

Vim – Go to End of File:


• From normal mode, type “G” to jump to the last line of the file
• Or type “Ngg” where N is the line number to go to
• For example, “20gg” goes to line 20

Emacs Editor:
Emacs is a popular text editor choice on Linux systems. It comes pre-installed or can be easily
installed via package managers on most Linux distributions. Emacs integrates smoothly with the
command-line interface of Linux, making it well-suited for terminal-based editing and remote use
over SSH. The customizability of Emacs through its own Lisp language allows tapping into
numerous community extensions tailored for Linux users’ needs like coding and system
administration. Although it has a steep learning curve initially, Emacs’ broad capabilities and
ability to extensively personalize the editing environment make it a powerful tool for Linux
power users willing to invest time in mastering it.

B. Exposure to Turbo C:
Turbo C was an integrated development environment (IDE) for programming in the C language. It
was developed by Borland and first introduced in 1987. At the time, Turbo C was known for its
compact size, comprehensive manual, fast compile speed and low price. It had many similarities to
an earlier Borland product, Turbo Pascal, such as an IDE, a low price and a fast compiler, but was
not as successful because of competition in the C compiler market.

Techopedia Explains Turbo C:

Turbo C 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

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 4


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
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.

C. Explore to Hacker Rank or any other Online coding platform and compiler environment.
What Is HackerRank Used For?

HackerRank is an online platform featuring competitive coding, programming, and technical


assessments. Through interactive challenges, HackerRank gamifies learning, studying, and
assessments for students, consumers, seasoned professionals, and businesses.

For students and those learning coding or programming, HackerRank is an excellent tool for
practicing new skills and developing proficiency in programming languages. Employers also use
HackerRank to analyze candidates’ coding abilities before investing in interviews.
ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 5
DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
HackerRank Tests for Candidates

When applying for software engineering or related computer science jobs, you may need to
complete a HackerRank test as part of your application or interview process.

From an employer standpoint, these tests “provide a standardized and objective way to evaluate
coding proficiency, problem-solving abilities, and algorithmic knowledge,” says Joseph Harisson,
CEO of IT Companies Network.

Companies can also determine minimum scores for HackerRank challenges, so those without the
required skills are weeded out before progressing.

The platform allows employers to “tailor the assessment process and identify candidates with the
right technical expertise,” says Harisson.

In a tech career hiring process, the employer may ask you to complete a challenge on HackerRank
in subject areas like:

• Algorithms
• Data structures
• Mathematics
• Artificial intelligence (AI) and machine learning (ML)
• C and C++
• Java
• Python
• Ruby
• SQL
• Databases and data storage
• Linux
• Functional programming

D. “Hello World” in C
#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}
Output:
Hello, World!

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 6


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
How "Hello, World!" program works?

• The #include is a preprocessor command that tells the compiler to include the contents
of stdio.h (standard input and output) file in the program.
• The stdio.h file contains functions such as scanf() and printf() to take input and display
output respectively.
• If you use the printf() function without writing #include <stdio.h>, the program will not
compile.
• The execution of a C program starts from the main() function.
• printf() is a library function to send formatted output to the screen. In this
program, printf() displays Hello, World! text on the screen.
• The return 0; statement is the "Exit status" of the program. In simple terms, the program
ends with this statement.

E. Write a simple program to read int, float, char and string using scanf() and display using
printf() in all the above given platforms.
/* C program to Print Integer, Char, and Float value */

#include <stdio.h>
int main()
{
int Integer;
char Character;
float InputFloat;
char string;
printf(" Please Enter a Character : ");
scanf("%c", &Character);
printf(" Please Enter an Integer Value : ");
scanf("%d", &Integer);
printf(" Please Enter Float Value : ");
scanf("%f", &InputFloat);
printf(" Please Enter String : ");
scanf("%s", &string);
printf(" \n The Character that you Entered is : %c", Character);
printf(" \n The Integer Value that you Entered is : %d", Integer);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 7


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
printf(" \n The Float Value that you Entered is : %f", InputFloat);
printf(" \n The String that you Entered is : %s", string);
return 0;
}
Output:
Please Enter a Character :s
Please Enter an Integer Value : 10
Please Enter Float Value :2.5
Please Enter String :Aditya

The Character that you Entered is :s


The Integer Value that you Entered is :10
The Float Value that you Entered is : 2.5
The String that you Entered is :Aditya

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 8


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 2: Basics and Operators
(a) Sum and Difference of 2 numbers
#include <stdio.h>
main()
{
int a, b;
clrscr();
printf("Enter the a, b values:");
scanf("%d %d" ,&a, &b);
printf("sum: %d", a+b);
printf("sub: %d", a-b);
printf("mul: %d", a*b);
printf("div: %d", a/b);
printf("per: %d", a%b);
getch();
}
Output:
Enter a,b values:20 10
Sum:30sub:10mul:200div:2rem:0

Playing with Characters


#include <stdio.h>
int main()
{
char Character;
char string;
printf(" Please Enter a Character : ");
scanf("%c", &Character);
printf(" Please Enter String : ");
scanf("%s", &string);
printf(" \n The Character that you Entered is : %c", Character);
printf(" \n The String that you Entered is : %s", string);
return 0;
}
Output:
Please Enter a Character :s

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 9


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Please Enter String :Aditya
The Character that you Entered is :s
The String that you Entered is :Aditya

(b) Bitwise Operators


Bitwise Operators
Objective: Learn how to work with bits (0,1) and bitwise operators.
We use the bitwise operators in C language to perform operations on the available
data at a bit level. Thus, performing a bitwise operation is also called bit-level programming. It is
mainly used in numerical computations for a faster calculation because it consists of two digits – 1
or 0.
Types of Bitwise Operators in C
There are various types of bitwise operators used in all the programming languages. Here is a list of
the ones used in C:

• Bitwise OR Operator
• Bitwise AND Operator
• Unary Operator (Binary One’s complement operator)
• Bitwise XOR Operator
• Binary Right Shift Operator
• Binary Left Shift Operator

#include <stdio.h>
main() {
unsigned int p = 60; /* 60 = 0011 1100 */
unsigned int q = 13; /* 13 = 0000 1101 */
int r = 0;
r = p | q; /* 61 = 0011 1101 */
printf(“Line 1 – The value of r is %d\n”, r );
r = p & q; /* 12 = 0000 1100 */
printf(“Line 2 – The value of r is %d\n”, r );
r = ~p; /*-61 = 1100 0011 */
printf(“Line 3 – The value of r is %d\n”, r );

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 10


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
r = p ^ q; /* 49 = 0011 0001 */
printf(“Line 4 – The value of r is %d\n”, r );
r = p >> 2; /* 15 = 0000 1111 */
printf(“Line 5 – The value of r is %d\n”, r );
r = p << 2; /* 240 = 1111 0000 */
printf(“Line 6 – The value of r is %d\n”, r );
}
Output:
Line 1 – The value of c is 61

Line 2 – The value of c is 12

Line 3 – The value of c is -61

Line 4 – The value of c is 49

Line 5 – The value of c is 15

Line 6 – The value of c is 240

(c) Conversion of Fahrenheit to Celsius and vice versa


/* C Program to convert temperature from Fahrenheit to Celsius and vice versa.*/
#include <stdio.h>

int main()
{

float fh,cl;
int choice;

printf("\n1: Convert temperature from Fahrenheit to Celsius.");


printf("\n2: Convert temperature from Celsius to Fahrenheit.");
printf("\nEnter your choice (1, 2): ");
scanf("%d",&choice);

if(choice ==1){
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f",&fh);
cl= (fh - 32) / 1.8;
printf("Temperature in Celsius: %.2f",cl);
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 11


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
else if(choice==2){
printf("\nEnter temperature in Celsius: ");
scanf("%f",&cl);
fh= (cl*1.8)+32;
printf("Temperature in Fahrenheit: %.2f",fh);
}
else{
printf("\nInvalid Choice !!!");
}
return 0;
}

Output:
First Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 1

Enter temperature in Fahrenheit: 98.6


Temperature in Celsius: 37.00

Second Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 2

Enter temperature in Celsius: 37.0


Temperature in Fahrenheit: 98.60

Third Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 3

Invalid Choice !!!

(d) Distance travelled by an object


#include<stdio.h>
int main() {
float u, a, d;
int t;
printf("\nEnter the value of a : ");
scanf("%f", & a);
ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 12
DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
printf("\nEnter the value of u : ");
scanf("%f", & u);
printf("\nEnter the value of t : ");
scanf("%d", & t);
d = (u * t) + (a * t * t) / 2;
printf("\n The Distance : %.2f", d);
return 0;
}
Output:
Enter the value of a : 8
Enter the value of u : 7
Enter the value of t : 6
The Distance : 186.00

(e) Calculate Simple interest and compound interest.

#include<stdio.h>
main()
{
long p=1000,n=10,r=2;
clrscr();
printf("simple interest %ld", p*n*r/100);
getch();
}

Output:
Simple interest 200

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 13


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 3: Operators and Expressions, Variables and Type conversions

(a)Evaluate the following expressions a, b integers, c float, d double, i, j intergers


i. a/b*c-b+a*d/3
ii. j = (i++) + (++i)
#include<stdio.h>
#include<math.h>
main( )
{
int a;
float value;
clrscr( );
printf("Enter the value:");
scanf("%d", &a);
value= sqrt(a);
printf("Root value of the given number: %f",
value);
getch( );
}

Output:
Enter the value: 16

(a) Root value of given of given number:4 Find the area of circle, square, rectangle and
triangle
#include<stdio.h>
#include<math.h>
main(){
int choice;
printf("Enter 1 to find area of Triangle\n 2 for finding area of Square\n 3 for finding area of
Circle\n 4 for finding area of Rectangle\n 5 for Parallelogram");
scanf("%d",&choice);
switch(choice) {
case 1: {
int a,b,c;
float s,area;
printf("Enter sides of triangle");

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 14


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
scanf("%d%d %d",&a,&b,&c);
s=(float)(a+b+c)/2;
area=(float)(sqrt(s*(s-a)*(s-b)*(s-c)));
printf("Area of Triangle is %f ",area);
break;
}
case 2: {
float side,area;
printf("Enter Sides of Square");
scanf("%f",&side);
area=(float)side*side;
printf("Area of Square is %f ",area);
break;
}
case 3: {
float radius,area;
printf("Enter Radius of Circle");
scanf("%f",&radius);
area=(float)3.14159*radius*radius;
printf("Area of Circle %f",area);
break;
}
case 4: {
float len,breadth,area;
printf("Enter Length and Breadth of Rectangle");
scanf("%f %f",&len,&breadth);
area=(float)len*breadth;
printf("Area of Rectangle is %f ",area);
break;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 15


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
case 5: {
float base,height,area;
printf("Enter base and height of Parallelogram");
scanf("%f %f",&base,&height);
area=(float)base*height;
printf("Enter area of Parallelogram is %f ",area);
break;
}
default: {
printf("Invalid Choice");
break;
}
}
}
Output:
Run 1:
1 to find area of Triangle
2 for finding area of Square
3 for finding area of Circle
4 for finding area of Rectangle
5 for Parallelogram
5
Enter base and height of Parallelogram
2468
Enter area of Parallelogram is 8.000000
Run 2:
1 to find area of Triangle
2 for finding area of Square
3 for finding area of Circle
4 for finding area of Rectangle

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 16


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
5 for Parallelogram
3
Enter Radius of Circle
4.5
Area of Circle is 63.617199

(d) Find the maximum of three numbers using conditional operator


#include<stdio.h>
int main(){
int a,b,c,big;
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);
big=(a>b&&a>c?a:b>c?b:c);
printf("\nThe biggest number is:%d",big);
return 0;
}
Output:
Enter any there numbers: 13 25 6
Largest number is: 25

(c)Take marks of 5 subjects in integers, find the total in integer and average in float

#include<stdio.h>
main( )
{
int t, h, e, m, sc, so, to;
float avg;
clrscr( );
printf("Enter the six subject marks:\n");
scanf("%d %d %d %d %d %d", &t, &h, &e, &m,
&sc, &so);
to=t + h + e + m + sc + so;
avg=to/6;
printf("Total marks: %d", to);
printf("Average marks: %f", avg);
getch( );

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 17


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
Output:
Enter the six subject marks:
60 70 54 40 80 63
Total marks:367
Average marks:61.166666

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 18


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 4: Conditional Statements

(a) Conditional statements in C

The conditional statements (also known as decision control structures) such as if, if else, switch,
etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These decision-
making statements in programming languages decide the direction of the flow of program
execution.

Need of Conditional Statements


There come situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also where
we need to make some decisions and based on these decisions we will execute the next block of
code. For example, in C if x occurs then execute y else execute z. There can also be multiple
conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r.
This condition of C else-if is one of the many ways of importing multiple conditions.

Types of Conditional Statements in C

(b) Roots of a Quadratic Equation


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

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 19


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
float a,b,c,r1,r2,d;
printf ("Enter the values of a b c: ");
scanf (" %f %f %f", &a, &b, &c);
d= b*b - 4*a*c;
if (d>0) {
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d==0) {
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("Roots are equal =%f %f", r1, r2);
}
else
printf("Roots are imaginary");
return 0;
}
Output:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000

Enter the values of a b c: 1 2 1


Roots are equal =-1.000000 -1.000000

(c) Generate electricity bill


// C Program to Calculate Electricity Bill//

#include<stdio.h>
main()
{
int pr,pvr,tu,sc;
float uc;
clrscr();
printf("Enter the present Reading:");
scanf("%d",&pr);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 20


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
printf("\nEnter the previous Reading:");
scanf("%d",&pvr);
tu=pr-pvr;
printf("\nTotal units:%d",tu);
if(tu<=100)
{
uc=1.00;
sc=50;
}
else if(tu>=100)
{
uc=2.00;
sc=60;
}
else if(tu>=200)
{
uc=3.00;
sc=70;
}
else if(tu>=300)
{
uc=4.00;
sc=80;
}
else if(tu>=400)
{
uc=5.00;
sc=90;
}
else
{
uc=5.00;
sc=100;
}
printf("\n Unit cost:%f",uc);
printf("\nService charge:%d",sc);
printf("\nTotal bill:%f",tu*uc+sc);
getch();
}
Output:
Enter the present Reading: 782
Enter the previous Reading: 512
Total units: 270
Unit cost: 3.00
Service charge: 70
Total bill: 880.000000
ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 21
DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(d) Simulate a calculator using switch case
#include <stdio.h>
int main() {
char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (op) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
return 0;
}
Output:
Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 22


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(e) Find the given year is a leap year or not, year should be YYYY
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
// leap year if perfectly divisible by 400
if (year % 400 == 0) {
printf("%d is a leap year.", year);
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
printf("%d is not a leap year.", year);
}
// leap year if not divisible by 100
// but divisible by 4
else if (year % 4 == 0) {
printf("%d is a leap year.", year);
}
// all other years are not leap years
else {
printf("%d is not a leap year.", year);
} return 0;
}
Output:
Enter a year: 1900
1900 is not a leap year.
Enter a year: 2012
2012 is a leap year.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 23


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 5: Loops

“for” Loop in C
Objective: Learn the usage of the for loop

In programming, a loop is used to repeat a block of code until the specified condition is met.

C programming has three types of loops:

for loop
while loop
do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn about while and
do...while loop.

for Loop
The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

Usage of the for loop:


The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is
terminated.
However, if the test expression is evaluated to true, statements inside the body of the for loop are
executed, and the update expression is updated.
again the test expression is evaluated.

(a) Sum of the digits of a 5-digit number


#include <stdio.h>
int main()
{
int num = 58612;
int sum = 0;
while(num != 0){
sum += num % 10;
num = num/10;
}
printf("Digit sum: %d", sum);
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 24


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Output:
Digit sum:22

(b) Given number is a prime or not

#include<stdio.h>
main()
{
int n,c=0,i=2;
clrscr();
printf("Enter the number:");
scanf("%d",&n);
while(i<n)
{
if(n%i==0)
c=c+1;
i++;
}
if(c==0)
printf("Given number prime number");
else
printf("Given number not prime number");
getch();
}

Output:
Enter thye any integer number: 7
Given number prime number

(c) Armstrong Number or not


#include <stdio.h>
int main() {
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;

while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;

result += remainder * remainder * remainder;

// removing last digit from the orignal number


originalNum /= 10;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 25


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}

Output:
Enter a three-digit integer: 371
371 is an Armstrong number.

(d) Palindrome or not


#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
// reversed integer is stored in reversed variable
while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
// palindrome if orignal and reversed are equal
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
Output:
Enter an integer: 1001
1001 is a palindrome.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 26


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(e) Printing patterns using Loops

#include <stdio.h>
int main()
{
int n;
printf("Enter the number of rows");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}

Output:

(f) Construct a Pascal triangle

#include <stdio.h>
int main()
{
int no_row, c = 1, blk, i, j;
printf("Input number of rows: ");
scanf("%d", &no_row);
for (i = 0; i < no_row; i++) {

for (blk = 1; blk <= no_row - i; blk++)


printf(" ");

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 27


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB

// Inner loop for generating and printing pattern.


for (j = 0; j <= i; j++) {
if (j == 0 || i == 0) // If it's the first column or first row, set c to 1.
c = 1;
else
c = c * (i - j + 1) / j; // Calculate the next pattern value.
printf("% 4d", c); // Print the pattern value.
}

printf("\n"); // Move to the next row.


}

return 0; // Return 0 to indicate successful execution.


}

Output:
Input number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 28


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 6: Arrays

(a) One dimensional Arrays in C


Objective: Print the sum and free the memory where the array is stored

#include <stdio.h>
#include <stdlib.h>

int main()
{
int* ptr; //declaration of integer pointer
int limit; //to store array limit
int i; //loop counter
int sum; //to store sum of all elements

printf("Enter limit of the array: ");


scanf("%d", &limit);

//declare memory dynamically


ptr = (int*)malloc(limit * sizeof(int));

//read array elements


for (i = 0; i < limit; i++) {
printf("Enter element %02d: ", i + 1);
scanf("%d", (ptr + i));
}

//print array elements


printf("\nEntered array elements are:\n");
for (i = 0; i < limit; i++) {
printf("%d\n", *(ptr + i));
}

//calculate sum of all elements


sum = 0; //assign 0 to replace garbage value
for (i = 0; i < limit; i++) {
sum += *(ptr + i);
}
printf("Sum of array elements is: %d\n", sum);

//free memory
free(ptr); //hey, don't forget to free dynamically allocated memory.

return 0;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 29


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}

Output:
Enter limit of the array: 5
Enter element 01: 100
Enter element 02: 200
Enter element 03: 300
Enter element 04: 400
Enter element 05: 500

Entered array elements are:


100
200
300
400
500
Sum of array elements is: 1500

(b) Array reversal


Objective: Working with indices in array

#include<stdio.h>
int main()
{
int n, arr[n], i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int rev[n], j = 0;
for(i = n-1; i >= 0; i--)
{
rev[j] = arr[i];
j++;
}
printf("The Reversed array: ");
for(i = 0; i < n; i++)
{
printf("%d ", rev[i]);
}
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 30


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Output:

Enter the size of the array: 5


Enter the elements: 1 2 3 4 5
The Reversed array: 5 4 3 2 1

(c) Search an element in array


#include <stdio.h>
int main() {
int n, i, search, flag = 0;
int arr[100];
printf("Enter the number of elements in array: ");
scanf("%d", &n);
printf("Enter %d integers:\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &search);
for(i = 0; i < n; i++)
{
if(arr[i] == search)
{
printf("Element found at position: %d\n", i);
flag = 1;
break;
}
}
if(flag == 0) {
printf("Element not found in the array.\n");
}
return 0;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 31


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Output:
Enter the number of elements in array: 5
Enter 5 integers:
10
20
30
40
50
Enter the element to search: 40
Element found at position: 3

(d) Find min and max elements in array

#include<stdio.h>
main()
{
int a[50],i,n,large,small;
clrscr();
printf("Enter how many elements enter into
array:");
scanf("%d",&n);
printf("Enter %d Integer elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
large=a[0];
small=a[0];
for(i=1;i<n;i++)
{
if(large<a[i])
large=a[i];
else if(small>a[i])
small=a[i];
}
printf("\nLargest number in array:%d",large);
printf("\nSmallest number in array:%d",small);
getch();
}
Output:
Enter how many elements enter into array:4
Enter 4 integer elements:
10

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 32


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
20
30
40
Largest element in array:40
Smallest element in array:10

(e) Replace an element into array at a given index

#include<stdio.h>
#define size 5
int main()
{
int arr[size] = {1, 20, 5, 78, 30};
int element, pos, i;

printf("Enter position and element\n");


scanf("%d%d",&pos,&element);

if(pos <= size && pos >= 0)


{
for(i = size; i > pos; i--)
arr[i] = arr[i-1];

arr[pos] = element;

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


printf("%d ", arr[i]);
}
else
printf("Invalid Position\n");

return 0;
}

Output:
Input
int arr[5] = {10, 20, 30, 40, 50}
Element = 100 position = 2.
Output
{10, 20, 100, 30, 40, 50}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 33


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(f) Identify duplicate elements from array

#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 2, 7, 8, 8, 3};
int length = sizeof(arr)/sizeof(arr[0]);
printf("Duplicate elements in given array: \n");
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
if(arr[i] == arr[j])
printf("%d\n", arr[j]);
}
}
return 0;
}

Output:

Duplicate elements in given array:


2
3
8

(g) Sorting of elements in an array using Bubble sort

#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 34


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}

Output:

Enter number of elements


6
Enter 6 integers
2
-4
7
8
4
7

Sorted list in ascending order:


-4
2
4
7
7
8

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 35


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 7: 2-D Arrays

(a) Addition of two matrices

#include <stdio.h>
int main() {
int m, n, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
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]);
}
}
printf("Enter the elements of matrix B: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &b[i][j]);
}
}
// add the matrices
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
// print the result
printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}

Output:
Enter the number of rows and columns of the matrices: 2 2
Enter the elements of matrix A:
12
34
Enter the elements of matrix B:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 36


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
56
78
The sum of the two matrices is:
68
10 12

(b) Multiplication of two matrices

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


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

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 37


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 38


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(c) Transpose of a Matrix

#include<stdio.h>
int main(){
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
int matrix[10^5][10^5];
printf("Enter the elements of the matrix:\n");
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &matrix[i][j]);
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("The transposed matrix is:\n");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 39


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Output:
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
12
23
34
The transposed matrix is:
123
234

(d) Trace of a Matrix

#include <stdio.h>
int main()
{
int i, j, rows, columns, trace = 0;
printf("Enter Matrix Rows and Columns = ");
scanf("%d %d", &rows, &columns);
int Tra_arr[rows][columns];
printf("Please Enter the Matrix Items = \n");
i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
scanf("%d", &Tra_arr[i][j]);
j++;
}
i++;
}
i = 0;
while(i < rows)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 40


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
{
j = 0;
while(j < columns)
{
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
j++;
}
i++;
}

printf("The Trace Of the Matrix = %d\n", trace);


}

Output:
Enter Matrix Rows and Columns = 3 3
Please Enter the Matrix Items =
10 20 30
40 50 60
70 80 90
The Trace Of the Matrix = 150

(e) Lower Triangular in a Matrix

#include <stdio.h>
int main() {
int arr1[10][10], i, j, n;
float determinant = 0;
printf("\n\nDisplay the lower triangular of a given matrix :\n");
printf("Input the size of the square matrix : ");
scanf("%d", &n);
printf("Input elements in the matrix :\n");
for (i = 0; i < n; i++) {

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 41


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
for (j = 0; j < n; j++) {
printf("element - [%d],[%d] : ", i, j);
scanf("%d", &arr1[i][j]);
}
}
printf("The matrix is :\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("% 4d", arr1[i][j]);
}
printf("\n");
}
printf("\nSetting zero in lower triangular matrix\n");
for (i = 0; i < n; i++) {
printf("\n");
for (j = 0; j < n; j++) {
if (i <= j) {
printf("% 4d", arr1[i][j]);
} else {
printf("% 4d", 0);
}
}
}
printf("\n\n");
return 0;
}
Output:
Display the lower triangular of a given matrix :
----------------------------------------------------
Input the size of the square matrix : 3
Input elements in the first matrix :
1
2
3
ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 42
DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
4
5
6
7
8
9
The matrix is :
1 2 3
4 5 6
7 8 9
Setting zero in lower triangular matrix

1 2 3
0 5 6
0 0 9

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 43


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 8: Strings

(a) Printing Tokens


Objective: print each word of the sentence in a new line
#include <stdio.h>

#include <string.h>

#include <math.h>

#include <stdlib.h>

int main() {

char *s;

s = malloc(1024 * sizeof(char));

scanf("%[^\n]", s);

s = realloc(s, strlen(s) + 1);

for (char *c = s; *c != NULL; c++) {

if (*c == ' ') {

*c = '\n';

printf("%s", s);

return 0;

Output:
Learning C is fun

Learning

is

fun

(b) Count number of alphabets (lowercase, uppercase, consonants, vowels) and digits
#include <stdio.h>
int main()
{
char line[150];
int vowels, consonant, digit, space;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 44


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
// initialize all variables to 0
vowels = consonant = digit = space = 0;
// get full line of string input
printf("Enter a line of string: ");
fgets(line, sizeof(line), stdin);
// loop through each character of the string
for (int i = 0; line[i] != '\0'; ++i)
{
// convert character to lowercase
line[i] = tolower(line[i]);
// check if the character is a vowel
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u') {
// increment value of vowels by 1
++vowels;
}
// if it is not a vowel and if it is an alphabet, it is a consonant
else if ((line[i] >= 'a' && line[i] <= 'z'))
{
++consonant;
}
// check if the character is a digit
else if (line[i] >= '0' && line[i] <= '9')
{
++digit;
}
// check if the character is an empty space
else if (line[i] == ' ')
{
++space;
}
}
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}

Output:
Enter a line of string: C++ 20 is the latest version of C++ yet.
Vowels: 9
Consonants: 16
Digits: 2
White spaces: 8

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 45


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(c) Lowercase to Uppercase, Uppercase to Lowercase, Toggle case, Sentential case

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

int main()
{
char str[100];
int i;

printf("\n Please Enter any String: ");


gets(str);

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


{

if(str[i] >= 'A' && str[i] <= 'Z')


str[i] = str[i] + 32;

else if(str[i] >= 'a' && str[i] <= 'z')


str[i] = str[i] - 32;

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

return 0;
}

Output:
Please Enter any String: PREPinsta
Toggoled string: prepINSTA

(d) Digit Frequency

#include <stdio.h>
#include <string.h>
void solve(char *s){
int freq[10] = {0};
for(int i = 0; i < strlen(s); i++){
if(s[i] >= '0' && s[i] <= '9'){
freq[s[i] - '0']++ ;
}
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 46


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
for(int i = 0; i<10; i++){
if(freq[i] > 0)
printf("(Number %d, Freq %d)", i, freq[i]);
}
}
int main(){
char *s = "we85abc586wow236h69";
solve(s);
}

Output:

(Number 2, Freq 1)

(Number 3, Freq 1)

(Number 5, Freq 2)

(Number 6, Freq 3)

(Number 8, Freq 2)

(Number 9, Freq 1)

(e) Find string length, concatenate two strings, reverse a string using built-in and without built-
in string functions

#include<stdio.h>
#include<conio.h>
void main()
{
char arr[30],s1[10],s2[10],s3[10];
int opt,i=0,j,len=0;
//clrscr();
printf("Enter any option\n\n");
printf("1: Find out length of the string\n");
printf("2: Concatenate of the two string\n");

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 47


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
printf("3:Reverse of the string\n");
printf("4:Copy of the string\n");
printf("Enter the choice\n\n\n\n\n");
scanf("%d",&opt);
switch(opt)
{
case 1:
{
printf("Enter any string \n");
scanf("%s",arr);
for(i=0;arr[i]!='\0';i++);
printf("The length of the string %d",i);
break;
}
case 2:
{
printf(" String Concatenation \n");
printf("\nEnter the First string:\n");
scanf("%s", s1);
printf("\nEnter Second string");
scanf("%s",s2);
for(i=0;s1[i]!='\0';i++)
{
s3[i]=s1[i];
}
s3[i]='\0';
for(j=0;j<=i;j++)
{
s3[i+j]=s2[j];
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 48


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
printf("The Concatenated string is %s",s3);
break;
case 3:
{
printf(" Reverse the string ");
printf("\nEnter the string");
scanf("%s",s1);
while(s1[i]!='\0')
{
len=len+1;
i++ ;
}
for(i=len-1;i>=0;i--)
{
printf("%c",s1[i]);
}
break;
}
case 4:
{
printf(" String copying \n");
printf("Enter 1st string :");
scanf("%s",s1);
printf("Enter 2st string :");
scanf("%s",s2);
while(s2[i]!='\0')
{
s1[i]=s2[i];
i++;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 49


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
s1[i]='\0';
printf("%s",s1);
break;
}
default:
{
printf("Not is valid Option........");
}
}
}
getch();
}
Output:
Enter any option
1: Find out length of the string
2: Concatenate of the two string
3:Reverse of the string
4:Copy of the string
Enter the choice
2
String Concatenation
Enter the First string:
raju
Enter Second string
ravi
The Concatenated string is rajuravi

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 50


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 9: Functions and Recursion

(a)Functions and Recursion


Functions in C
Introduction
A function in C is a block of code that runs only when it is called. You can pass data (known as
parameters) into a function. The functions in C are used to perform specific actions. They help you
to optimise and reuse the code. You only have to define the function’s code once and use it multiple
times.
Generally, a C function is defined and declared in a single step. The reason is the function definition
always begins with the function declaration, so you don’t have to declare it explicitly.

Advantage of functions in C
Functions in C serve an extremely useful feature and provides the following advantages:
The functions decrease the iteration of the same statements in a program. So, they decrease the
program’s size.
The function improves code readability by offering modularity to the program.
Functions can be called multiple times from different parts of a program, promoting code
reusability.
They make programs easy to understand and manage by breaking a large program into smaller
pieces.

Basic Syntax of Functions


Here’s the basic syntax of function in C:
return_type function_name(parameter1, parameter2, ... parameterN) {
body of the function
}
General Aspects of Functions in C Programming
Three general aspects of functions in C programming are:
i. Function Declaration
ii. Function Call
iii. Function Definition

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 51


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
i. Function Declaration
The function declaration informs the compiler about the name, data type of parameters, number of
parameters, and return type of a function. It is optional to write parameter names during declaration
because you can do that when defining the function.
ii. Function Call
The compiler executes the function call in C. You can call the function anywhere in the whole
program. But make sure to pass the number of arguments (of the same data type) as specified when
declaring the function.
iii. Function Definition
It means defining the statements that the compiler will execute during the function call. It represents
the body of the function. Function definition should return only one value upon the completion of
the execution.
Here’s one of the easy-to-understand function in C programming examples that illustrates all three
general aspects of a function.
#include <stdio.h>
// Function declaration
int max_num(int x, int y)
{
// Function definition
if (x > y)
return x;
else
return y;
}
int main(void){
int a = 11, b = 19;
// Calling the function to determine the larger of the two numbers
int p = max_num(a, b);
printf("The biggest number is %d", p);
return 0;
}
Output:
The biggest number is 19
The first part of the above program declares the function max_num, whose data type is int; the
variables passed are x and y. The function definition part compares the value of two variables, and

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 52


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
based on the comparison, it returns the value. The function calls the max_num and prints the output
based on the comparison.
Types of Functions

Types of Functions in C
There are 2 types of functions in C programming:
Library Functions:
They are also known as built-in functions. They are directly usable; no need to define them. The
examples of these types of functions in C are printf(), scanf(), puts(), gets(), floor(), ceil(), etc.
User-defined functions:
The functions which the programmer creates are called user-defined functions. The user-defined
functions in C should be declared and defined before being used. These functions can be improved
and altered as per the programmer’s need. They can be used multiple times. So, they decrease the
code’s complexity.
Header Files for Library Functions in C Programming
The header files in C contain a set of predefined standard library functions and other entities. They
are included in a program using #include <header_filename.h>. These files provide the necessary
declarations and definitions for the C standard library.
The example of a header file for library functions in C is “#include <stdio.h>”. It includes the
standard input/output functions.
Return Value
A C function doesn't need to return a value from the function. If you don't want to return value from
the function, you must use void for the return type.
Here is one of the function in C programming examples that demonstrates the use of a function
without a return value.
#include <stdio.h>

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 53


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
// The below function prints a greeting message
void greet()
{
printf("Welcome to C programming");
}
int main()
{
greet(); // Calls the greet function
return 0;
}
Output:
Welcome to C programming
In the above example, the greet function has a return type void, so it doesn’t return any value. It
only prints the message using printf.
If a function needs to return a value, you can specify a return type other than void, such as int, char,
or any other appropriate data type.
Here’s an example demonstrating using the C function that returns a value.
#include <stdio.h>
// The below function calculates the sum of two integers
int sum(int a, int b)
{
int c = a + b;
return c;
}
int main()
{
int m1, m2;
printf("Please enter two numbers: ");
scanf("%d %d", &m1, &m2);
int addition = sum(m1, m2);
printf("The sum of two numbers is: %d\n", addition);
return 0;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 54


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Output:
Please enter two numbers: 5 6
The sum of two numbers is: 11

In the above example, the sum takes two integer values a and b. It calculates the sum and stores the
result in variable c. Subsequently, the function returns the result.
The main function prompts the user to enter two numbers. The sum function is called in which the
entered numbers are passed as arguments. The value returned from the sum function is assigned to
the addition variable, which is finally printed to the console.
Different aspects of function calling
Function calling in C incorporates various aspects. They are discussed below.
i. Function Declaration:
It mentions the name of the function, the types of its parameters (if exist), and its return type.
For example,
int add(int p, int q);
ii. Function Definition:
This aspect represents the actual implementation of the function. It contains the function body that
includes the statements to be executed.
For example,
int add(int m, int n)
{
return m + n;
}
iii. Function Parameters:
Functions in C can accept zero or more parameters (also known as arguments). These parameters
are used to pass values to that function.
iv. Return Values:
Functions can return a value to the caller through the return statement.
v. Calling Conventions:
Calling conventions specify the conventions and rules for the way function calls are invoked and
the way parameters are passed.
vi. Function Call:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 55


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
If you want to call a function, you just need to use its name followed by parentheses. There may be
arguments inside parentheses.
For example,
int outcome = add(5, 6);
Example for Function without argument and return value
#include <stdio.h>
// Function declaration
void printhelloMessage();
// Function definition
void printhelloMessage()
{
printf("Here is your C program!\n");
}
int main()
{
// Calls the declared function
printhelloMessage();
return 0;
}
Output:
Here is your C program.

In the above program, the defined function, i.e., printhelloMessage(), neither has arguments nor a
return value. It simply prints the message written in the printf function.
Example for Function with argument and without return value
#include <stdio.h>
// Function declaration
void printSum(int m, int n);
// Function definition
void printSum(int m, int n)
{

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 56


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
int sum = m + n;
printf("The addition of %d and %d is %d\n", m, n, sum);
}
int main()
{
int number1, number2;
printf("Please enter two numbers: ");
scanf("%d %d", &number1, &number2);
// Calls the function
printSum(number1, number2);
return 0;
}
Output:
Please enter two numbers: 5 7
The addition of 5 and 7 is 12

In the above program, the defined function printSum accepts two arguments, i.e., m and n. It
calculates the sum of the values of these arguments. The printf function in the main body calls this
function, and finally, the program prints the sum of the numbers.
Recursive Functions in C Programming
The functions in C are recursive if they can call themselves until the exit condition is fulfilled.
#include <stdio.h>
// The following recursive function calculates the Fibonacci sequence
int fibonacci(int m)
{
if (m == 0)
{
return 0;
}
else if (m == 1)
{
return 1;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 57


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
else
{
return fibonacci(m - 1) + fibonacci(m- 2);
}
}

int main() {
int num;

printf("Please enter a number to calculate the Fibonacci sequence: ");


scanf("%d", &num);
printf("Fibonacci sequence of %d is %d\n", num, fibonacci(num));

return 0;
}

Output:
Please enter a number to calculate the Fibonacci sequence: 16
Fibonacci sequence of 16 is 987

In the above program, the ‘fibonacci’ function generates the Fibonacci series up to the given
number using recursion.
Inline Functions in C Programming
When you use functions in C, the pointer for execution flow transfers to the function definition after
the function call. So, you need an additional pointer that jumps to the definition and returns. The
use of inline functions helps prevent the use of an extra pointer.
Inline functions are functions wherein rather than calling the function, we substitute it with the
program code. Hence, the pointer doesn’t have to transfer back to the definition. To make an inline
function, you must use the keyword inline before a function.
The syntax of an inline function is:
inline function_name (){
//function definition

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 58


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
Here’s an example program that uses an inline function in C:
#include <stdio.h>
// Inline function is defined to calculate the minimum of two numbers
static inline int min(int a, int b)
{
return (a < b) ? a: b;
}
int main()
{
int m1, m2;
printf("Please enter two numbers: ");
scanf("%d %d", &m1, &m2);
int minimum = min(m1, m2);
printf("The minimum of %d and %d is %d\n", m1, m2, minimum);
return 0;
}
Output:
Please enter two numbers: 12 18
The minimum of 12 and 18 is 12

The given program uses an inline function in C to calculate the minimum of two numbers. The
program prompts the user to enter two numbers, calculates the minimum using the inline function,
and then displays the result.
(b)Fibonacci Numbers using recursion
Objective: Complete the recursive function
#include <stdio.h>
// Recursive function to calculate Fibonacci numbersint fibonacci(int n) {
if (n <= 1)
{
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 59


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
}
int main()
{
int n;
printf("Enter the number of terms in the Fibonacci sequence: ");
scanf("%d", &n);
printf("Fibonacci Sequence:\n");
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}

Output:
Enter the number of terms in the Fibonacci sequence:5
Fibonacci Sequence:
0
1
1
2
3

(b) Factorial using recursion


#include<stdio.h>
int fact(int);int main()
{
int x,n;
printf(" Enter the Number to Find Factorial :");
scanf("%d",&n);
x=fact(n);
printf(" Factorial of %d is %d",n,x);
return 0;}int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}

Output:
Enter the Number to Find Factorial :5
Factorial of 5 is 120

(d)Find the Digit Sum using recursion


#include <stdio.h>

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 60


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
int sum (int a);
int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;}
int sum (int num)
{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}

Output:
Enter the number: 2345
Sum of digits in 2345 is 14

(c) LCM using recursive function


#include <stdio.h>
/* Function declaration */int lcm(int a, int b);
int main()
{
int num1, num2, LCM;
/* Input two numbers from user */
printf("Enter any two numbers to find lcm: ");
scanf("%d%d", &num1, &num2);
/*
* Ensures that first parameter of LCM function
* is always less than second
*/
if(num1 > num2)
LCM = lcm(num2, num1);
else
LCM = lcm(num1, num2);

printf("LCM of %d and %d = %d", num1, num2, LCM);


return 0;}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 61


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
/**
* Recursive function to find lcm of two numbers 'a' and 'b'.
* Here 'a' needs to be always less than 'b'.
*/int lcm(int a, int b){
static int multiple = 0;

/* Increments multiple by adding max value to it */


multiple += b;
/*
* Base condition of recursion
* If found a common multiple then return the multiple.
*/
if((multiple % a == 0) && (multiple % b == 0))
{
return multiple;
}
else
{
return lcm(a, b);
}
}

Output:
Enter any two numbers to find lcm: 12
30
LCM of 12 and 30 = 60

(d) Calculate the Nth term using recursive function

Objective: Find the Nth term

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
int find_nth_term(int n, int a, int b, int c)
{
//Write your code here.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 62


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
int main()
{
int n, a, b, c;
scanf("%d %d %d %d", &n, &a, &b, &c);
int ans = find_nth_term(n, a, b, c);
printf("%d", ans);
return 0;
}
Output:
Enter the numbers 5 1 4 3
11

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 63


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 10: Pointers

(a) Pointers in C
Basic functionalities of pointers in C
A function pointer in C is a variable that stores the address of a function. It allows you to refer to a
function by using its pointer and later call the function using that function pointer. This provides
flexibility in calling functions dynamically and can be useful in scenarios where you want to select
and call different functions based on certain conditions or requirements.
The function pointers in C are declared using the asterisk (*) operator to obtain the value saved in
an address.
Advantages of Function Pointers
A function pointer in C is useful to generate function calls to which they point. Hence, the
programmers can pass them as arguments. The function pointers enhance the code’s readability.
You can access many identical functions using a single line of code.
Other prominent advantages of function pointer in C include passing functions as parameters to
other functions. Therefore, you can create generic functions which can be used with any function
provided that it possesses the right signature.
Syntax of Function Pointer in C
Here is the function pointer syntax in C.
return type (*ptr_name)(type1, type2...);
Let’s look at an example:
int (*ip) (int);
*ip is a pointer in the above declaration. It points to a function that returns an int value and also
accepts an integer value as an argument.
Functions Using Pointer Variables
In C, you can pass pointers as function arguments and return pointers from the function. If you want
to pass pointers in the function, you just need to declare the function parameter as a pointer type.
Here’s a C program demonstrating functions using pointer variables.
#include <stdio.h>
void increment(int *numb);
int main()
{
int numb = 10;
printf("The number before increment is: num = %d\n", numb);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 64


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
increment(&numb);
printf("The output after increment is: num = %d\n", numb);
return 0;
}
void increment(int *numb) {
(*numb)++;
}
Output:
The number before increment is: num = 10
The output after increment is: num = 11
In the above program, the increment function increments an integer’s value using a pointer. The
numb variable is declared and initialized to 10. Subsequently, we call the increment function and
pass the address of numb variable. Lastly, the value of numb is printed at the output.

Referencing and Dereferencing of Function Pointer in C


Referencing a function pointer in C refers to assigning the address of a function to the pointer using
the ‘&’ operator. On the other hand, Dereferencing a function pointer in C refers to accessing a
function and invoking it with arguments using the ‘*’ operator.

Program to pass pointers with functions in C


If you want to pass pointers to functions in C, you must define the function that accepts a pointer
parameter. Subsequently, you need to pass the address of the array or variable that you want to
work with.
Here's a program that demonstrates passing pointers with functions:

#include <stdio.h>
// C program to swap two integers through pointers
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 65


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
int main()
{
int a = 50;
int b = 100;
printf("The numbers before swap: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("The numbers after swap: a = %d, b = %d\n", a, b);
return 0;
}
Output:
he numbers before swap: a = 50, b = 100
The numbers after swap: a = 100, b = 50
The above program shows that the swap function accepts two integer pointers as parameters. Within
the function, we’ve used these pointers to access and swap the variables’ values they point to.
Example for Function Pointer in C
Here’s an example program that demonstrates function pointer in C.
#include <stdio.h>
// The following function subtracts two numbers
int subtract(int a, int b) {
return a - b;
}
int main()
{
// The command declares function pointers
int (*subPtr)(int, int);
subPtr = subtract;
printf("The subtraction of two numbers: %d\n", subPtr(7, 4));
return 0;
}
Output:
The subtraction of two numbers: 3

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 66


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
In the above program, we declare a function pointer subPtr that points to a function that accepts two
integers as arguments and returns an integer. The syntax (*subPtr)(int, int) declares the function
pointer.
Within the main function, we assign the subtract function’s address to the function pointer with the
help of subPtr = subtract. So, subPtr now points to the subtract function. Subsequently, we call the
function via the function pointer by command subPtr(7, 4).
Function Pointer Operations
The below section discusses some common operations that you can accomplish using function
pointers:
i) Declaring a function pointer:
Syntax:
return_type (*pointer_name)(parameter_list);
Example:
int (*funcPtr)(int, int); // This function pointer to a function accepts two int parameters and returns
int
ii) Assigning a function address to a function pointer:
sumPtr = add; // Assigns the address of a function to a function pointer.
Declaring a Function Pointer in C
Since each function has a unique memory address, you can use the function pointers in C to point to
the foremost executable code within a function body.

Declaration of function pointer in C


As seen from the example in the above figure, the function add() adds two integer numbers. The

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 67


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
function name points to the address of the function itself. Hence, we’ve used a function pointer fptr
that holds the address of the start of the function add(a, b) (the address is 1001 in the above
example).
Note: Before using a function pointer, you must declare it to inform the compiler about the type of
function the particular pointer can point to.

Calling Functions Using Pointers

Calling a function using a pointer is the same as calling a function using the function’s name.

The following program demonstrates calling functions using pointers.

#include <stdio.h>

void add(int a, int b)

int sum = a + b;

printf("The addition of %d and %d is: %d\n", a, b, sum);

int main()

void (*addPtr)(int, int); // Function pointer declaration

addPtr = add; // Assigning address of add function

addPtr(7, 8); // Calling the function using function pointer

return 0;

Output:

The addition of 7 and 8 is: 15

In the above program, the add function accepts two integers as arguments, computes their sum, and
displays the output. The declaration of addPtr function pointers happens with the parameter types
and return type that match the functions they would point to.

addPtr = add command assigns the add function’s address to the addPtr function pointer. AddPtr(7,
8) calls the add function through the addPtr function pointer (with the input arguments).

(b)Students Marks Sum


Objective: Learn using Pointers with Arrays and Functions
https://www.hackerrank.com/challenges/students-marks-sum/problem?isFullScreen=true
ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 68
DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
(c) Sorting Array of Strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size_of_array 3 //define size of the array
//function to display arrayvoid display(char array[][30]){
for(int i=0; i<size_of_array; i++){
printf("%s ", array[i]);
}
printf("\n");}
int main(){
//create an array of strings
char array[size_of_array][30];
//Inputting names
printf("Enter %d Strings: \n", size_of_array);
for(int i=0; i<size_of_array; i++){
scanf("%s", array[i]);
}
//display the original array
printf("Original array: ");
display(array);
char temp[30];
//Sort array using the Buuble Sort algorithm
for(int i=0; i<size_of_array; i++){
for(int j=0; j<size_of_array-1-i; j++){
if(strcmp(array[j], array[j+1]) > 0){
//swap array[j] and array[j+1]
strcpy(temp, array[j]);
strcpy(array[j], array[j+1]);
strcpy(array[j+1], temp);
}
}
}
//display the sorted array
printf("Sorted Array: ");

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 69


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
display(array);
return 0;
}

Output:

Enter 3 Strings:
Ball Apple Cat
Original array: Ball Apple Cat
Sorted Array: Apple Ball Cat

(d)Find the sum of a 1D array using malloc()


#include <stdio.h>
int main()
{
int arr[100],size,sum=0;
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter the elements of the array: ");
for(int i=0; i<size; i++)
{
scanf("%d",&arr[i]);
}
//calculating sum of entered array elements
for(int i=0; i<size; i++)
{
sum+=arr[i];
}
printf("Sum of array elements is: %d",sum);
return 0;
}
Output:
Enter size of the array: 5
Enter the elements of the array
10 20 30 40 50
Sum of array elements is 150

(e) Swap two numbers using functions and pointers - call by value and reference
(i)call by reference
#include <stdio.h>swap (int *, int *);int main(){

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 70


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
return 0;}swap (int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}

Output:

Enter value of a & b: 10 20


Before Swapping:
a = 10
b = 20
After Swapping:
a = 20
b = 10

(i) call by value


#include<stdio.h>

void swap (int a, int b)

int temp;

temp = a;

a = b;

b = temp;

printf("After swapping 1st number is %d and 2nd number is %d", a ,b);

int main(void)

int first, second;

//printf("Enter two numbers : \n");

scanf("%d %d",&first,&second);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 71


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
swap(first,second);

printf("\n After swap function called 1st number is %d and 2nd number is %d", first ,second);

return 0;

Output:

After swapping 1st number is 7 and 2nd number is 3

After swap function called 1st number is 3 and 2nd number is 7

(f) Dynamic Array in C

// C program to create dynamic array using malloc() function


#include <stdio.h>
#include <stdlib.h>

int main()
{

// address of the block created hold by this pointer


int* ptr;
int size;

// Size of the array


printf("Enter size of elements:");
scanf("%d", &size);

// Memory allocates dynamically using malloc()


ptr = (int*)malloc(size * sizeof(int));

// Checking for memory allocation


if (ptr == NULL) {
printf("Memory not allocated.\n");
}
else {

// Memory allocated
printf("Memory successfully allocated using "
"malloc.\n");

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 72


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB

// Get the elements of the array


for (int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (int k = 0; k < size; ++k) {
printf("%d, ", ptr[k]);
}
}

return 0;
}

Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 73


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 11: Structure, Union, typedef, bit-fields and enum

a) Write a c program to find the total ,average of n students using structures


#include stdio.h //put is <>in header file
#include conio.h
struct student
{
int rollno,tot;
char name[25];
int mark[5];
};
void main()
{
struct student s[5]; //Data type of ‘*s’ is struct student
int i,n,j;
clrscr();
printf(“Enter the number of students:”);
scanf(“%d”,&n);
printf(“\t*Students Records*\n”);
//take input from user
for(i=0;i<n;i++)
{
printf("\nEnter Student Roll Number: ");
scanf("%d",&s[i].rollno);
printf("\nEnter Student name: ");
scanf("%s",s[i].name);
printf("\nEnter Student 3 subject's marks: ");
for(j=0;j<3;j++)
scanf("%d",&s[i].mark[j]);
}
//calculation
for(i=0;i<n;i++)
{

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 74


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
s[i].tot=0;
for(j=0;j<3;j++)
s[i].tot = s[i].tot+ s[i].mark[j];
}
//Display result
for(i=0;i<n;i++)
{
printf("\t*Students Records*\n");
printf("\n==================================\n");
printf("\nStudent's Roll no. – %d", s[i].rollno);
printf("\nStudent's Name – %s", s[i].name);
printf("\nStudent's Total Marks – %d", s[i].tot);
}
getch();
}
Output:
Enter the number of students:2
*Students Records*
Enter Student Roll Number: 01
Enter Student name: rathi
Enter Student 3 subject’s marks:
12
67
89
Enter Student Roll Number: 02
Enter Student name: kishore
Enter Student 3 subject’s marks:
56
89
90
*Students Records*
==================================
Student’s Roll no. – 1

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 75


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Student’s Name – rathi
Student’s Total Marks – 168 *Students Records*
==================================
Student’s Roll no. – 2
Student’s Name – kishore
Student’s Total Marks – 235

b) // C program for Boxes through Tunnel


#include <stdio.h>
#include <stdlib.h>
#define MAX_HEIGHT 41
struct box
/**
* Define three fields of type int: length, width and height
*/
int length;
int width;
int height;
};
typedef struct box box;
int get_volume(box b) {
/**
* Return the volume of the box
*/
return b.length * b.width * b.height;
}
int is_lower_than_max_height(box b) {
/**
* Return 1 if the box's height is lower than MAX_HEIGHT and 0 otherwise
*/
if (b.height < MAX_HEIGHT) {
return 1;
} else {

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 76


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
return 0;
}
}
int main()
{
int n;
scanf("%d", &n);
box *boxes = malloc(n * sizeof(box));
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
for (int i = 0; i < n; i++) {
if (is_lower_than_max_height(boxes[i])) {
printf("%d\n", get_volume(boxes[i]));
}
}
return 0;
}
Output:
input:
4
555
1 2 40
10 5 41
7 2 42
Output:
125
80

c) C program for Post Transition


#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 6

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 77


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
struct package
{
char* id;
int weight;
};
typedef struct package package;
struct post_office
{
int min_weight;
int max_weight;
package* packages;
int packages_count;
};
typedef struct post_office post_office;
struct town
{
char* name;
post_office* offices;
int offices_count;
};
typedef struct town town;
void print_all_packages(town t)
{
printf("%s:\n", t.name);
for (int i = 0; i < t.offices_count; i++)
{
printf("\t%d:\n", i);
for (int j = 0; j < t.offices[i].packages_count; j++)
printf("\t\t%s\n", t.offices[i].packages[j].id);
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 78


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
void send_all_acceptable_packages(town* source, int source_office_index, town* target, int
target_office_index)
{
int n = 0;
for (int i = 0; i < source->offices[source_office_index].packages_count; i++)
if (source->offices[source_office_index].packages[i].weight >= target-
>offices[target_office_index].min_weight &&
source->offices[source_office_index].packages[i].weight <= target-
>offices[target_office_index].max_weight)
++n;
package* newPackages = malloc(sizeof(package)*(n + target-
>offices[target_office_index].packages_count));
package* oldPackages = malloc(sizeof(package)*(source-
>offices[source_office_index].packages_count - n));
for (int i = 0; i < target->offices[target_office_index].packages_count; i++)
newPackages[i] = target->offices[target_office_index].packages[i];
n = target->offices[target_office_index].packages_count;
int m = 0;
for (int i = 0; i < source->offices[source_office_index].packages_count; i++)
if (source->offices[source_office_index].packages[i].weight >= target-
>offices[target_office_index].min_weight &&
source->offices[source_office_index].packages[i].weight <= target-
>offices[target_office_index].max_weight)
{
newPackages[n] = source->offices[source_office_index].packages[i];
++n;
}
else
{
oldPackages[m] = source->offices[source_office_index].packages[i];
++m;
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 79


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
target->offices[target_office_index].packages_count = n;
free(target->offices[target_office_index].packages);
target->offices[target_office_index].packages = newPackages;
source->offices[source_office_index].packages_count = m;
free(source->offices[source_office_index].packages);
source->offices[source_office_index].packages = oldPackages;
}
int number_of_packages(town t)
{
int ans = 0;
for (int i = 0; i < t.offices_count; i++)
ans += t.offices[i].packages_count;
return ans;
}
town town_with_most_packages(town* towns, int towns_count)
{
int ans;
int max_packages = -1;
for (int i = 0; i < towns_count; i++)
if (number_of_packages(towns[i]) > max_packages)
{
max_packages = number_of_packages(towns[i]);
ans = i;
}
return towns[ans];
}

town* find_town(town* towns, int towns_count, char* name)


{
for (int i = 0; i < towns_count; i++)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 80


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
if (!strcmp(towns[i].name, name))
return &(towns[i]);
return &towns[0];
}
int main()
{
int towns_count;
scanf("%d", &towns_count);
town* towns = malloc(sizeof(town)*towns_count);
for (int i = 0; i < towns_count; i++) {
towns[i].name = malloc(sizeof(char) * MAX_STRING_LENGTH);
scanf("%s", towns[i].name);
scanf("%d", &towns[i].offices_count);
towns[i].offices = malloc(sizeof(post_office)*towns[i].offices_count);
for (int j = 0; j < towns[i].offices_count; j++) {
scanf("%d%d%d", &towns[i].offices[j].packages_count, &towns[i].offices[j].min_weight,
&towns[i].offices[j].max_weight);
towns[i].offices[j].packages = malloc(sizeof(package)*towns[i].offices[j].packages_count);
for (int k = 0; k < towns[i].offices[j].packages_count; k++) {
towns[i].offices[j].packages[k].id = malloc(sizeof(char) * MAX_STRING_LENGTH);
scanf("%s", towns[i].offices[j].packages[k].id);
scanf("%d", &towns[i].offices[j].packages[k].weight);
}
}
}
int queries;
scanf("%d", &queries);
char town_name[MAX_STRING_LENGTH];
while (queries--) {
int type;
scanf("%d", &type);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 81


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
switch (type) {
case 1:
scanf("%s", town_name);
town* t = find_town(towns, towns_count, town_name);
print_all_packages(*t);
break;
case 2:
scanf("%s", town_name);
town* source = find_town(towns, towns_count, town_name);
int source_index;
scanf("%d", &source_index);
scanf("%s", town_name);
town* target = find_town(towns, towns_count, town_name);
int target_index;
scanf("%d", &target_index);
send_all_acceptable_packages(source, source_index, target, target_index);
break;
case 3:
printf("Town with the most number of packages is %s\n", town_with_most_packages(towns,
towns_count).name);
break;
}
}
return 0;
}
Input:
2
A
2
213
a2
b3

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 82


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
124
c2
B
1
414
d1
e2
f3
h4
5
3
2B0A1
3
1A
1B

Output:
Town with the most number of packages is B
Town with the most number of packages is A
A:
0:
a
b
1:
c
e
f
h
B:
0:
D

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 83


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
d)copy one structure variable to another of same type
struct class
{
int no;
char name [20];
float marks;
}
main ( )
{
int x;
struct class stu1 = { 111, “Rao”, 72.50};
struct class stu2 = {222, “Reddy”, 67.80};
struct class stu3;
stu3 = stu2;
x = ( ( stu3.no= = stu2.no) && ( stu3.marks = = stu2.marks))?1:0;
if ( x==1)
{
printf (“ \n student 2 & student 3 are same \n”);
printf (“%d\t%s\t%f “ stu3.no, stu3.name, stu3.marks);
}
else
printf ( “\n student 2 and student 3 are different “);
}

Out Put:

Student 2 and student 3 are same


222 reddy 67.0000

11 f)// program for shift/rotate using bit fields

#include <stdio.h>

union test {
// Bit-field member x with 3 bits
unsigned int x : 3;
// Bit-field member y with 3 bits
unsigned int y : 3;
// Regular integer member z
int z;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 84


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB

};
int main()
{
// Declare a variable t of type union test
union test t;
// Assign the value 5 to x (3 bits)
t.x = 5;
// Assign the value 4 to y (3 bits)
t.y = 4;
// Assign the value 1 to z (32 bits)
t.z = 1;
// Print the values of x, y, and z
printf("t.x = %d, t.y = %d, t.z = %d", t.x, t.y, t.z);

return 0;
}

Output:
t.x = 1, t.y = 1, t.z = 1

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 85


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 12: Files
a)Write text into and read text from a file
#include <stdio.h>

int main() {

FILE *file;

char textToWrite[] = "Hello, this is some text.";

char buffer[100];

// Writing text to a file

file = fopen("example.txt", "w");

if (file == NULL) {

perror("Error opening file for writing");

return 1;

fprintf(file, "%s", textToWrite);

fclose(file);

// Reading text from a file

file = fopen("example.txt", "r");

if (file == NULL) {

perror("Error opening file for reading");

return 2;

fgets(buffer, sizeof(buffer), file);

fclose(file);

// Print the read text

printf("Read from file: %s\n", buffer);

return 0;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 86


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB

b)write into text and read text from binary file using fread() and fwrite()
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
char buffer[1024]; // Buffer to store data

// Open the source file for reading in binary mode

sourceFile = fopen("source.txt", "rb");

if (sourceFile == NULL) {

perror("Error opening source file");

return 1;

// Open the destination file for writing in binary mode

destinationFile = fopen("destination.txt", "wb");

if (destinationFile == NULL) {

perror("Error opening destination file");

fclose(sourceFile);

return 2;

// Copy the contents of the source file to the destination file

size_t bytesRead;

while ((bytesRead = fread(buffer, 1, sizeof(buffer), sourceFile)) > 0) {

fwrite(buffer, 1, bytesRead, destinationFile);

// Close the files

c)//copy the contents of one file to another file

#include <stdio.h>

int main() {

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 87


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
FILE *sourceFile, *destinationFile;

char ch;

// Open the source file for reading

sourceFile = fopen("source.txt", "r");

if (sourceFile == NULL) {

perror("Error opening source file");

return 1;

// Open the destination file for writing

destinationFile = fopen("destination.txt", "w");

if (destinationFile == NULL) {

perror("Error opening destination file");

fclose(sourceFile);

return 2;

// Copy contents from source to destination

while ((ch = fgetc(sourceFile)) != EOF) {

fputc(ch, destinationFile);

// Close the files

fclose(sourceFile);

fclose(destinationFile);

printf("File copied successfully.\n");

return 0;

d)Merge two files into the third file using command line arguments
#include <stdio.h>
int main(int argc, char *argv[]) {

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 88


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
if (argc != 4) {

printf("Usage: %s source1.txt source2.txt destination.txt\n", argv[0]);

return 1;

FILE *sourceFile1, *sourceFile2, *destinationFile;

char ch;

// Open the first source file for reading

sourceFile1 = fopen(argv[1], "r");

if (sourceFile1 == NULL) {

perror("Error opening first source file");

return 2;

// Open the second source file for reading

sourceFile2 = fopen(argv[2], "r");

if (sourceFile2 == NULL) {

perror("Error opening second source file");

fclose(sourceFile1);

return 3;

// Open the destination file for writing

destinationFile = fopen(argv[3], "w");

if (destinationFile == NULL) {

perror("Error opening destination file");

fclose(sourceFile1);

fclose(sourceFile2);

return 4;

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 89


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Exercise – 13: Logic Building – Augmented Experiments (Complete any 2)

a)// Variadic functions in c


#include <stdio.h>
#include <stdarg.h>
// Function to find the average of a variable number of integers
double findAverage(int num, ...) {
va_list args;
va_start(args, num);
double sum = 0;
for (int i = 0; i < num; i++) {
sum += va_arg(args, int);
}
va_end(args);
return sum / num;
}
int main() {
// Example usage of the variadic function
double average = findAverage(3, 10, 20, 30);
printf("Average: %.2f\n", average);
return 0;
}

b)// Querying the document


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 100
// Function to search for a keyword in a document
void searchKeyword(FILE *file, const char *keyword) {
char line[MAX_LINE_LENGTH];

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 90


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
int lineNumber = 0;
while (fgets(line, MAX_LINE_LENGTH, file) != NULL) {
lineNumber++;
// Check if the keyword is present in the current line
if (strstr(line, keyword) != NULL) {
printf("Found '%s' on line %d: %s", keyword, lineNumber, line);
}
}
}
int main() {
FILE *file = fopen("document.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Example: Search for the keyword "query"
searchKeyword(file, "query");
fclose(file);
return 0;
}

c)// Structuring the Document


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
struct word {
char* data;
};
struct sentence {

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 91


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
struct word* data;
int word_count;//denotes number of words in a sentence
};
struct paragraph {
struct sentence* data ;
int sentence_count;//denotes number of sentences in a paragraph
};
struct document {
struct paragraph* data;
int paragraph_count;//denotes number of paragraphs in a document
};
struct document get_document(char* text)
{
struct document doc;
struct paragraph *cur_paragraph = NULL;
struct sentence *cur_sentence = NULL;
char *new_word = NULL;
doc.data = NULL;
doc.paragraph_count = 0;
for (char *s = text; *s; ++s)
{
if (*s == ' ' || *s == '.')
{
if (cur_paragraph == NULL)
{
doc.paragraph_count++;
doc.data = (struct paragraph *) realloc(doc.data, sizeof(struct paragraph) *
doc.paragraph_count);
cur_paragraph = doc.data + doc.paragraph_count - 1;
cur_paragraph->data = NULL;
cur_paragraph->sentence_count = 0;
cur_sentence = NULL;
}
if (cur_sentence == NULL)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 92


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
{
cur_paragraph->sentence_count++;
cur_paragraph->data = (struct sentence *) realloc(cur_paragraph->data, sizeof(struct
sentence) * cur_paragraph->sentence_count);
cur_sentence = cur_paragraph->data + cur_paragraph->sentence_count - 1;
cur_sentence->data = NULL;
cur_sentence->word_count = 0;
}
cur_sentence->word_count++;
cur_sentence->data = (struct word *) realloc(cur_sentence->data, sizeof(struct word) *
cur_sentence->word_count);
cur_sentence->data[cur_sentence->word_count - 1].data = new_word;
new_word = NULL;
if (*s == '.')
cur_sentence = NULL;
*s = 0;
}
else if (*s == '\n')
{
cur_sentence = NULL;
cur_paragraph = NULL;
}
else
{
if (new_word == NULL)
{
new_word = s;
}
}
}
return doc;
}
struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n)
{

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 93


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
return Doc.data[n - 1].data[m - 1].data[k - 1];
}
struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m)
{
return Doc.data[m - 1].data[k - 1];
}
struct paragraph kth_paragraph(struct document Doc, int k)
{
return Doc.data[k - 1];
}
void print_word(struct word w) {
printf("%s", w.data);
}
void print_sentence(struct sentence sen) {
for(int i = 0; i < sen.word_count; i++) {
print_word(sen.data[i]);
if (i != sen.word_count - 1) {
printf(" ");
}
}
}
void print_paragraph(struct paragraph para) {
for(int i = 0; i < para.sentence_count; i++){
print_sentence(para.data[i]);
printf(".");
}
}
void print_document(struct document doc) {
for(int i = 0; i < doc.paragraph_count; i++) {
print_paragraph(doc.data[i]);
if (i != doc.paragraph_count - 1)
printf("\n");
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 94


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
}
char* get_input_text() {
int paragraph_count;
scanf("%d", &paragraph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
int main()
{
char* text = get_input_text();
struct document Doc = get_document(text);
int q;
scanf("%d", &q);
while (q--) {
int type;
scanf("%d", &type);
if (type == 3){
int k, m, n;
scanf("%d %d %d", &k, &m, &n);
struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n);
print_word(w);
}
else if (type == 2) {

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 95


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
int k, m;
scanf("%d %d", &k, &m);
struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m);
print_sentence(sen);
}
else{
int k;
scanf("%d", &k);
struct paragraph para = kth_paragraph(Doc, k);
print_paragraph(para);
}
printf("\n");
}
}
Input:
2
Learning C is fun.
Learning pointers is more fun.It is good to have pointers.
3
12
211
3111
Output:
Learning pointers is more fun.It is good to have pointers.
Learning C is fun
Learning

d)// Small triangle ,Large Triangles

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct triangle

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 96


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
{
int a;
int b;
int c;
};
typedef struct triangle triangle;
double area(triangle tr) {
double p = (tr.a + tr.b + tr.c) / 2.0;
return sqrt(p * (p - tr.a) * (p - tr.b) * (p - tr.c));
}
int compare(const void *a, const void *b) {
triangle *t1 = (triangle*) a;
triangle *t2 = (triangle*) b;
double area1 = area(*t1);
double area2 = area(*t2);
if (area1 > area2) {
return 1;
} else if (area1 < area2) {
return -1;
} else {
return 0;
}
}
void sort_by_area(triangle* tr, int n) {
qsort(tr, n, sizeof(triangle), compare);
}
int main()
{
int n;
scanf("%d", &n);
triangle *tr = malloc(n * sizeof(triangle));

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 97


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
}
sort_by_area(tr, n);
for (int i = 0; i < n; i++) {
printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
}
return 0;
}

Input:
3
7 24 25
5 12 13
345
Output:
345
5 12 13
7 24 25

e)//Permutation of strings
#include <stdio.h>
#include <string.h>
// Function to swap characters at positions i and j in a string
void swap(char *x, char *y) {
char temp = *x;
*x = *y;
*y = temp;
}
// Function to generate permutations of a string
void generatePermutations(char *str, int start, int end) {
if (start == end) {
printf("%s\n", str);

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 98


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
} else {
for (int i = start; i <= end; i++) {
swap((str + start), (str + i));
generatePermutations(str, start + 1, end);
swap((str + start), (str + i)); // backtrack
}
}
}
int main() {
char inputString[100];
// Input the string
printf("Enter a string: ");
scanf("%s", inputString);
int n = strlen(inputString);
// Generate and print permutations
printf("Permutations of %s are:\n", inputString);
generatePermutations(inputString, 0, n - 1);
return 0;
}
Output:
Enter a string: ABC
ABC
ACB
BAC
BCA
CBA
CAB

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 99


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
Additional Program: 1
// Function to find two's complement of a binary number
#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
*/
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 100


DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
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;
}
Output:
Enter 8 bit binary value: 01101100
Original binary = 01101100
Ones complement = 10010011
Twos complement = 10010100

ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 101

You might also like