0% found this document useful (0 votes)
19 views170 pages

Pps Core Manulal - 2022

The document provides a comprehensive overview of basic Linux commands including 'cat', 'pwd', 'ls', 'mv', 'rm', 'cp', 'grep', 'mkdir', 'rmdir', 'cd', 'kill', and 'ps', along with their syntax, descriptions, and examples. It also introduces the 'vi' editor, explaining its modes and basic commands for editing text files. This serves as a foundational guide for users to navigate and manipulate files and directories in a Unix-like environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views170 pages

Pps Core Manulal - 2022

The document provides a comprehensive overview of basic Linux commands including 'cat', 'pwd', 'ls', 'mv', 'rm', 'cp', 'grep', 'mkdir', 'rmdir', 'cd', 'kill', and 'ps', along with their syntax, descriptions, and examples. It also introduces the 'vi' editor, explaining its modes and basic commands for editing text files. This serves as a foundational guide for users to navigate and manipulate files and directories in a Unix-like environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

Week 1:

Ubuntu and Linux Commands


1) Command CAT

Syntax: cat [argument] [specific file]


Description: “cat" is short for concatenate. This command is used to create, view and
concatenate files.
Examples:
cat /etc/passwd
This command displays the "/etc/passwd" file on your screen.
cat /etc/profile
This command displays the "/etc/profile" file on your screen. Notice that
some of the contents of this file may scroll off of your screen.
cat file1 file2 file3 > file4
This command combines the contents of the first three files into the fourth file.

2) Command pwd

Syntax: pwd
Description: "pwd" stands for present working directory. It displays your current
position
in the UNIX file system.
Example:
pwd
There are no options (or arguments) with the "pwd" command.
It is simply used to report your current working directory.

3) Command ls

Syntax : ls [ options] [names]


Description: "ls" stands for list. It is used to list information about files and
directories.
Examples:
ls
This is the basic "ls" command, with no options. It provides a very basic listing of
the files in your current working directory. Filenames beginning with a
decimal are considered hidden files, and they are not shown.
ls -a
The -a option tells the ls command to report information about all files, including
hidden files.
ls -l
The -l option tells the "ls" command to provide a long listing of information
about the files and directories it reports. The long listing will provide important
information about file permissions, user and group ownership, file size, and creation
date.

ls -al
This command provides a long listing of information about all files in the current
directory. It combines the functionality of the -a and -l options. This is probably
the most used version of the ls command.

ls -al /usr

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 1


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
This command lists long information about all files in the "/usr" director y.

ls -alR /usr | more


This command lists long information about all files in the "/usr" directory, and
all sub-directories of /usr. The -R option tells the ls command to provide a
recursive listing of all files and sub-directories.

ls -ld /usr

Rather than list the files contained in the /usr directory, this command lists
information about the /usr directory itself (without generating a listing of the
contents of /usr). This is very useful when you want to check the permissions
of the directory, and not the files the directory contains.

4) Command mv

Syntax : mv [options] sources target


Options -b backup files that are about to be overwritten or removed.
-i interactive mode; if that exists, you'll be asked whether to overwrite the file
Description: The "mv" command is u sed to move and rename files.
Examples:
mv Chapter1 Chapter1.bad
This command renames the file "Chapter1” to the new name "Chapter1.bad".

mv Chapter1 garbage
This command renames the file "Ch apter1 " to the new name "garbage".
(Notice that if "garbage" is a directory, "Chapter1" would be moved into that director
y).

mv Chapter1 /tmp
This command moves the file "Chapter1" into the director y named "/tmp".

mv tmp tmp.old
Assuming in this case that tmp is a directory, this example renames the directory
tmp to the new name tmp.old.

5) Command rm

Syntax: rm [options] files


Options -d, --directory
Unlink FILE, even if it is a non-empty directory (super-user only).
-f, --force
Ignore nonexistent files, never prompt
-i, --interactive
Prompt before any removal
-r, -R, --recursive
Remove the contents of directories recursively
-v, --verbose
Explain what is being done

Description: The "rm" command is used to remove files and directories.


(Warning - be very careful when removing files and directories!)

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 2


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Examples:
rm Chapter1.bad
This command deletes the file named "Chapter1.bad" (assuming you have permission
to delete this file).
rm Chapter1 Chapter2 Chapter3
This command deletes the files named "Chapter1", "Chapter2", and "Chapter3".

rm -i Chapter1 Chapter2 Chapter3


This command prompt you before deleting any of the three files specified.
The -i option stands for inquire . You must answer y (for yes) for each file you really
want to delete. This can be a safer way to delete files.

rm *.html
This command deletes all files in the current directory whose filename ends
with the characters ".html".

rm index *
This command deletes all files in the current directory whose filename begins
with the characters "index".

rm -r new-novel
This command deletes the director y named "new-novel". This directory, and
all of its' contents, are erased from the disk, including any sub-directories and files.

6) Command cp

Syntax: cp [options] file1 file2


cp [options] files directory

Options
-b backup files that are about to be overwritten or removed
-i interactive mode; if exists, you'll be asked whether to overwrite the file
-p preserves the original file's ownership, group, permissions, and timestamp

Description: The "cp" command is used to copy files and directories.


Note that when using the cp command, you must always specify both the
source and destination of the file(s) to be copied.

Examples:
cp .profile .profile.bak
This command copies your ".profile" to a file named ".profile.bak".

cp /usr/fred/Chapter1 .
This command copies the file named "Chapter1" in the "/usr/fred" directory to
the current director y. This example assumes that you have write permission
in the current directory.

cp /usr/fred/Chapter1 /usr/mary
This command copies the "Chapter1" file in "/usr/fred" to the directory named
"/usr/mary". This example assumes that you have write permission in the
"/usr/mary" director y.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 3


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
7) Command grep

Syntax: grep [options] regular expression [files]

Options:
-i case-insensitive search
-n show the line# along with the matched line
-v invert match, e.g. find all lines that do NOT match
-w match entire words, rather than substrings

Description: Think of the "grep" command as a "search" command


(most people wish it was named "search "). It is used to
search for text strings within one or more files.

Examples:

grep 'fred' /etc/passwd


This command searches for all occurrences of the text string 'f red' within the
"/etc/passwd" file. It will find and print (on the screen) all of the lines in this file that
contain the text string 'fred', including lines that contain usernames like "fred "
- and also "alfred".

grep '^fred' /etc/passwd


This command searches for all occurrences of the text string 'f red' within the
"/etc/passwd" file, but also requires that the "f" in the name "fred" be in the
first column of each record (that's what the caret character tells grep). Using this
more advanced search, a user named "alfred" would not be matched, because the
letter "a" will be in the first column.

grep 'joe' *
This command searches for all occurrences of the text string 'joe' within all files
of the current directory.
8) Command mkdir

Syntax : mkdir [options] directory name


Description: The "mkdir" command is used to create new directories (sub-directories).
Examples:
mkdir tmp
This command creates a new directory named "tmp" in your current directory.
(This example assumes that you have the proper permissions to create a
new sub-directory in your current working directory. )

mkdir memos letters e-mail


This command creates three new sub-directories (memos, letters, and e-mail) in the
current directory.

mkdir /usr/fred/tmp
This command cr eates a new director y named "tmp" in the directory
"/usr/fr ed". "tmp" is now a sub-directory of "/usr/fred". (This example assumes
that you hav e the proper permissions to create a new director y in /usr/fred.)
mkdir -p /home/joe/customer/acme

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 4


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
This command creates a new directory named /home/joe/customer/acme, and
creates any intermediate directories that are needed. If only /home/joe existed to
begin with, then the directory "customer" is created, and the directory "acme" is
created inside of customer.
9) Command rmdir

Syntax: rmdir [options] directories


Description: The "rm" command is used to remove files and directories. (Warning
- be very careful when removing
files and directories!)
Examples:
rm Chapter1.bad
This command deletes the file named "Chapter1.bad" (assuming you have permission
to delete this file).
rm Chapter1 Chapter2 Chapter3
This command deletes the files named "Chapter1", "Chapter2", and "Chapter3".

rm -i Chapter1 Chapter2 Chapter3


This command prompts you before deleting any of the three files specified. The -i option
stands for inquire . You must
answer y (for yes) for each file you really want to delete. This can be a safer way to
delete files.

rm *.html
This command deletes all files in the current directory whose filename ends with the
characters ".html".

rm index *
This command deletes all files in the current directory whose filename begins with the
characters "index".

rm -r new-novel
This command deletes the director y named "new-novel". This directory, and all of its'
contents, are erased from the disk, including any sub-directories and files.
10) Command cd, chdir
Syntax: cd [name of directory you want to move to]
Description: "cd" stands for chan ge directory. It is the primary command for
moving around the filesystem.
Examples:
cd /usr
This command moves you to the "/usr" director y. "/usr" becomes your current
working directory.
cd /usr/fred
Moves you to the "/usr/fred" directory.

cd /u*/f*
Moves you to the "/usr/fred" directory - if this is the only directory matching this
wildcard pattern.
cd
Issuing the "cd" command without any arguments moves you to your home directory.

cd -

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 5


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Using the Korn shell, this command moves you back to your previous working
directory. This is very useful when you're in
the middle of a project, and keep moving back-and-forth between two directories.

11) Command kill

Syntax: kill [options] IDs


Description: kill ends one or more process IDs. In order to do this you must own
the process or be design ated a privileged user. To find the process ID of a certain
job use ps .

12) Command ps
Syntax: ps [options]
Description: The "ps" command (process statistics) lets you check the status of
processes that ar e running on your Unix
System.
Examples:
ps
The ps command by itself shows minimal information about the processes you
are running. Without any arguments, this command will not show information
about other processes running on the system.
ps -f
The -f argument tells ps to supply full information about the processes it
displays. In this ex ample, ps displays full information about the processes you are
running.
ps -e
The -e argument tells the ps command to show every process running on the system.
ps -ef
The -e and -f arguments are normally combined like this to show full
information about every process running on the system. This is probably the
most often-used form of the ps

13) Command. ps -ef | more


Because the output normally scrolls off the screen, the output of the ps -ef command is
often piped into the more command. The more command lets you view one screenful of
information at a time.

ps -fu fred
This command shows full information about the processes currently being run by the
user named fred (the -u option lets you specify a username).
What is vi?
The default editor that comes with the UNIX operating system is called vi (visual
editor). [Alternate editors for UNIX environments include pico and emacs, a product of
GNU.]
The UNIX vi editor is a full screen editor and has two modes of operation:
Command mode commands which cause action to be taken on the file, and
Insert mode in which entered text is inserted into the file.
In the command mode, every character typed is a command that does something to the
text file being edited; a character typed in the command mode may even cause the vi
editor to enter the insert mode. In the insert mode, every character typed is added to the
text in the file; pressing the <Esc> (Escape) key turns off the Insert mode.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 6


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
While there are a number of vi commands, just a handful of these is usually sufficient
for beginning vi users. To assist such users, this Web page contains a sampling of basic
vi commands. The most basic and useful commands are marked with an asterisk (* or
star) in the tables below. With practice, these commands should become automatic.
NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place
of a lowercase letter; the results will not be what you expect.

