Pps Core Manulal - 2022
Pps Core Manulal - 2022
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
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
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
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
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
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
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.
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
Examples:
grep 'joe' *
This command searches for all occurrences of the text string 'joe' within all files
of the current directory.
8) Command mkdir
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
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 -
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
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.
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
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
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
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
#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
#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;
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
C 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
#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
#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:
#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
Programs on operators:
#include <stdio.h>
int main()
{
int a,b,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("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
}
OUT PUT:
#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:
#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:
#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:
#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:
#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);
OUT PUT:
#include <stdio.h>
int main()
{
int a, b;
float c, d;
OUT PUT:
#include <stdio.h>
int main()
{
int a = 13, b = 15;
printf("Output = %d\n", a&b);
}
OUT PUT:
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d\n", a|b);
OUT PUT:
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite.
It is denoted by ^.
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d\n", a^b);
OUT PUT:
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
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:
#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
}
OUT PUT:
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;
OUT PUT:
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 <<.
#include<stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
int a = 5, b = 9;
OUT PUT:
#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
PROGRAM 1:
#include<stdio.h>
int main()
{
return 0;
}
OUTPUT:
#include<stdio.h>
int main()
{
// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
return 0;
}
OUTPUT:
Character Value: a
Integer Value: 9
#include<stdio.h>
int main()
{
return 0;
}
OUTPUT:
Integer Value: 97
Character Value: a
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;
if(x<y)
{
printf("Variable x is less than y\n");
}
printf("I am Not in if");
}
OUT PUT:
OUT PUT:
#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:
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:
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);
Output:
#include <stdio.h>
#include <math.h>
int main()
{
int num;
int num1;
float num2;
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:
21. Write C Program to Find the Largest Number Among Three Numbers.
/* 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);
OUT PUT:
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;
OUT PUT:
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:
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);
OUT PUT:
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:
#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
discriminant = b * b - 4 * a * c;
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;
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;
OUT PUT:
#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:
#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;
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':
default:
printf("%c is a consonant\n",ch);
break;
}
}
OUT PUT:
Example 1:
#include <stdio.h>
#include <conio.h>
OUTPUT:
Welcome
to
PPS
#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:
while(condition)
{
statement(s);
}
#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:
#include <stdio.h>
int main()
{
int n, rev = 0, remainder;
while (n != 0)
{
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10; //n=n/10;
}
OUT PUT:
#include <stdio.h>
int main()
{
int Number, Reminder, Sum=0;
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:
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;
f1=f2;
f2=f3;
n--; // n value should be decrement
}
OUT PUT:
#include <stdio.h>
int main()
{
int num, reverse_num=0, remainder,temp;
if(reverse_num==num)
{
printf("%d is a palindrome number\n",num);
}
else
{
printf("%d is not a palindrome number\n",num);
}
OUT PUT:
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:
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;
do
{
printf("%d * %d = %d \n",number,i,(number*i));
i++;
}while(i<=10);
OUT PUT:
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);
OUT PUT:
#include<stdio.h>
void main()
{
int m,n;
do
{
printf("%d\t",m);
m++;
}while(m<=n);
}
OUT PUT:
11. Write a C Program to calculate the Simple interest using do-while loop.
printf("Enter t: ");
scanf("%f", &t);
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:
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$ ./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
#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:
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);
if (count == 2)
{
printf("n is a Prime number");
}
else
{
printf("n is not a Prime number");
}
OUT PUT:
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);
if (low % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d ", 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
#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:
#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:
#include <stdio.h>
int main()
{
int num, count, sum = 0;
OUT PUT:
#include <stdio.h>
void main()
{
int num,rem,sum=0,temp;
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:
#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:
#include<stdio.h>
int main ()
{
first = second;
second = third;
return 0;
OUT PUT:
#include<stdio.h>
void main()
{
int i,n,rem,sum=0;
OUT PUT:
#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:
Programs on One Dimensional Array. (4 programs), Linear search & Bubble sort
Programs on Two Dimensional Arrays. (2 programs)
#include <stdio.h>
void main()
{
int arr[10];
int i;
printf("\n\nRead and Print elements of an array:\n");
printf("-----------------------------------------\n");
Output:
#include <stdio.h>
void main()
{
int i,n,a[100];
OUTPUT:
#include <stdio.h>
void main()
{
int a[100];
int i, n, sum=0;
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
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
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
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,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
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,k,r1,c1,r2,c2,sum=0;
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 :
----------------------------------
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
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],i,j,r,c;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}
The matrix is :
1 2
3 4
#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
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
#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
#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
#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
Programs on Strings.
Programs on Strings with and without using string built-in Functions.
#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
#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
#include<stdio.h>
#include
int main()
{
char str[30];
int len;
printf("Enter string:\n");
gets(str);
len = strlen(str);
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
#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
#include<stdio.h>
#include<string.h>
int main()
{
char str1[40], str2[40];
int d;
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.
#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
#include<stdio.h>
#include<string.h>
int main()
{
char name[40];
strrev(name);
return 0;
}
Output:
Enter youe name: pps
Reversed name is: spp
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.
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.
#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
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);
return 0;
}
#include <stdio.h>
int main()
{
char s[] = "Programming is fun";
int i;
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
#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);
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.
#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
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
#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
#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
#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
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
#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
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
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);
out put:
Details of student:
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
/* Incorrect: *ptr_a/*ptr_b;
Correct: *ptr_a / *ptr_b;
Correct: (*ptr_a)/(*ptr_b); */
#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
#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
#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
#include <stdio.h>
int main()
{
// Integer variables
int a = 20, b = 10;
// Initialization of pointers
ptr_a = &a;
ptr_b = &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
#include <stdio.h>
int main()
{
// Initializing integer variables
int a = 20, b = 10;
// Equal to
if (*ptr_a == *ptr_b)
{
printf("%d is equal to %d.", *ptr_a, *ptr_b);
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
// Initializing integer variable
int a = 30;
return 0;
}
Output:
Value of variable a = 50
/*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;
Output:
20 is the greatest.
#include <stdio.h>
int main()
{
// Initializing integer variable
int a = 34;
return 0;
}
Output:
Increment:
Before increment a = 34
After increment a = 35
Decrement:
Before decrement a = 35
After decrement a=34
#include <stdio.h>
int main()
{
// Declaring integer variable for
// storing result
int and, or, ex_or;
Output:
a AND b = 0
a OR b = 3
a Exclusive-OR b = 3
#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
#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
#include <stdio.h>
#define ROWS 4
#define COLS 3
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;
}
int main()
{
int mat1[ROWS][COLS], mat2[ROWS][COLS], res[ROWS][COLS];
return 0;
}
Output:
Enter elements in first matrix of size 3x3:
123
456
789
Output:
input
Computer
12
15000
Tv
15
6000
Radio
45
1500
Output
Computer 12 15000.00
Tv 15 6000.00
Radio 45 1500.00
#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
#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
#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
#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
#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);
Output:
#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
#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
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
#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:
#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
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("C Program");
}
Output:
Hello C Program
#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:
The sum is 34
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:
The sum is 34
#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
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:
The sum is 34
#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
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
#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
Recursion:
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
result = sum(number);
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
#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
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;
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
#include<stdio.h>
gcd = findGCD(num1,num2);
printf("\n The GCD of %d and %d is: %d\n\n",num1,num2,gcd);
return 0;
}
Output:
Recursion : Find GCD of two numbers :
------------------------------------------
Input 1st number: 10
Input 2nd number: 50
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;
Output:
#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:
#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
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
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:
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
#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.
#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.
#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