To Get Into and Out Of vi


To Start vi
To use vi on a file, type in vi filename. If the file named filename exists, then the first
page (or screen) of the file will be displayed; if the file does not exist, then an empty file
and screen are created into which you may enter text.
* vi filename edit filename starting at line 1
recover filename that was being edited when system
vi -r filename
crashed

To Exit vi
Usually the new or modified file is saved when you leave vi. However, it is also possible
to quit vi without saving the file.
Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of
command is completed by hitting the <Return> (or <Enter>) key.
quit vi, writing out modified file to file named in original
* :x<Return>
invocation
:wq<Return quit vi, writing out modified file to file named in original
> invocation
:q<Return> quit (or exit) vi
quit vi even though latest changes have not been saved for this vi
* :q!<Return>
call

Adding, Changing, and Deleting Text


Unlike PC editors, you cannot replace or delete text by highlighting it with the mouse.
Instead use the commands in the following tables.
Perhaps the most important command is the one that allows you to back up and undo
your last action. Unfortunately, this command acts like a toggle, undoing and redoing
your most recent action. You cannot go back more than one step.
UNDO WHATEVER YOU JUST DID; a simple
*u
toggle

The main purpose of an editor is to create, add, or modify text for a file.
Inserting or Adding Text
The following commands allow you to insert and add text. Each of these commands puts
the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the
entry of text and to put the vi editor back into command mode.
* i insert text before cursor, until <Esc> hit
I insert text at beginning of current line, until <Esc> hit
* a append text after cursor, until <Esc> hit
Aappend text to end of current line, until <Esc> hit
open and put text in a new line below current line, until
*o
<Esc> hit
* Oopen and put text in a new line above current line, until

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 7


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
<Esc> hit

Changing Text
The following commands allow you to modify text.
*r replace single character under cursor (no <Esc> needed)
replace characters, starting with current cursor position, until
R
<Esc> hit
change the current word with new text,
cw
starting with the character under cursor, until <Esc> hit
change N words beginning with character under cursor, until <Esc>
cNw hit;
e.g., c5w changes 5 words
C change (replace) the characters in the current line, until <Esc> hit
cc change (replace) the entire current line, stopping when <Esc> is hit
Ncc or change (replace) the next N lines, starting with the current line,
cNc stopping when <Esc> is hit

Deleting Text
The following commands allow you to delete text.
*x delete single character under cursor
Nx delete N characters, starting with character under cursor
dw delete the single word beginning with character under cursor
delete N words beginning with character under cursor;
dNw
e.g., d5w deletes 5 words
delete the remainder of the line, starting with current cursor
D
position
* dd delete entire current line
Ndd or delete N lines, beginning with the current line;
dNd e.g., 5dd deletes 5 lines

Cutting and Pasting Text


The following commands allow you to copy and paste text.
yy copy (yank, cut) the current line into the buffer
Nyy or copy (yank, cut) the next N lines, including the current line, into the
yNy buffer
p put (paste) the line(s) in the buffer into the text after the current line

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 8


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 2:

Designing of flowcharts and algorithms using raptor tool

1. Areas of Polygons

(i)Area of Pentagon :
Step 1 : Start
Step 2 : Read side a and area Ar
Step 3 : Caculate area using the formula
Ar = (sqrt(5*(5+2*sqrt(5)))*a*a)/4
Step 4 : Display Ar
Step 5 : Stop
Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 9


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
(ii)Area of Hexagon:

Step 1 : Start
Step 2 : Read side a and area Ar
Step 3 : Caculate area using the formula Ar = ((3*sqrt(3)*(a*a))/2
Step 4 : Display Ar
Step 5 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 10


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
2. Calculation of Simple and Compound Interest

(i). Calculation of Simple Interest:

Step 1 : Start
Step 2 : Read Principal P, Time T, Rate R, Simple Interest SI
Step 3 : Calculate Simple Interest using the formula
SI = (P*T*R)/100
Step 4 : Display SI
Step 5 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 11


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
(ii)Calculation of Compound Interest:

Step 1 : Start
Step 2 : Read Principal P, Rate r, Time n, Compound Interest CI
Step 3 : Calculate Compound interest using the formula
CI =P*pow((1+r/100),n)-P
Step 4 : Display CI
Step 5 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 12


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
3. Swapping of Two numbers with and without temporary variable

(i)Using temporary variable:

Step 1 : Start
Step 2 : Read two numbers a,b and variable temp
Step 3 : temp = a
Step 4 : a = b
Step 5 : b = temp
Step 6 : Display a,b
Step 7 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 13


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
(ii)Without using temporary variable

Step 1 : Start
Step 2 : Read two numbers a,b
Step 3 : a = a+b
Step 4 : b = a-b
Step 5 : a = a-b
Step 6 : Display a,b
Step 7 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 14


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
4. Checking whether a number is even or odd

Algorithm:
Step 1 : Start
Step 2 : Read the number a
Step 3 : If a%2 == 0, then go to Step 4 else go to Step 5
Step 4 : Display a is even and go to Step 6
Step 5 : Display a is odd
Step 6 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 15


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
5. Sum of first ‘n’ natural numbers

Algorithm:
Step 1 : Start
Step 2 : Read number n , Sum
Step 3 : Calculate sum of first n natural numbers using the formula
Sum = (n*(n+1))/2
Step 4 : Display Sum
Step 5 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 16


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
6. Checking a number whether it is divisible by any given number

Algorithm:
Step 1 : Start
Step 2 : Read two numbers a,b
Step 3 : If a%b==0 then go to Step 4 else go to Step 5
Step 4 : Display a is divisible by b and go to Step 6
Step 5 : Display a is not divisible by b
Step 6 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 17


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
7. Evaluation of mathematical expressions

Algorithm:
Step 1 : Start
Step 2 : Read 3 numbers a,b,c and 3 expressions Exp1, Exp2, Exp3
Step 3 : Calculate the value of first expression using the formula
Exp1 = a-b/3+c*2-1
Step 4 : Calculate the value of second expression using the formula
Exp2 = a-b/(3+c)*(2-1)
Step 5 : Calculate the value of third expression using the formula
Exp3 = a-(b/(3+c)*2)-1
Step 6 : Display Exp1, Exp2, Exp3, Exp4, Exp5
Step 7 : Stop

Flowchart:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 18


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
8. Programs using scanf ( ) and printf ( ) statements

Program #1:
/*Calculation of average of marks obtained by a student in 3 subjects*/

#include<stdio.h>
void main()
{
int m1,m2,m2;
float avg;
printf(“Enter marks obtained in three subjects : \n”);
scanf(“%d%d%d”,&m1,&m2,&m3);
avg = (m1+m2+m3)/3;
printf(“The average of the marks %d , %d , %d is %d\n”,m1,m2,m3,avg);
}

Output:

Enter marks obtained in three subjects:


95
99
91
The average of the marks 95 , 99 , 91 is 95.000000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 19


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Program #2:
Calculation of area and perimeter of rectangle

#include<stdio.h>
void main()
{
int l,b,perimeter,area;
printf(“Enter the values of length and breadth : \n”);
scanf(“%d%d”,&l,&b);
area = l*b;
perimeter = 2*(l+b);
printf(“Area and perimeter for l=%d and b=%d\n”,l,b);
printf(“Area=%d\n Perimeter=%d\n”,area,perimeter);
}
Output:
Enter the values of length and breadth:
5
8
Area and perimeter for l=3 and b=6
Area=40
Perimeter=26

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 20


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

1. Program to find the roots of quadratic equation.

#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);

discriminant = b * b - 4 * a * c;

// condition for real and different roots


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}

// condition for real and equal roots


else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}

// if roots are not real


else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart,
realPart, imagPart);
}

return 0;
}
OUTPUT:
Enter coefficients a, b and c: 2.3
4
5.6
root1 = -0.87+1.30i and root2 = -0.87-1.30i

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 21


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

C Storage Class:

2. Program to implement Storage classes.

There are 4 types of storage class:


 automatic
 external
 static
 register

1. Write a program in C to print Automatic storage class

#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}

Output:

11 20 20 20 11

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 22


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

2. Write a program in C to print Static storage class

#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}

Output:

10 24
11 25
12 26

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 23


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

3. Write a program in C to print Register storage class

#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
printf("%d",a);
}

Output:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 24


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

4. Write a program in C to print External storage class

#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized
somewhere in the pogram or not.
printf("%d",a);
}
int a = 20;

Output

20

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 25


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

Programs on operators:

1. Write C program to Arithmetic operators

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

printf("Enter a and b values:");


scanf("%d%d",&a,&b);

c = a+b;
printf("a+b = %d \n",c);

c = a-b;
printf("a-b = %d \n",c);

c = a*b;
printf("a*b = %d \n",c);

c = a/b;
printf("a/b = %d \n",c);

c = a%b;
printf("Remainder when a divided by b = %d \n",c);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 26


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

2. Write C program to Assignment operator’s

#include <stdio.h>
int main()
{
int a,c;
printf("Enter a value:");
scanf("%d",&a);

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10 and c=c+a
printf("c = %d\n", c);
c -= a; // c is 5 and c=c-a
printf("c = %d\n", c);
c *= a; // c is 25 and c=c*a
printf("c = %d\n", c);
c /= a; // c is 5 and c=c/a
printf("c = %d\n", c);
c %= a; // c = 0 and c=c%a
printf("c = %d\n", c);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 27


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

3. Write C program to Relational operators

#include <stdio.h>
int main()
{
int a,b,c;
printf("Enter a and b and c values:");
scanf("%d%d%d",&a,&b,&c);
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
}

OUTPUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 28


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

4. Write C program to Logical Operator

#include <stdio.h>
int main()
{
int a, b, c, result;
printf("Enter a and b and c values:");
scanf("%d%d%d",&a,&b,&c);
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 29


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

5. Write C program to Conditional Operators?:

Syntax :( Condition? true_value: false_value);

#include <stdio.h>
int main()
{
int age;
printf("Enter your age");
scanf("%d",&age);
(age>=18)? printf("eligible for voting\n") : printf("not eligible for voting\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 30


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

6. Write C program to Post-increment and Post-decrement Operators

#include <stdio.h>
int main()
{
int a, b;
float c, d;
printf("Enter a and b values:");
scanf("%d%d",&a,&b);
printf("Enter c and d values:");
scanf("%f%f",&c,&d);

printf("a++ = %d \n", a++);


printf("b-- = %d \n", b--);

printf("c++ = %f \n", c++);


printf("d-- = %f \n", d--);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 31


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

7. Write C program to Pre-increment and Pre-decrement Operators

#include <stdio.h>
int main()
{
int a, b;
float c, d;

printf("Enter a and b values:");


scanf("%d%d",&a,&b);

printf("Enter c and d values:");


scanf("%f%f",&c,&d);

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);


printf("--d = %f \n", --d);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 32


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

8. Write C program to Bitwise AND operator '&'

The output of bitwise AND is 1 if the corresponding bits of two operands is 1.


If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)

#include <stdio.h>
int main()
{
int a = 13, b = 15;
printf("Output = %d\n", a&b);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 33


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

9. Write C program to Bitwise OR operator '|'

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1.


In C Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d\n", a|b);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 34


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

10. Write C program to Bitwise XOR (exclusive OR) operator ^

The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite.
It is denoted by ^.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
________
00010101 = 21 (In decimal)

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d\n", a^b);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 35


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

11. Write C program to Bitwise complement operator

It changes 1 to 0 and 0 to 1. It is denoted by ~.

35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Twist in bitwise complement operator in C Programming

The bitwise complement of 35 (~35) is -36 instead of 220, but why?

For any integer n, bitwise complement of n will be -(n+1). To understand this, you
should have the knowledge of 2's complement.
2's Complement

Two's complement is an operation on binary numbers. The 2's complement of a number


is equal to the complement of that number plus 1. For example:

Decimal Binary 2's complement


0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.

The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36.
Hence, the output is -36 instead of 220.
Bitwise complement of any number N is -(N+1). Here's how:

Bitwise complement of N = ~N (represented in 2's complement form) */

#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
}
OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 36


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

12. Write C program to Right Shift Operator

Right Shift Operator:

Right shift operator shifts all bits towards right by certain number of specified bits. It is
denoted by >>.
12 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by

two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift) */

#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
int a = 5, b = 9;

// The result is 00000010

printf("a>>1 = %d\n", a >> 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 37


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

13. Write C program to Left Shift Operator

Left Shift Operator:

Left shift operator shifts all bits towards left by a certain number of specified bits. The
bit positions that have been vacated by the left shift operator are filled with 0. The
symbol of the left shift operator is <<.

212 = 11010100 (In binary)


212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal) */

#include<stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
int a = 5, b = 9;

// The result is 00001010


printf("a<<1 = %d\n", a<<1);

// The result is 00010010


printf("b<<1 = %d\n", b<<1);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 38


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
WEEK 3:

14. Write C Programs on precedence and Associativity & Type conversions.

i. Precedence and Associativity:

#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}

OUTPUT:

Value of (a + b) * c / d is: 90
Value of ((a + b) * c) / d is: 90
Value of (a + b) * (c / d) is: 90
Value of a + (b * c) / d is: 50

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 39


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
ii. Type conversions:

PROGRAM 1:

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

// create a double variable


double value = 4150.12;
printf("Double Value: %.2lf\n", value);

// convert double value to integer


int number = value;

printf("Integer Value: %d", number);

return 0;
}

OUTPUT:

Double Value: 4150.12


Integer Value: 4150

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 40


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
PROGRAM 2:

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

// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);

// assign character value to integer variable


int number = alphabet;
printf("Integer Value: %d", number);

return 0;
}

OUTPUT:
Character Value: a
Integer Value: 9

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 41


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
PROGRAM 3:

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

// create an integer variable


int number = 97;
printf("Integer Value: %d\n", number);

// (char) converts number to character


char alphabet = (char) number;
printf("Character Value: %c", alphabet);

return 0;
}

OUTPUT:
Integer Value: 97
Character Value: a

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 42


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

Programs on Conditional Statements or Decision Statements:

15. Write C program to find largest of given two numbers.

Syntax of if statement:

if (condition)
{
//Block of C statements here
//These statements will only execute if the condition is true
}

Program:

#include <stdio.h>
int main()
{
int x,y;

printf("Enter the x and y values:");


scanf("%d%d",&x,&y);

if(x<y)
{
printf("Variable x is less than y\n");
}
printf("I am Not in if");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 43


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:
16. Write C progaram a Person is eligible to vote
#include<stdio.h>
void main()
{
int age;
printf("Enter a person age:");
scanf("%d",&age);
if(age>=18)
{
printf("He is eligible to vote\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 44


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

17. Write C program to check equivalence of two numbers

#include<stdio.h>
void main()
{
int m,n;
printf("Enter m and n values:");
scanf("%d%d",&m,&n);
if(m-n==0)
printf("\nTwo numbers are equal\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 45


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

18. Write C progame enter only the three numbers and calculate their sum and
multiplication.

#include<stdio.h>
void main()
{
int a,b,c,x;
printf("Enter a and b and c values:");
x=scanf("%d%d%d",&a,&b,&c);
if(x==3)
{
printf("\n Addition : %d\n",a+b+c);
printf("\n Multiplication :%d\n",a*b*c);
}
printf("I am Not in if");
}
OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 46


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

19. Write C Program to Check Even or Odd.

syntax of if-else:

if (test-expression)
{
True block of statements
}
else
{
False block of statements
}

Program:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);

// true if num is perfectly divisible by 2


if(num % 2 == 0)
printf("%d is even.\n", num);
else
printf("%d is odd.\n", num);

Output:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 47


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

20. Write C program to check number is perfect square or not.

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

int num;
int num1;
float num2;

printf("Enter an integer number: ");


scanf("%d",&num);

num2=(sqrt(num));
num1=num2;

if(num1==num2)
printf("%d is a perfect square.\n",num);
else
printf("%d is not a perfect square.\n",num);
}
OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 48


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

21. Write C Program to Find the Largest Number Among Three Numbers.

The Nested If in C Programming language Syntax is:

/* if ( test condition 1)
{
//If the test condition 1 is TRUE then these it will check for test condition 2
if ( test condition 2)
{
//If the test condition 2 is TRUE, these statements execute
Test condition 2 True statements;
}
else
{
//If the c test condition 2 is FALSE, then these statements execute
Test condition 2 False statements;
}
}
else
{
//If the test condition 1 is FALSE then these statements will be executed
Test condition 1 False statements;
} */

Program:

#include <stdio.h>
int main()
{
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);

if (n1 >= n2)


{
if (n1 >= n3)
{
printf("%.2lf is the largest number.\n", n1);
}
else
{
printf("%.2lf is the largest number.\n", n3);
}
}
else
{
if (n2 >= n3)
{
printf("%.2lf is the largest number.\n", n2);
}

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 49


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
else
{
printf("%.2lf is the largest number.\n", n3);
}
}
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 50


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

22. Write C Program to Check Whether a Character is a Vowel or Consonantvowel


or consonant.

 There are 5 vowels in English alphabets; these are a, e, i, o, and u. These vowels
can be in uppercase or lowercase.

Progaram:

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

printf("\n Enter any character: ");


scanf("%c", &ch);
//check alphabate
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
// check for vowel
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ||
ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
{
printf("\n It is an vowel.\n\n");
}
else
{
printf("\n It is a consonant.\n\n");
}
}
else
{
printf("\n It is not an vowel nor consonant.\n\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 51


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

23. Write C program to check whether a person is eligible for voting or not?

#include <stdio.h>
int main()
{
int a;
printf(" Enter your current Age Here:\n");
scanf("%d",&a);
if ( a < 18 )
{
printf("Consider as minor \n");
printf("Not fit for Working\n");
}
else
{
if (a >= 18 && a <= 50 )
{
printf("He/She is successfully eligible for Working \n");
printf("Fill all the details and apply for it\n");
}
else
{
printf("Age is not satisfactory according to the organization norms\n");

}
}
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 52


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

Syntax of if...else Ladder:

if (test expression1)
{
// statement(s)
}
else if(test expression2)
{
// statement(s)
}
else if (test expression3)
{
// statement(s)
}
..
else
{
// statement(s)
}

24. Write C Program to Find the Largest Number Among Three Numbers.

#include <stdio.h>
int main()
{
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);

// if n1 is greater than both n2 and n3, n1 is the largest


if (n1 >= n2 && n1 >= n3)
printf("%.2lf is the largest number.\n", n1);

// if n2 is greater than both n1 and n3, n2 is the largest


else if (n2 >= n1 && n2 >= n3)
printf("%.2lf is the largest number.\n", n2);

// if both above conditions are false, n3 is the largest


else
printf("%.2lf is the largest number.\n", n3);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 53


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

25. Write C Program to check if a given year is leap year leap or not.

#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.\n", 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.\n", year);
}
// leap year if not divisible by 100
// but divisible by 4
else if (year % 4 == 0)
{
printf("%d is a leap year.\n", year);
}
// all other years are not leap years
else {
printf("%d is not a leap year.\n", year);
}
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 54


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

26. Write C Program to Find Roots of a Quadratic Equation

#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;

printf("Enter coefficients a, b and c: ");


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

discriminant = b * b - 4 * a * c;

// condition for real and different roots


if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf\n", root1, root2);
}

// condition for real and equal roots


else if (discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2\n = %.2lf;", root1);
}

// if roots are not real


else
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi\n", realPart, imagPart,
realPart, imagPart);
}
}
OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 55


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

Syntax of switch...case:

switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements

27. Write C Program to create a simple arithmetic operations using switch case.

#include <stdio.h>

int main()
{
char operator;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf\n",n1, n2, n1+n2);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf\n",n1, n2, n1-n2);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf\n",n1, n2, n1*n2);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf\n",n1, n2, n1/n2);
break;

// operator doesn't match any case constant +, -, *, /

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 56


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
default:
printf("Error! operator is not correct\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 57


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

28. Write C program Simple Switch case program to display numbers.

#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);

switch(number)
{
case 30:
printf("number is equals to 30\n");
break;

case 60:
printf("number is equal to 60\n");
break;

case 90:
printf("number is equal to 90\n");
break;

default:
printf("number is not equal to 30, 60 or 90\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 58


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

29. Write C program to display vowel letter using switch case.

#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Enter any Alphabet\n"); //input alphabet from user
scanf("%c",&ch);//store the Entered Alphabet in ch
switch(ch)
{
case 'a':
printf("%c is a vowel\n",ch);
break;

case 'e':
printf("%c is a vowel\n",ch);
break;

case 'i':
printf("%c is a vowel\n",ch);
break;

case 'o':
printf("%c is a vowel\n",ch);
break;

case 'u':
printf("%c is a vowel\n",ch);
break;

//check upper case vowel letters

case 'A':
printf("%c is a vowel\n",ch);
break;

case 'E':
printf("%c is a vowel\n",ch);
break;

case 'I':
printf("%c is a vowel\n",ch);
break;

case 'O':
printf("%c is a vowel\n",ch);
break;

case 'U':

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 59


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
printf("%c is a vowel\n",ch);
break;

default:
printf("%c is a consonant\n",ch);
break;
}
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 60


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 3:

30. Write C Programs on Command line arguments.

Example 1:

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

int main(int argc, char *argv[])


{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}

TO RUN THE PROGRAM:


gcc name_of_file.c
./a.out Welcome to PPS

OUTPUT:

Welcome
to
PPS

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 61


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Example 2:

#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if( argc > 1 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}

gcc commandline.c
PC:~/knr$ ./a.out pps lab is the best lab

OUTPUT:

The arguments supplied are:


pps lab is the best lab
PC:~/knr$

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 62


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

 Programs on Conditional Statements (9)


 Programs on Looping Statements. (9)

The syntax of a while loop is :

while(condition)
{
statement(s);
}

1. Write C Program to Find factorial of a given number using while loop.

#include <stdio.h>
int main()
{
int n,i,f;
f=1; //f=i=1;
i=1;
printf("Enter a Number to Find Factorial: ");
scanf("%d",&n);
while(i<=n)
{
f*=i; //f=f*i;
i++;
}
printf("The Factorial of %d is : %d\n",n,f);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 63


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

2. Write a C program to print reverse of a given number using while loop.

#include <stdio.h>
int main()
{
int n, rev = 0, remainder;

printf("Enter an integer: ");


scanf("%d", &n);

while (n != 0)
{
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10; //n=n/10;
}

printf("Reversed number = %d\n", rev);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 64


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

3. Write a C Program to Find Sum of Digits of a Number using While Loop.

#include <stdio.h>

int main()
{
int Number, Reminder, Sum=0;

printf("\n Please Enter any number\n");


scanf("%d", &Number);

while(Number > 0)
{
Reminder = Number % 10;
Sum = Sum+ Reminder;
Number = Number / 10;
}
printf("\n Sum of the digits of Given Number = %d\n", Sum);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 65


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

4. Write a C program for Fibonacci series up to given length using while loop.

#include<stdio.h>
int main()
{
int f1=0,f2=1,f3,n;

printf("enter length of the fibonacci series:");


scanf("%d",&n);

printf("%d\t%d",f1,f2); // It prints the starting two values

while(n>0) // checks the condition


{
f3=f1+f2; // performs add operation on previous two values

printf("\t%d",f3); // It prints from third value to given length

f1=f2;
f2=f3;
n--; // n value should be decrement
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 66


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

5. Write a C Program to Check Whether a Number is Palindrome or Not using while


loop.

#include <stdio.h>
int main()
{
int num, reverse_num=0, remainder,temp;

printf("Enter an integer: ");


scanf("%d", &num);

/* Here we are generating a new number (reverse_num)


* by reversing the digits of original input number
*/
temp=num;
while(temp!=0)
{
remainder=temp%10;
reverse_num=reverse_num*10+remainder;
temp/=10;
}

/* If the original input number (num) is equal to


* to its reverse (reverse_num) then its palindrome
* else it is not.
*/

if(reverse_num==num)
{
printf("%d is a palindrome number\n",num);
}

else
{
printf("%d is not a palindrome number\n",num);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 67


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

6. Write a C Program to Check Armstrong Number of three digits using while loop.

#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
printf("armstrong number\n ");
else
printf("not armstrong number\n");

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 68


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

do while loop syntax:

do
{

//code to be executed

}while(conditio);

9. Write a C Program to print table for the given number using do while loop.

#include<stdio.h>
int main()
{
int i=1,number;

printf("Enter a number: ");


scanf("%d",&number);

do
{
printf("%d * %d = %d \n",number,i,(number*i));
i++;
}while(i<=10);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 69


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

9. Write a C program to check wheather the given number is prime or not using do-
while loop.

#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,x=2;
printf("Enter the number for testing(prime or not)\n:");
scanf("%d",&n);
do
{
if(n%x==0)
{
printf("The number %d is not prime number\n:",n);
exit(0);
}
x++;

}while(x<n);

printf(" The number %d is prime\n",n);


}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 70


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

10. Write a C program to display 1 to 10 numbers using do-while loop.

#include<stdio.h>
void main()
{
int m,n;

printf("enter m and n value:");


scanf("%d%d",&m,&n);

do
{
printf("%d\t",m);
m++;
}while(m<=n);
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 71


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

11. Write a C Program to calculate the Simple interest using do-while loop.

#include<stdio.h> // include stdio.h


int main()
{
float p, r, t;
char ch = 'y';
do
{
printf("Enter principal: ");
scanf("%f", &p);

printf("Enter rate: ");


scanf("%f", &r);

printf("Enter t: ");
scanf("%f", &t);

printf("SI = %.2f", (p *r * t)/100 );

printf("\n\nCalculate SI one more time ? ('y' for Yes, 'n' for no ) : ");
scanf(" %c", &ch); // notice the preceding white space before %c
}while(ch == 'y'); // keep asking for P, R and T til the input is 'y'

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 72


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

12. Write a C Program to print all prime numbers between 1 and 100 using while loop.

#include <stdio.h>
int main()
{
int count=0,n=0,i=1,j=1;
while(n<25)
{
j=1;
count=0;
while(j<=i)
{
if(i%j==0)
count++;
j++;
}

if(count==2)
{
printf("%d ",i);
n++;
}
i++;
}
}

OUTPUT:

pps-1@pps-lab-310:~/knr$ gcc prime.c

pps-1@pps-lab-310:~/knr$ ./a.out

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 73


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

Programs on Looping Statements. (9)

syntax of for loop:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

1. Write a C program to printf Half Pyramid using for loop.

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

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 74


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

2. Write a C program to check a number is prime number or not using for loop.

#include <stdio.h>
void main()
{
int n, i, count = 0;
printf("Enter any number n:");
scanf("%d", &n);

for (i = 1; i <= n; i++)


{
if (n % i == 0)
{
count++;
}
}

if (count == 2)
{
printf("n is a Prime number");
}
else
{
printf("n is not a Prime number");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 75


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

3. Write a C program to display Prime Numbers between Two Intervals using for
loop.

#include <stdio.h>
int main()
{
int low, high, i, flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Prime numbers between %d and %d are: ", low, high);

// iteration until low is not equal to high


while (low < high) {
flag = 0;

// ignore numbers less than 2


if (low <= 1) {
++low;
continue;
}

// if low is a non-prime number, flag will be 1


for (i = 2; i <= low / 2; ++i) {

if (low % i == 0) {
flag = 1;
break;
}
}

if (flag == 0)
printf("%d ", low);

// to check prime for the next number


// increase low by 1
++low;
}

return 0;
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gcc prime1.c
pps-1@pps-lab-310:~/knr$ ./a.out
Enter two numbers(intervals): 20
100
Prime numbers between 20 and 100 are: 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
97

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 76


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

4. Write a C program Perfect number is a positive number which sum of all


positive divisors excluding that number is equal to that number. For example 6 is
perfect number since divisor of 6 are 1, 2 and 3. Sum of its divisor is 1 + 2+ 3 = 6

#include <stdio.h>
Void main()
{
int n,i,sum;
int min,max;
printf("Input the number : ");
scanf("%d",&n);
sum = 0;
printf("The positive divisor : ");
for (i=1;i<n;i++)
{
if(n%i==0)
{
sum=sum+i;
printf("%d ",i);
}
}
printf("\nThe sum of the divisor is : %d\n",sum);
if(sum==n)
printf("\nSo, the number is perfect.\n");
else
printf("\nSo, the number is not perfect.\n");
printf("\n");
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 77


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

5. Write c program to print Floyd's Triangle using for loop.

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

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 78


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

6. Write a C Program to calculate the sum of first n natural numbers


Positive integers 1, 2, 3...n are known as natural numbers using for loop.

#include <stdio.h>
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when num is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d\n", sum);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 79


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

7. Write a C program to check whether a given number is an armstrong number or


not using for loop.

#include <stdio.h>
void main()
{
int num,rem,sum=0,temp;

printf("Input a number: ");


scanf("%d",&num);

for(temp=num;num>0;num=num/10)
{
rem=num % 10;
sum=sum+(rem*rem*rem);
}
if(sum==temp)
printf("%d is an Armstrong number.\n",temp);
else
printf("%d is not an Armstrong number.\n",temp);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 80


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

8. Write a C program to print Factorial of a number using for loop.

#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 81


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

9. Write a C Program for Fibonacci Series Using for Loop

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

int first = 0, second = 1, third, i, n;

printf ("Enter the length of the fibonacci series \n");

scanf ("%d", &n);

printf ("The Fibonacci series is :\n");

printf ("%d %d", first, second);

for (i = 2; i <= n; i++)

third = first + second;

printf (" %d ", third);

first = second;

second = third;

return 0;

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 82


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

10. Write a C program for Palindrome number using For Loop

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

printf("\n Enter The Number:");


scanf("%d",&n);

//LOOP TO FIND REVERSE OF A NUMBER


for(i=n;i>0; )
{
rem=i%10;
sum=sum*10+rem;
i=i/10;
}

/* CHECKING IF THE NUMBER ENTERED AND THE REVERSE NUMBER IS


EQUAL OR NOT */
if(sum==n)
{
printf("\n %d is a Palindrome Number",n);
}
else
{
printf("\n %d is not a Palindrome Number",n);
}
}

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 83


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 4:

11. Write a C program to reverse a number using for loop.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,rem,reverse=0;
printf("Enter a number for find reverse\n");
scanf("%d",&num);
printf("You entered %d\n",num);
for(;num!=0; num=num/10)
{
rem=num%10;
reverse=reverse*10+rem;
}
printf("Reverse of the given number %d\n",reverse);

OUT PUT:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 84


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

 Programs on One Dimensional Array. (4 programs), Linear search & Bubble sort
 Programs on Two Dimensional Arrays. (2 programs)

1. Write a program in C to store elements in an array and print it.

#include <stdio.h>
void main()
{
int arr[10];
int i;
printf("\n\nRead and Print elements of an array:\n");
printf("-----------------------------------------\n");

printf("Input 10 elements in the array :\n");


for(i=0; i<10; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}

printf("\nElements in array are: ");


for(i=0; i<10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

Output:

pps-1@pps-lab-310:~/knr$ gedit matonedi1.c


pps-1@pps-lab-310:~/knr$ gcc matonedi1.c
pps-1@pps-lab-310:~/knr$ ./a.out

Read and Print elements of an array:


-----------------------------------------
Input 10 elements in the array :
element - 0 : 1
element - 1 : 2
element - 2 : 3
element - 3 : 4
element - 4 : 5
element - 5 : 6
element - 6 : 7
element - 7 : 8
element - 8 : 9
element - 9 : 10
Elements in array are: 1 2 3 4 5 6 7 8 9 10

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 85


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

2. Write a program in C to read n number of values in an array and display it in


reverse order.

#include <stdio.h>
void main()
{
int i,n,a[100];

printf("Input the number of elements to store in the array :");


scanf("%d",&n);

printf("Input %d number of elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}

printf("\nThe values store into the array are : \n");


for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}

printf("\n\nThe values store into the array in reverse are :\n");


for(i=n-1;i>=0;i--)
{
printf("% 5d",a[i]);
}
printf("\n\n");
}

OUTPUT:

pps-1@pps-lab-310:~/knr$ gedit mat_rev.c


pps-1@pps-lab-310:~/knr$ gcc mat_rev.c
pps-1@pps-lab-310:~/knr$ ./a.out
Input the number of elements to store in the array :3
Input 3 number of elements in the array :
element - 0 : 2
element - 1 : 5
element - 2 : 7

The values store into the array are :


2 5 7

The values store into the array in reverse are :


7 5 2

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 86


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

3. Write a program in C to find the sum of all elements of the array.

#include <stdio.h>
void main()
{
int a[100];
int i, n, sum=0;

printf("\n\nFind sum of all elements of array:\n");


printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);

printf("Input %d elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}

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


{
sum += a[i];
}

printf("Sum of all elements stored in the array is : %d\n\n", sum);


}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit mat_sum.c
pps-1@pps-lab-310:~/knr$ gcc mat_sum.c
pps-1@pps-lab-310:~/knr$ ./a.out
Find sum of all elements of array:
Input the number of elements to be stored in the array: 3
Input 3 elements in the array:
element - 0 : 2
element - 1 : 5
element - 2 : 8
Sum of all elements stored in the array is: 15

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 87


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

4. Write a program in C to find the maximum and minimum element in an array.


#include <stdio.h>
void main()
{
int arr1[100];
int i, mx, mn, n;
printf("\n\nFind maximum and minimum element in an array :\n");
printf("--------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
mx = arr1[0];
mn = arr1[0];
for(i=1; i<n; i++)
{
if(arr1[i]>mx)
{
mx = arr1[i];
}
if(arr1[i]<mn)
{
mn = arr1[i];
}
}
printf("Maximum element is : %d\n", mx);
printf("Minimum element is : %d\n\n", mn);
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit min_max.c
pps-1@pps-lab-310:~/knr$ gcc min_max.c
pps-1@pps-lab-310:~/knr$ ./a.out

Find maximum and minimum element in an array :


--------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 45
element - 1 : 25
element - 2 : 21
Maximum element is : 45
Minimum element is : 21

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 88


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

5. Write a program in C for a 2D array of size 3x3 and print the matrix.

#include <stdio.h>
void main()
{
int arr1[3][3],i,j;
printf("\n\nRead a 2D array of size 3x3 and print the matrix :\n");
printf("------------------------------------------------------\n");
/* Stored values into the array*/
printf("Input elements in the matrix :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("\nThe matrix is : \n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",arr1[i][j]);
}
printf("\n\n");
}
OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit mat2d.c
pps-1@pps-lab-310:~/knr$ gcc mat2d.c
pps-1@pps-lab-310:~/knr$ ./a.out
Read a 2D array of size 3x3 and print the matrix :
------------------------------------------------------
Input elements in the matrix :
element - [0],[0] :1
element - [0],[1] : 2
element - [0],[2] : 3
element - [1],[0] : 4
element - [1],[1] : 5
element - [1],[2] : 6
element - [2],[0] : 7
element - [2],[1] : 8
element - [2],[2] : 9

The matrix is :

1 2 3
4 5 6
7 8 9

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 89


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

6. Write a program in C for addition of two Matrices of same size.

#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;

printf("\n\nAddition of two Matrices :\n");


printf("------------------------------\n");
printf("Input the size of the square matrix (less than 5): ");
scanf("%d", &n);

/* Stored values into the array*/


printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("Input elements in the second matrix :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",brr1[i][j]);
}
/* calculate the sum of the matrix */
for(i=0;i<n;i++)
for(j=0;j<n;j++)

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 90


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
crr1[i][j]=arr1[i][j]+brr1[i][j];
printf("\nThe Addition of two matrix is : \n");
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",crr1[i][j]);
}
printf("\n\n");
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit 2d_addition.c
pps-1@pps-lab-310:~/knr$ gcc 2d_addition.c
pps-1@pps-lab-310:~/knr$ ./a.out
Addition of two Matrices :
------------------------------
Input the size of the square matrix (less than 5): 2
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8

The First matrix is :


1 2
3 4
The Second matrix is :
5 6
7 8
The Addition of two matrix is :
6 8
10 12

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 91


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

7. Write a program in C for multiplication of two square Matrices.

#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,k,r1,c1,r2,c2,sum=0;

printf("\n\nMultiplication of two Matrices :\n");


printf("----------------------------------\n");

printf("\nInput the rows and columns of first matrix : ");


scanf("%d %d",&r1,&c1);
printf("\nInput the rows and columns of second matrix : ");
scanf("%d %d",&r2,&c2);
if(c1!=r2){
printf("Mutiplication of Matrix is not possible.");
printf("\nColumn of first matrix and row of second matrix must be same.");
}
else
{
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Input elements in the second matrix :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<r2;i++)
{
printf("\n");

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 92


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
for(j=0;j<c2;j++)
printf("%d\t",brr1[i][j]);
}
//multiplication of matrix
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
crr1[i][j]=0;
for(i=0;i<r1;i++) //row of first matrix
{
for(j=0;j<c2;j++) //column of second matrix
{
sum=0;
for(k=0;k<c1;k++)
sum=sum+arr1[i][k]*brr1[k][j];
crr1[i][j]=sum;
}
}
printf("\nThe multiplication of two matrices is : \n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",crr1[i][j]);
}
}
}
printf("\n\n");
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit matrix_mul.c
pps-1@pps-lab-310:~/knr$ gcc matrix_mul.c
pps-1@pps-lab-310:~/knr$ ./a.out
Multiplication of two Matrices :
----------------------------------

Input the rows and columns of first matrix : 2


2

Input the rows and columns of second matrix : 2


2
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 93


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
The First matrix is :
Multiplication of two Matrices :
----------------------------------

Input the rows and columns of first matrix : 2


2

Input the rows and columns of second matrix : 2


2
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8

The First matrix is :

1 2
3 4
The Second matrix is :

5 6
7 8
The multiplication of two matrices is :

19 22
43 50

1 2
3 4
The Second matrix is :

5 6
7 8
The multiplication of two matrices is :

19 22
43 50

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 94


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

8. Write a program in C to find transpose of a given matrix.

#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],i,j,r,c;

printf("\n\nTranspose of a Matrix :\n");


printf("---------------------------\n");

printf("\nInput the rows and columns of the matrix : ");


scanf("%d %d",&r,&c);

printf("Input elements in the first matrix :\n");


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

printf("\nThe matrix is :\n");


for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf("%d\t",arr1[i][j]);
}

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

printf("\n\nThe transpose of a matrix is : ");


for(i=0;i<c;i++){
printf("\n");
for(j=0;j<r;j++){
printf("%d\t",brr1[i][j]);
}
}
printf("\n\n");
}

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 95


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit transpose.c
pps-1@pps-lab-310:~/knr$ gcc transpose.c
pps-1@pps-lab-310:~/knr$ ./a.out
Transpose of a Matrix :
---------------------------

Input the rows and columns of the matrix : 2 2


Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4

The matrix is :

1 2
3 4

The transpose of a matrix is :


1 3
2 4

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 96


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

9. Write a C program to Implementation of Linear Search and Binary Search.

Program to implement linear search:

#include<stdio.h>
main()
{
int i,j,n,a[10],key;
clrscr();
printf("enter range for array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<=n;i++)
scanf("%d",&a[i]);
printf("enter the search element:");
scanf("%d",&key);
for(i=0;i<=n;i++)
{
if(key==a[i])
{
printf("element %d found at %d",key,i);
break;
}
else
if(i==n)
printf("element %d not found in array",key);
}
getch();
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit linearsearch.c
pps-1@pps-lab-310:~/knr$ gcc linearsearch.c
pps-1@pps-lab-310:~/knr$ ./a.out
enter range for array:4
enter elements into array:56
43
12
88
9
enter the search element:9
element 9 found at 4

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 97


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

10. Write a C Program to perform the binary search operation.

Program:

#include<stdio.h>
int main()
{
int i,n,key,a[10],low,high,mid;
printf("enter range for array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the search element:");
scanf("%d",&key);
low=0;
high=n-1;
for(i=0;i<n;i++)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("element %d found at %d",key,mid);
break;
}
if(key<a[mid])
high=mid;
else
low=mid+1;
if(i==n-1)
printf("element %d not found in array",key);
}
return 0;
}

Output:
pps-1@pps-lab-310:~/knr$ gedit binarysearch.c
pps-1@pps-lab-310:~/knr$ gcc binarysearch.c
pps-1@pps-lab-310:~/knr$ ./a.out
enter range for array:4
enter elements into array:12 23 34 45
the search element:45
element 45 found at 3

enter range for array:5


enter elements into array:1 34 56 78 88
the search element:45
element 45 not found in array

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 98


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

11. Write a C Program that implements the bubble sort method.

#include<stdio.h>
main()
{
int i,j,t,a[5],n;
clrscr();
printf("enter the range of array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("the sorted order is:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
return 0;
}
Output:
pps-1@pps-lab-310:~/knr$ gedit bubblesort.c
pps-1@pps-lab-310:~/knr$ gcc bubblesort.c
pps-1@pps-lab-310:~/knr$ ./a.out
enter the range of array:3
enter elements into array:3
2
1
the sorted order is: 1 2 3

enter the range of array:5


enter elements into array:56
23
34
12
8
the sorted order is: 8 12 23 34 56

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 99


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

12. Write a C program for selectioon sort

#incude<stdio.h>
int main()
{
int arr[5]={25,17,31,13,2};
int I,j,temp;
printf(“selection sort\n”);
printf(“\n array before sorting:\n”);
for(i=0;i<=3;i++)
printf(“%d\t,arr[i]”);
for(i=0;i<=3;i++)
{
for(j=j+1;j<=4;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf(“\n\n array after sortong:\n”);
for(i=0;i<=4;i++)
printf(“%d\t”,arr[i]);
return 0;
}

Output:
pps-1@pps-lab-310:~/knr$ gedit selectionsort.c
pps-1@pps-lab-310:~/knr$ gcc selectionsort.c
pps-1@pps-lab-310:~/knr$ ./a.out
1) Selection sort
Array before sorting:
25 17 31 13 2
Array after sorting:
2 13 17 25 31

2) selection sort
Array before sort
25 31 30 12 1
Array after sort
1 12 25 30 31

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 100


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 5:

13. Write a C Program that implements the insertion sort method

#include<stdio.h>
main()
{
int i,j,t,a[10],n,p=0;
printf("enter the range of array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
t=a[i];
for(p=i;p>0 && a[p-1]>t;p--)
a[p]=a[p-1];
a[p]=t;
}
printf("the sorted order is:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
return 0;
}

Output:
pps-1@pps-lab-310:~/knr$ gedit insertionsort.c
pps-1@pps-lab-310:~/knr$ gcc insertionsort.c
pps-1@pps-lab-310:~/knr$ ./a.out
enter the range of array:5
enter elements into array:5
4
3
2
1
the sorted order is: 1 2 3 4 5

enter the range of array:6


enter elements into array:23
12
89
45
67
34
the sorted order is: 12 23 34 45 67 89

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 101


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

 Programs on Strings.
 Programs on Strings with and without using string built-in Functions.

1. Write C program to read a string .

#include <stdio.h>
main ()
{
char str[80];
printf("enter text");
gets(str);
printf("entered text is:");
puts(str);
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit string1.c
pps-1@pps-lab-310:~/knr$ gcc string1.c
pps-1@pps-lab-310:~/knr$ ./a.out
enter text pps lab
entered text is: pps lab

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 102


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

2. Write C program to size of a string.

#include <stdio.h>
int main()
{
char s1[]={"welcome"};
char s2[20]={'a','e','i','o','u','\0'};
char s3[]={"environment"};
char s4[]={"India has won thomas cup after 43 years"};
printf("s1=%s,sizeof(s1)=%d\n",s1,sizeof(s1));
printf("s2=%s,sizeof(s2)=%d\n",s2,sizeof(s2));
printf("s3=%s,sizeof(s3)=%d\n",s3,sizeof(s3));
printf("s4=%s,sizeof(s4)=%d\n",s4,sizeof(s4));
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit string2.c
pps-1@pps-lab-310:~/knr$ gcc string2.c
pps-1@pps-lab-310:~/knr$ ./a.out
s1=welcome,sizeof(s1)=8
s2=aeiou,sizeof(s2)=20
s3=environment,sizeof(s3)=12
s4=India has won thomas cup after 43 years,sizeof(s4)=40

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 103


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

3. Write C program to find the length of the string.

#include<stdio.h>
#include

int main()
{
char str[30];
int len;

printf("Enter string:\n");
gets(str);

len = strlen(str);

printf("Length of given string is: %d", len);

return 0;
}

output:
pps-1@pps-lab-310:~/knr$ gedit stringlen.c
pps-1@pps-lab-310:~/knr$ gcc stringlen.c
pps-1@pps-lab-310:~/knr$ ./a.out

Enter string:
Welcome to C
Length of given string is: 12

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 104


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

4. Write C program to copy content of one string variable to another string


variable.

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

int main()
{
char str1[30], str2[30];

printf("Enter string:\n");
gets(str1);
strcpy(str2, str1);
printf("Coped string is: %s”, str2);

return 0;
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit stringcopy.c
pps-1@pps-lab-310:~/knr$ gcc stringcopy.c
pps-1@pps-lab-310:~/knr$ ./a.out
Enter string:
Welcome to C
Copied string is: Welcome to C

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 105


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

5. Write C program to compare two strings.

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

int main()
{
char str1[40], str2[40];
int d;

printf("Enter first string:\n");


gets(str1);
printf("Enter second string:\n");
gets(str2);
d = strcmp(str1, str2);
if(d==0)
{
printf("Given strings are same.");
}
else
{
printf("Given strings are different.");
}

return 0;
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit strcompare.c
pps-1@pps-lab-310:~/knr$ gcc strcompare.c
pps-1@pps-lab-310:~/knr$ ./a.out

Run 1:
--------------
Enter first string:
Welcome to C
Enter second String:
Welcome to C
Given strings are same.

Run 2:
--------------
Enter first string:
Welcome
Enter second String:
Welcome to C
Given strings are different.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 106


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

6. Write C program to concatenate two strings.

#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
printf("Enter first string:\n");
gets(str1);
printf("Enter second string:\n");
gets(str2);
strcat(str1,str2);
printf("Concatenated string is: %s", str1);
return 0;
}

output:
pps-1@pps-lab-310:~/knr$ gedit strcon.c
pps-1@pps-lab-310:~/knr$ gcc strcon.c
pps-1@pps-lab-310:~/knr$ ./a.out
Enter first string:
pps
Enter second String:
Naga
Concatenated string is: ppsNaga

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 107


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

7. Write C program to reverse a string

#include<stdio.h>
#include<string.h>
int main()
{
char name[40];

printf("Enter your name: ");


gets(name);

strrev(name);

printf("Reversed name is: %s", name);

return 0;
}

Output:
Enter youe name: pps
Reversed name is: spp

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 108


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

8. Write C program to convert all lower case letter in string to upper case.

#include<stdio.h>
#include<string.h>
int main()
{
char str[40];
printf("Enter string:\n");
gets(str);
strupr(str);
printf("String in uppercase is:");
puts(str);

return 0;
}

OUTPUT:
Enter string:
WeLcOmE To C 101. ↲
String in lowercase is:
WELCOME TO C 101.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 109


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

9. Write C program to convert all upper case letter in string to lower case.

i. Program:

#include<stdio.h>
#include<string.h>
int main()
{
char str[40];
printf("Enter string:\n");
gets(str);
strlwr(str);
printf("String in lowercase is:");
puts(str);

return 0;
}

OUTPUT:
Enter string:
WeLcOmE To C 101.
String in lowercase is:
welcome to c 101.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 110


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
ii. Write a C Program to String functions (predefined) examples.

#include<stdio.h>
#include<string.h>
void main()
{
char s1[50],s2[50],s3[50];
int cmp;
printf("Enter three strings\n");
gets(s1);
gets(s2);
gets(s3);
printf("length of s1 is %d\n",strlen(s1));
strcpy(s3,s1);
printf("After copying 1st string into 3rd string is %s\n",s3);
cmp=strcmp(s1,s2);
if(cmp==0)
printf("The two Strings s1 and s2 are equal\n");
else
printf("The two Strings s1 and s2 are not equal\n");
printf("Reverse of a string is %s",strrev(s1));
printf("After adding first two strings %s\n",strcat(s1,s2));
}

Output:

pps-1@pps-lab-310:~/knr$ ./a.out
Enter three strings
HI WELCOME
TO PPSLAB1
ROOM NO 310
length of s1 is 10
After copying 1st string into 3rd string is HI WELCOME
The two Strings s1 and s2 are not equal
After adding first two strings HI WELCOMETO PPSLAB1

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 111


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

10. Write C program without using string built-in Functions.

 String length1:

#include <stdio.h>
int main()
{
//Initializing variable.
char str[100];
int i,length=0;

//Accepting input.
printf("Enter a string: \n");
scanf("%s",str);

//Initializing for loop.


for(i=0; str[i]!='\0'; i++)
{
length++; //Counting the length.
}

printf("\nLength of input string: %d",length);

return 0;
}

pps-1@pps-lab-310:~/knr$ gedit stringlen.c


pps-1@pps-lab-310:~/knr$ gcc stringlen.c
pps-1@pps-lab-310:~/knr$ ./a.out
Enter a string:
welcome
Length of input string: 7

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 112


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
 String length2:

#include <stdio.h>
int main()
{
char s[] = "Programming is fun";
int i;

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

printf("Length of the string: %d", i);


return 0;
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit stringlen.c
pps-1@pps-lab-310:~/knr$ gcc stringlen.c
pps-1@pps-lab-310:~/knr$ ./a.out
Enter a string:
welcome
Length of input string: 7

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 113


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
 string copy:

#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);

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


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

s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}

OUT PUT:
Enter string s1: hi iam a programmer.
String s2: hi iam a programmer.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 114


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
 String reverse:

#include <stdio.h>
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;

printf("Input a string\n");
gets(s);
// Calculating string length

while (s[count] != '\0')


count++;
end = count - 1;

for (begin = 0; begin < count; begin++) {


r[begin] = s[end];
end--;
}

r[begin] = '\0';
printf("%s\n", r);
return 0;
}
OUTPUT:
pps-1@pps-lab-310:~/knr$ gedit string.c
pps-1@pps-lab-310:~/knr$ gcc string.c

pps-1@pps-lab-310:~/knr$ ./a.out
Input a string
hi welcome
emoclew ih

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 115


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
 String Compare:

#include<stdio.h>
int main() {
char str1[30], str2[30];
int i;
printf("\nEnter two strings :");
gets(str1);
gets(str2);
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])
printf("str1 < str2");
else
printf("str1 = str2");
return (0);
}

OUTPUT:
pps-1@pps-lab-310:~/knr$ ./a.out

Enter two strings :welcome boy


welcome girl
str1 < str2pps-1@pps-lab-310:~/knr$ ./a.out

Enter two strings :welcome boys


welcome boys
str1 = str2

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 116


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
 Concatenated String:

#include<stdio.h>
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

OUTPUT:
Enter First String:PPSLAB1
Enter Second String:IN E-BLOCK 310
Concatenated String is PPSLAB1IN E-BLOCK 310

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 117


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

11. Write a C to determine if the given string is a palindrome or not

#include<stdio.h>
void main()
{
char S[50];
int Len = 0, Flag =0,I,J;
printf(“enter a string”);
gets(S);
while (S[Len]!= NULL)
Len++;
I = 0 ,J = Len-1;
while ( I< (Len/2)+1 )
{
if ( S[I]== S[J] )
Flag=0;
else
Flag=1;
I++;
J- -;
}
if ( Flag == 0 )
printf(“the given string %s is a palindrome”, S);
else
printf(“the given string %s is not a palindrome”, S)
}

Output:
1. Enter the string:malayalam
The given string malayalam is a palindrome
2. Enter the string:india
The given string india is not a palindrome

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 118


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 6:

12. Write a C Program to count the lines, words & characters in a given text

#include <stdio.h>
main()
{
char line[81], ctr;
int i,c,end = 0, characters = 0,words = 0,lines = 0;
printf("KEY IN THE TEXT.\n");
printf("GIVE ONE SPACE AFTER EACH WORD.\n");
printf("WHEN COMPLETED, PRESS 'RETURN'.\n\n");
while( end==0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
printf ("\n");
printf("Number of lines = %d\n", lines);
printf("Number of words = %d\n", words);
printf("Number of characters = %d\n", characters);
}
Output:
1. KEY IN THE TEXT.
GIVE ONE SPACE AFTER EACH WORD.
WHEN COMPLETED, PRESS 'RETURN'.
Admiration is a very short-lived passion.
Admiration involves a glorious obliquity of vision.
Always we like those who admire us but we do not
like those whom we admire.
Fools admire, but men of sense approve.
Number of lines = 5
Number of words = 36
Number of characters = 205

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 119


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

 Programs on Accessing Structures and Nested Structures.


 Programs on Pointers, pointer arithmetic, pointer expression
 Programs on Pointer to structure, Call by Reference, Pointer to Pointer.
 Programs on Unions, typedef and enum.

//Programs on Accessing Structures and Nested Structures.

1. Write a C Program to display student information by initializing structures

#include<stdio.h>
struct student
{
char name[10];
int rollno;
int age;
};
main()
{
static struct student s1;
printf("enter the name,rollno,age");
scanf("%s%d%d\n",&s1.name,&s1.rollno,&s1.age);
printf("%s %d %d",s1.name,s1.rollno,s1.age);
}

Output:
Ente name, rollno,age
Ravi 11 25
Ravi 11 25

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 120


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

2. Write a C program to find the salary of employee and salary details using nested
structures.

Program:

#include<stdio.h>
struct employee
{
char name[10];
int id;
struct salary
{
int basic,pf;
float hra,ta,da,gross;
}s1;
}e1;
main()
{
printf("enter name & id of emp");
scanf("%s%d",&e1.name,&e1.id);
printf("enter salary of emp");
scanf("%d%f%f%d",&e1.s1.basic,&e1.s1.hra,&e1.s1.da,&e1.s1.pf);
e1.s1.hra=15% * basic;
e1.s1.da=45%*basic;
e1.s1.gross=e1.s1.basic+e1.s1.hra+e1.s1.da+-e1.s1.pf;
printf("%s\n%d",e1.name,e1.s1.gross);
printf("\n%d\n%f\n%d\n%f\n",e1.s1.basic,e1.s1.hra,e1.s1.da,e1.s1.pf,e1.s1.gross);
}
Output:
Enter name and id of emp
knr
101
Enter salary of Emp
5000
Gross salary : 8000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 121


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

3. Program to print the Student information using nested structures.

Program:
#include<stdio.h>
struct person
{
char name[20];
int age;
char dob[10];
};
struct student
{
struct person info;
int roll_no;
float marks;
};
int main()
{
struct student s1;
printf("Details of student: \n\n");
printf("Enter name: ");
scanf("%s", s1.info.name);
printf("Enter age: ");
scanf("%d", &s1.info.age);
printf("Enter dob: ");
scanf("%s", s1.info.dob);
printf("Enter roll no: ");
scanf("%d", &s1.roll_no);
printf("Enter marks: ");
scanf("%f", &s1.marks);
printf("Name: %s\n", s1.info.name);
printf("Age: %d\n", s1.info.age);
printf("DOB: %s\n", s1.info.dob);
printf("Roll no: %d\n", s1.roll_no);
printf("Marks: %.2f\n", s1.marks);

// signal to operating system program ran fine


return 0;
}

out put:
Details of student:

Enter name: Phil


Enter age: 27
Enter dob: 23/4/1990
Enter roll no: 78123
Enter marks: 92

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 122


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

4. Write a C A program to find the total no. of marks using array of structure.

#include<stdio.h>
struct student
{
char name[10];
int rollno;
int subject[5],total;
};
main ( )
{
static struct student s[100];
int n,i,j;
clrscr();
printf("enter the no.of students");
scanf("%d",&n);
printf("enter the marks of fivesubjects");
for(i=0;i<n;i++)
{
printf("enter s[%d] student marks",i);
s[i].total=0;
for(j=0;j<5;j++)
{
scanf("%d",&s[i].subject[j]);
s[i].total=s[i].total+s[i].subject[j];
}
printf("%d",s[i].total);
}
}

Output:
enter the no.of students2
enter the marks of fivesubjectsenter s[0] student marks1
2
3
4
5
15enter s[1] student marks12
32
14
15
65
138

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 123


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

Programs on Pointers, pointer arithmetic, pointer expression

/* Incorrect: *ptr_a/*ptr_b;
Correct: *ptr_a / *ptr_b;
Correct: (*ptr_a)/(*ptr_b); */

1. Write a C Program to print address of x variable

#include <stdio.h>
int main()
{
int x = 10;
// Prints address of x
printf(
"Address of variable x = %p", &x);
return 0;
}

Output:
Address of variable x = 0x7fff3b690fd4

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 124


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

2. Program to illustrate accessing the value of variable using pointers using


arithmetic operations.

#include<stdio.h>
main()
{
int a,b,*p1,*p2,x,y,z;
a=12,b=4;
p1=&a; p2=&b;
x=*p1**p2-6;
y=(4-*p2)**p1+10;
printf("addressof a=%d\n",p1);
printf("addressof b=%d\n",p2);
printf("a=%d,b=%d\n",a,b);
printf("x=%d,y=%d\n",x,y);
*p2=*p2+3; *p1=*p2-5;
z=*p1**p2-6;
printf("a=%d,b=%d\n",a,b);
printf("z=%d\n",z);
return 0;
}

Output:

Address of a = 65543
Address of b = 64455
a = 12 b = 4
z=42

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 125


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

3. Write a C Program to illustrate the address of a variable using various methods.

#include<stdio.h>
main()
{
char a;
int x;
float p,q;
a='a';
x=125;
p=10.25,q=18.76;
printf("%c is stored at address %u\n",a,&a);
printf("%d is stored at address %u\n",x,&x);
printf("%f is stored at address %u\n",p,&p);
printf("%f is stored at address %u\n",q,&q);
return 0;
}

Output:
a is stored at address 65525
125 is stored at address 65522
10.250000 is stored at address 65518
18.760000 is stored at address 65514

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 126


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

4. Write a C program to showing pointer expressions

// during Arithmetic Operations

#include <stdio.h>
int main()
{
// Integer variables
int a = 20, b = 10;

// Variables for storing arithmetic


// operations solution
int add, sub, div, mul, mod;

// Pointer variables for variables


// a and b
int *ptr_a, *ptr_b;

// Initialization of pointers
ptr_a = &a;
ptr_b = &b;

// Performing arithmetic Operations


// on pointers
add = *ptr_a + *ptr_b;
sub = *ptr_a - *ptr_b;
mul = *ptr_a * *ptr_b;
div = *ptr_a / *ptr_b;
mod = *ptr_a % *ptr_b;

// Printing values
printf("Addition = %d\n", add);
printf("Subtraction = %d\n", sub);
printf("Multiplication = %d\n", mul);
printf("Division = %d\n", div);
printf("Modulo = %d\n", mod);
return 0;
}

Output:
Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2
Modulo = 0

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 127


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

5. Write a C program showing Relational Operations using pointer expressions

#include <stdio.h>
int main()
{
// Initializing integer variables
int a = 20, b = 10;

// Declaring pointer variables


int* ptr_a;
int* ptr_b;

// Initializing pointer variables


ptr_a = &a;
ptr_b = &b;

// Performing relational operations


// less than operator
if (*ptr_a < *ptr_b)
{
printf("%d is less than %d.", *ptr_a, *ptr_b);
}

// Greater than operator


if (*ptr_a > *ptr_b)
{
printf("%d is greater than %d.", *ptr_a, *ptr_b);
}

// Equal to
if (*ptr_a == *ptr_b)
{
printf("%d is equal to %d.", *ptr_a, *ptr_b);
}

return 0;
}

Output:

20 is greater than 10.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 128


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

6. Write a C program showing Assignment Operations using pointer expressions

#include <stdio.h>
int main()
{
// Initializing integer variable
int a = 30;

// Declaring pointer variable


int* ptr_a;

// Initializing pointer using


// assignment operator
ptr_a = &a;

// Changing the variable's value using


// assignment operator
*ptr_a = 50;

// Printing value of 'a' after


// updating its value
printf("Value of variable a = %d", *ptr_a);

return 0;
}

Output:
Value of variable a = 50

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 129


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

7. Write a C program showing Conditional Operations using pointer expressions

/*Syntax:
expression1 ? expression2 : expression3;

Example:
c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2; */

#include <stdio.h>
int main()
{
// Initializing integer variables
int a = 15, b = 20, result = 0;

// Declaring pointer variables


int *ptr_a, *ptr_b;

// Initializing pointer variables


ptr_a = &a;
ptr_b = &b;

// Performing ternary operator


result = ((*ptr_a > *ptr_b) ? *ptr_a : *ptr_b);

// Printing result of ternary operator


printf("%d is the greatest.", result);
return 0;
}

Output:
20 is the greatest.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 130


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

8. Write a C program showing Unary Operations using pointer expressions.

#include <stdio.h>
int main()
{
// Initializing integer variable
int a = 34;

// Declaring pointer variable


int* ptr_a;

// Initializing pointer variable


ptr_a = &a;

// Value of a before increment


printf("Increment:\n");
printf(
"Before increment a = %d\n", *ptr_a);

// Unary increment operation


(*ptr_a)++;

// Value of a after increment


printf(
"After increment a = %d", *ptr_a);

// Value before decrement


printf("\n\nDecrement:\n");
printf(
"Before decrement a = %d\n", *ptr_a);

// unary decrement operation


(*ptr_a)--;

// Value after decrement


printf("After decrement a=%d", *ptr_a);

return 0;
}

Output:

Increment:
Before increment a = 34
After increment a = 35

Decrement:
Before decrement a = 35
After decrement a=34

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 131


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

9. Write a C program showing Bitwise Operations using pointer expressions

#include <stdio.h>
int main()
{
// Declaring integer variable for
// storing result
int and, or, ex_or;

// Initializing integer variable


int a = 1, b = 2;
// Performing bitwise operations
// AND operation
and = a & b;
// OR operation
or = a | b;
// EX-OR operation
ex_or = a ^ b;
// Printing result of operations
printf("\na AND b = %d", and);
printf("\na OR b = %d", or);
printf("\na Exclusive-OR b = %d", ex_or);
return 0;
}

Output:

a AND b = 0
a OR b = 3
a Exclusive-OR b = 3

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 132


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

10. Write a C program traversal using pointers.

#include <stdio.h>
int main()
{
int N = 5;
// An array
int arr[] = { 1, 2, 3, 4, 5 };
// Declare pointer variable
int* ptr;
// Point the pointer to first
// element in array arr[]
ptr = arr;
// Traverse array using ptr
for (int i = 0; i < N; i++)
{
// Print element at which
// ptr points
printf("%d ", ptr[0]);
ptr++;
}
}

Output:

12345

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 133


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

11. Program to print the elements of array using pointers.

#include<stdio.h>
main()
{
int a[5]={5,4,6,8,9};
int *p=&a[0];
int i;
for(i=0;i<5;i++)
printf("%d",*(p+i));
for(i=0;i<5;i++)
printf(" %u\n",(p+i));
}

Output:
12345
12345

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 134


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

12. Program to display 2D array elements using pointer to function.

#include <stdio.h>
#define ROWS 4
#define COLS 3

void array_of_arrays_ver(int arr[][COLS]); /* prototype */


void ptr_to_array_ver(int (*arr)[COLS]); /* prototype */

int main ()
{
// declare 4x3 array
int matrix[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
printf("Printing Array Elements by Array of Arrays Version Function: \n");
array_of_arrays_ver(matrix);
printf("Printing Array Elements by Pointer to Array Version Function: \n");
ptr_to_array_ver(matrix);
return 0;
}

void array_of_arrays_ver(int arr[][COLS])


{
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}
}
void ptr_to_array_ver(int (*arr)[COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
printf("%d\t", (*arr)[j]);
}
arr++;
printf("\n");
}
}

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 135


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Output:

Printing Array Elements by Array of Arrays Version Function:


1 2 3
4 5 6
7 8 9
10 11 12
Printing Array Elements by Pointer to Array Version Function:
1 2 3
4 5 6
7 8 9
10 11 12

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 136


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

13. Write a C Program for matrix addition using pointers to function

/* Function declaration to input, add and print matrix */


void matrixInput(int mat[][COLS]);
void matrixPrint(int mat[][COLS]);
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);

int main()
{
int mat1[ROWS][COLS], mat2[ROWS][COLS], res[ROWS][COLS];

// Input elements in first matrix


printf("Enter elements in first matrix of size %dx%d: \n", ROWS, COLS);
matrixInput(mat1);

// Input element in second matrix


printf("\nEnter elemetns in second matrix of size %dx%d: \n", ROWS, COLS);
matrixInput(mat2);

// Finc sum of both matrices and print result


matrixAdd(mat1, mat2, res);

printf("\nSum of first and second matrix: \n");


matrixPrint(res);

return 0;
}

void matrixInput(int mat[][COLS])


{
int i, j;

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


{
for (j = 0; j < COLS; j++)
{
// (*(mat + i) + j) is equal to &mat[i][j]
scanf("%d", (*(mat + i) + j));
}
}
}

void matrixPrint(int mat[][COLS])


{
int i, j;

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


{
for (j = 0; j < COLS; j++)

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 137


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
{
// *(*(mat + i) + j) is equal to mat[i][j]
printf("%d ", *(*(mat + i) + j));
}
printf("\n");
}
}

void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS])


{
int i, j;

// Iterate over each matrix elements


for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
// res[i][j] = mat1[i][j] + mat2[i][j]
*(*(res + i) + j) = *(*(mat1 + i) + j) + *(*(mat2 + i) + j);
}
}
}

Output:
Enter elements in first matrix of size 3x3:
123
456
789

Enter elemetns in second matrix of size 3x3:


987
654
321

Sum of first and second matrix:


10 10 10
10 10 10
10 10 10

Programs on Pointer to structure, Call by Reference, Pointer to Pointer.

(i) A program to print the elements of a structure using pointers


#include<stdio.h>
struct invest
{
char name[20];
int number;
float price;
};
main()

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 138


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
{
struct invest product[3],*ptr;
printf("input\n\n");
for(*ptr=product[3];ptr<product+3;ptr++)
scanf("%s%d%f",ptr->name,&ptr->number,&ptr->price);
printf("\nOutput \n\n");
ptr=product;
while(ptr<product+3)
{
printf("%20s%5d%10.2f\n",ptr->name,ptr->number,ptr->price);
ptr++;
}
return 0;
}

Output:
input
Computer
12
15000
Tv
15
6000
Radio
45
1500

Output
Computer 12 15000.00
Tv 15 6000.00
Radio 45 1500.00

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 139


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

14. Write a C program to accessing Structure Members with Pointer.

#include <stdio.h>
struct my_structure
{
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"StudyTonight", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
output:
NAME: StudyTonight
NUMBER: 35
RANK: 1

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 140


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

15. Write a C Program to implement call by value

#include<stdio.h>
void swap(int ,int);
int main()
{
int a,b;
printf(“Enter the a, b values\n”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a, b values are %d, %d\n”,a,b);
swap(a,b);
printf(“After swapping a, b values are %d, %d\n”,a,b);
return 0;
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
}

Output:
Enter the a, b values: 2 3
Before swapping a, b values are 2, 3
After swapping a, b values are 2 3

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 141


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

16. Write a C program to implement call by refers

#include<stdio.h>
main()
{
int a=10,b=20,c;
clrscr();
c=add(&a,&b);
printf("%d",c);
getch();
}
add(int *x,int *y)
{
int z;
z=*x+*y;
return(z);
}

Output:

30

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 142


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

17. Write a C Program for pointer to pointer

#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 143


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

18. Write a C Programs on Unions, typedef and enum.

i. Program to display Student details using union

#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}

Output:

Union record1 values example


Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 144


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
ii. Program on union

#include <stdio.h>
union test1 {
int x;
int y;
} Test1;

union test2 {
int x;
char y;
} Test2;

union test3 {
int arr[10];
char y;
} Test3;

int main()
{
printf("sizeof(test1) = %lu, sizeof(test2) = %lu, "
"sizeof(test3) = %lu",
sizeof(Test1),
sizeof(Test2), sizeof(Test3));
return 0;
}

Output:
sizeof(test1)=4, sizeof(test2)=4, sizeof(test3)=40

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 145


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

19. Write a C Program to display book details using typedef function

#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;

int main( )
{
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}

Output:
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 146


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

20. Write a C Simple Program of structure in C with the use of typedef

Program:
#include<stdio.h>
#include<string.h>
typedef struct professor
{
char p_name[50];
int p_sal;
} prof;

void main(void)
{
prof pf;
printf("\n Enter Professor details: \n");
printf("\n Enter Professor name:\t");
scanf("%s", pf.p_name);
printf("\n Enter professor salary: \t");
scanf("%d", &pf.p_sal);
printf("\n Professor name is:\t");
printf("%s", pf.p_name);
printf("\n professor salary is: \t");
printf("%d", pf.p_sal);
}

Output:
Enter Professor Details:
Enter Professor name: knr
Enter professor salary:40000
Professor name is: knr
professor salary is : 40000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 147


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

21. Write a C Program to demonstrate working of enum in C

#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

Output:

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 148


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 7:

22. Write a C Program for enumerated data types with initialization.

#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5 wednesday, thursday = 10, friday, saturday};

int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday,
friday, saturday);
return 0;
}

Output:
1 2 5 6 10 11 12

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 149


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 8:

 Programs on Functions. (4 programs)


 Programs using Recursion.

Different aspects of function calling

I. function without arguments and without return value


II. function without arguments and with return value
III. function with arguments and without return value
IV. function with arguments and with return value

Example1: for Function without argument and without return value

#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("C Program");
}

Output:

Hello C Program

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 150


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Example 2: Write a C program to calculate the sum of two numbers for Function
without argument and without return value

#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}

output:

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 151


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
function without arguments and with return value:

1. Write a C program for Function without argument and with return value

Example1:

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}

output:
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 152


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Example2: Write a Cprogram to calculate the area of the square function without
arguments and with return value

#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}

Output:
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 153


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Function with argument and without return value:

Example1: Write a C program to calculate the sum of two numbers Function with
argument and without return value.

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 154


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Example2: Write a C program to calculate the average of five numbers function with
argument and without return value

#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers: 30.000000

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 155


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Function with argument and with return value:

1. Write a C program to calculate sum of two numbers function with argument and
with return value

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 156


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Example 2: Write a C program to check whether a number is even or odd function with
argument and with return value

#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 157


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 8:

Recursion:

1. Write a C program Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
OUTPUT:
Enter a positive integer:3
sum = 6

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 158


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 8:

2. Write a C program the factorial of a given number using a recursive function

#include <stdio.h>
unsigned long long int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}

OUTPUT:

Factorial of 12 is 479001600

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 159


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 8:

3. Write a C program the Fibonacci series for a given number using a recursive
function.

#include <stdio.h>

int fibonacci(int i)
{

if(i == 0)
{
return 0;
}

if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

int main()
{

int i;

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


{
printf("%d\t\n", fibonacci(i));
}

return 0;
}

OUTPUT:
When the above code is compiled and executed, it produces the following result −

0
1
1
2
3
5
8
13
21
34

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 160


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 8:

4. Write a program in C to find GCD of two numbers using recursion.

#include<stdio.h>

int findGCD(int num1,int num2);


int main()
{
int num1,num2,gcd;
printf("\n\n Recursion : Find GCD of two numbers :\n");
printf("------------------------------------------\n");
printf(" Input 1st number: ");
scanf("%d",&num1);
printf(" Input 2nd number: ");
scanf("%d",&num2);

gcd = findGCD(num1,num2);
printf("\n The GCD of %d and %d is: %d\n\n",num1,num2,gcd);
return 0;
}

int findGCD(int a,int b)


{
while(a!=b)
{
if(a>b)
return findGCD(a-b,b);
else
return findGCD(a,b-a);
}
return a;
}

Output:
Recursion : Find GCD of two numbers :
------------------------------------------
Input 1st number: 10
Input 2nd number: 50

The GCD of 10 and 50 is: 10

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 161


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 9:

 Programs on Dynamic Memory Allocation Functions (3 programs).

1. Write C program to create memory for int, char and float variable at run time.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iVar;
char *cVar;
float *fVar;

/*allocating memory dynamically*/


iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));
printf("Enter integer value: ");
scanf("%d",iVar);
printf("Enter character value: ");
scanf(" %c",cVar);
printf("Enter float value: ");
scanf("%f",fVar);
printf("Inputted value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar);

/*free allocated memory*/


free(iVar);
free(cVar);
free(fVar);
return 0;
}

Output:

Enter integer value:5


Enter character value:c
Enter float value:5.8
Inputted value are 5,c,5.8

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 162


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 9:

2. Write a C Program for sum of array element using malloc function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

Out put:

Enter number of elements:5


Enter elements:
1
3
2
3
5
Sum =14

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 163


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 9:

3. Write a C Program for smallest number in an array using calloc function

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int *element;
printf("Enter total number of elements: ");
scanf("%d", &n);
/* returns a void pointer(which is type-casted to int*)
pointing to the first block of the allocated space */
element = (int*) calloc(n,sizeof(int));
/* If it fails to allocate enough space as specified,
it returns a NULL pointer.*/
if(element == NULL)
{
printf("Error.Not enough space available");
exit(0);
}
for(i = 0; i < n; i++)
{
/*
storing elements from the user
in the allocated space
*/
scanf("%d", element+i);
}
for(i = 1; i < n; i++)
{
if(*element > *(element+i))
{
*element = *(element+i);
}
}
printf("Smallest element is %d", *element);
return 0;
}

Out put:
Enter total number of elements:
5
21
5
6
3
8
20
Smallest element is 3

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 164


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 9:

4. Write a C example program for realloc

Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i;
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
return 0;
}

Out put:

10 20 30

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 165


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 10:

 Programs on File Input and Output functions (3 programs).


 Programs on File Operations. (5 programs)

1. Write a C Program to write data file and read data from file

#include<stdio.h>
main()
{
charch;
FILE *f2;
f2=fopen("data.dat","w");
while((ch=getchar())!=EOF)
putc(ch,f2);
fclose(f2);
f2=fopen("data.dat","r");
while((ch=getc(f2))!=EOF)
putchar(ch);
fclose(f2);
}

Output:

This is the file program

This is the file program

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 166


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 10:

2. Write a C program to write integer data into file and read it from file.

#include<stdio.h>
main()
{
int num;
FILE *f2;
f2=fopen("data.int","w");
scanf("%d",&num);
putw(num,f2);
fclose(f2);
f2=fopen("data.int","r");
num=getw(f2);
printf("%d",num);
fclose(f2);
}

Output:
12
12

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 167


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 10:

3. Write a C Program to copy one file contents to another

#include <stdio.h>
#include <process.h>
void main(int argc, char *argv[])
{
FILE *fs,*ft;
char ch;
if(argc!=3)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL) // check the condition if the file pointer is NULL or not
{
puts("Target file cannot be opened.");
fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF) // check the condition if the file is end or not
break;
else
fputc(ch,ft);
}
fclose(fs); fclose(ft);
getch();
}
Output:
source.c
this is source text
ouput.c
Command line arguments
source.c ouput.c
source.c
this is source text
ouput.c
this is source text
Command line arguments
source.c
Invalid number of arguments.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 168


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 10:

4. Write a C Program to reverse the first n characters in a file.

#include <stdio.h>
#include <string.h>
#include <process.h>
void main(int argc, char *argv[])
{
char a[15];
char s[20];
char n;
int k,j=0,i,len;
FILE *fp;
if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}
k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='\0';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='\0';
getch();
}
Output:
source.c
this is source
ouput.c
Command line arguments
source.c ouput.c
source.c
this is source
ecruos si siht
Command line arguments
source.c
Invalid number of arguments.

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 169


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.
Week 10:

5. Write a C program to write product details.

#include<stdio.h>
main()
{
char c[20];
int p,q,b;
FILE *f2;
f2=fopen("data.dat","w");
printf("enter item name,price, quantity");
scanf("%s%d%d",&c,&p,&q);
b=p*q;
printf("%s%d%d%d",c,p,q,b);
fclose(f2);
}

Output:
Enter item name, price, quantity
Rice 25 1
Rice 25 1 25

Week 11
Revision

VIDYA JYOTHI INSTITUTE OF TECHNOLOGY (An Autonomous Institution) 170


Aziz Nagar Gate, C.B. Post, Hyderabad - 500 075, Telangana.

You might also like