Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PPS File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Department of Applied Science & Engineering

SUBJECT: Programming for Problem Solving (ESC103)

B. Tech. 1st Year

2018-19

V.K. Sinha, Rubaljeet Kaur , Meenakshi , Nisha Kumari

Chandigarh Engineering College


Landran, Mohali-140307
Index
Sr. Practical Name Date Page Signature
No No
1 Familiarization with programming environment.

2 WAP to print text on the screen.


3 WAP to perform arithmetic operation
4 WAP to swap two numbers with the help of third variable
and without using of third variable
5 WAP to find the entered number is even or odd
6 WAP to find the largest among three numbers.

7 WAP to find the roots of quadratic equation.


8 WAP to find whether the entered character is upper case ,
lower case , digit or special symbol.

9 WAP to find the sum of a series 1n+2n+3n+……+mn

10 WAP to find factorial of given number by using while loop.


11 WAP to check whether the entered number is palindrome or
not by using do-while.

12 WAP to perform arithmetic operation on 1-D Array.


13 WAP to perform arithmetic operation on 2-D Array.
14 WAP to perform string manipulation function.
15 WAP to search an element using linear or binary search.
16 WAP to sort list of elements using Bubble sort.
17 WAP to sort list of elements using Insertion sort.
18 WAP to sort list of elements using Selection sort.
19 WAP to swap two numbers using call by value and call by
reference.
20 WAP to find Fibonacci series using recursion.
21 WAP to sort list of elements using Quick sort.
22 WAP to sort list of elements using Merge sort.
23 WAP to perform Array of Structure.
24 WAP to implement pointers.
25 WAP to perform file handling.
Practical Beyond Syllabus
1 Conversion of C program into C++ program
2 Introduction to Code Block IDE
3 Introduction to Dev C IDE
4
Find the largest of 2 no. using condition operator

5
To demonstrate the importance of ampersand(&)operator in
scanf

Course code ESC103


Category Engineering Science Course
Course title Programming for Problem Solving (Theory & Lab.)

Scheme and L T P Credits Semester – II


Credits 3 0 4 5 [The lab component should
have one hour of tutorial
followed or preceded by
laboratory assignments.]
Pre-requisites (if -
any)

Course Outcomes
The student will learn
• To formulate simple algorithms for arithmetic and logical problems.
• To translate the algorithms to programs (in C language).
• To test and execute the programs and correct syntax and logical errors.
• To implement conditional branching, iteration and recursion.
• To decompose a problem into functions and synthesize a complete
program using divide and conquer approach.
• To use arrays, pointers and structures to formulate algorithms and
programs. To apply programming to solve matrix addition and multiplication
problems and searching and sorting problems.
• To apply programming to solve simple numerical method problems,
namely rot finding of function, differentiation of function and simple
integration.

Laboratory Outcomes
• To formulate the algorithms for simple problems
• To translate given algorithms to a working and correct program
• To be able to correct syntax errors as reported by the compilers
• To be able to identify and correct logical errors encountered at run time
• To be able to write iterative as well as recursive programs
• To be able to represent data in arrays, strings and structures and manipulate them
through a program To be able to declare pointers of different types and use them
in defining selfreferential structures.
• To be able to create, read and write to and from simple text files.

(ii)Laboratory - Programming for Problem Solving[ L : 0; T:0 ; P : 4 (2credits)]


[The laboratory should be preceded or followed by a tutorial to explain
the approach or algorithm to be implemented for the problem given.]

Tutorial 1: Problem solving using computers:


Lab1: Familiarization with programming environment

Tutorial 2: Variable types and type conversions:


Lab 2: Simple computational problems using arithmetic expressions

Tutorial 3: Branching and logical expressions:


Lab 3: Problems involving if-then-else structures

Tutorial 4: Loops, while and for loops:


Lab 4: Iterative problems e.g., sum of series

Tutorial 5: 1D Arrays: searching,


sorting: Lab 5: 1D Array manipulation

Tutorial 6: 2D arrays and Strings


Lab 6: Matrix problems, String operations

Tutorial 7: Functions, call by


value: Lab 7: Simple functions
Tutorial 8 &9: Numerical methods (Root finding, numerical differentiation, numerical
integration):
Lab 8 and 9: Programming for solving Numerical methods problems

Tutorial 10: Recursion, structure of recursive


calls Lab 10: Recursive functions

Tutorial 11: Pointers, structures and dynamic memory


allocation Lab 11: Pointers and structures

Tutorial 12: File handling:


Lab 12: File operations
Practical 1: Familiarization with programming environment

C is a general-purpose, imperative computer programming language,


supporting structured programming, lexical variable scope and recursion. By design, C
provides constructs that map efficiently to typical machine instructions, and therefore it
has found lasting use in applications that had formerly been coded in assembly language,
including operating systems, as well as various application software for computers
ranging from supercomputers to embedded systems.
C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs, and
used to re-implement the Unix operating system. It has since become one of the most
widely used programming languages of all time, with C compilers from various vendors
available for the majority of existing computer architectures and operating systems. C has
been standardized by the American National Standards Institute (ANSI) since 1989
(see ANSI C) and subsequently by the International Organization for
Standardization (ISO).
C is an imperative procedural language. It was designed to be compiled using a relatively
straightforward compiler, to provide low-level access to memory, to provide language
constructs that map efficiently to machine instructions, and to require minimal run-time
support. Despite its low-level capabilities, the language was designed to encourage cross-
platform programming. A standards-compliant and portably written C program can be
compiled for a very wide variety of computer platforms and operating systems with few
changes to its source code. The language has become available on a very wide range of
platforms, from embedded microcontrollers to supercomputers.

IDE: An integrated development environment (IDE) is a software application that


provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of a source code editor, build
automation tools, and a debugger.

Compiler: A compiler is a software program that compiles program source code files into
an executable program. It is included as part of the integrated development environment
IDE with most programming software packages.
The compiler takes source code files that are written in a high-level language, such as C,
BASIC, or Java, and compiles the code into a low-level language, such as machine code
or assembly code. This code is created for a specific processor type, such as and Intel
Pentium or PowerPC. The program can then be recognized by the processor and run from
the operating system.

C++ built-in Header Files


alloc.h dos.h limits.h share.h sys\stat.h
assert.h errno.h locale.h signal.h sys\timeb.h
bcd.h fcntl.h malloc.h stdarg.h sys\types.h
bios.h float.h math.h stddef.h time.h
complex.h fstream.h mem.h stdio.h utime.h
conio.h generic.h memory.h stdiostr.h values.h
ctype.h graphics.h new.h stream.h varargs.h
dir.h io.h process.h string.h sys\stat.h
direct.h iomanip.h search.h strstrea.h sys\timeb.h
dirent.h iostream.h setjmp.h sys\locking.h sys\types.h

List of best and free C/C++ compilers and IDEs for Programmers

Eclipse Dev C++ GCC CC65


NetBeans CodeLite Xcode LCC
Code::Blocks MinGW Tiny C – Compiler SDCC
Digital Mars: Ultimate++ Portable C Compiler nesC
C Free Mirosoft Visual Failsafe C CC386
Studio Express
Sky IDE Open Watcom Pelles C SubC
Turbo C++ TurboC3
TC
Turbo C++ Keyboard Shortcuts

Shortcuts Shortcuts Shortcuts


Action Action Action
keys keys keys

For
F1 Alt+X Quit Ctrl+F9 Run
Help

F2 Save Alt+Bksp Undo Ctrl+F2 Program reset

F3 Open Shift+Alt+Bksp Redo Alt+F9 Compile


Go to
F4 Shift+Del Cut Alt+F4 Inspect
cursor

F5 Zoom Ctrl+Ins Copy Ctrl+F4 Evaluate/Modify

F6 Next Shift+Ins Paste Ctrl+F3 Call stack

Trace Toggle
F7 Ctrl+Del Clear Ctrl+F8
into breakpoint

Step Search
F8 Ctrl+L Ctrl+F5 Size/Move
over again
Previous
F9 Make Alt+F7 Alt+F3 Close
error
Next
F10 Menu Alt+F8 Alt+F5 User screen
error

Alt+0 List all Shift+F1 Index Ctrl+F7 Add watchb

Topic Previous
Ctrl+F1 Alt+F1
search topic

Data Types available in C++:

1. Primary(Built-in) Data Types:


o character
o integer
o floating point
o boolean
o double floating point
o void
o wide character
2. User Defined Data Types:
o Structure
o Union
o Class
o Enumeration
3. Derived Data Types:
o Array
o Function
o Pointer
o Reference
The lists of modifiers used in C++ are:

 signed
 unsigned
 long
 short

Data Type Description Size Typical Range


(Keywords)

char Any single character. It 1 byte -128 to 127 or 0 to 255


may include a letter, a
digit, a punctuation
mark, or a space.

signed char Signed character. 1 byte -128 to 127

unsigned char Unsigned character. 1 byte 0 to 255

wchar_t Wide character. 2 or 4 bytes 1 wide character


Data Type Description Size Typical Range
(Keywords)

int Integer. 4 bytes -2147483648 to 2147483647

signed int Signed integer. Values 4 bytes -2147483648 to 2147483647


may be negative, positive,
or zero.

unsigned int Unsigned integer. Values 4 bytes 0 to 4294967295


are always positive or
zero. Never negative.

short Short integer. 2 bytes -32768 to 32767

signed short Signed short integer. 2 bytes -32768 to 32767


Values may be negative,
positive, or zero.

unsigned short Unsigned short integer. 2 bytes 0 to 65535


Values are always
positive or zero. Never
negative.

long Long integer. 4 bytes -2147483648 to 2147483647

signed long Signed long integer. 4 bytes -2147483648 to 2147483647


Values may be negative,
positive, or zero.

unsigned long Unsigned long integer. 4 bytes 0 to 4294967295


Values are always
positive or zero. Never
negative.
Floating-point Data Types
Data Type Description Size Typical Range
(Keywords)

float Floating point number. 4 bytes +/- 3.4e +/- 38 (~7 digits)
There is no fixed number of
digits before or after the
decimal point.

double Double precision floating 8 bytes +/- 1.7e +/- 308 (~15
point number. More digits)
accurate compared to float.

long double Long double precision 8 bytes +/- 1.7e +/- 308 (~15
floating point number. digits)

Boolean Data Type


Data Type Description Size Typical Range
(Keywords)

bool Boolean value. It can only take one 1 byte true or false
of two values: true or false.

C Keywords
asm else new this
auto enum operator throw
bool explicit private TRUE
break export protected try
case extern public typedef
catch FALSE register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

In addition,
the following
words are
also
reserved:

And bitor not_eq xor


and_eq compl or xor_eq
bitand not or_eq

Functions Descriptions
abort stops the program
abs absolute value
acos arc cosine
asctime a textual version of the time
asin arc sine
assert stops the program if an expression isn't true
atan arc tangent
atan2 arc tangent, using signs to determine quadrants
sets a function to be called when the program
atexit
exits
atof converts a string to a double
atoi converts a string to an integer
atol converts a string to a long
bsearch perform a binary search
allocates and clears a two-dimensional chunk of
calloc
memory
ceil the smallest integer not less than a certain value
clearerr clears errors
returns the amount of time that the program has
clock
been running
cos cosine
cosh hyperbolic cosine
returns a specifically formatted version of the
ctime
time
difftime the difference between two times
div returns the quotient and remainder of a division
exit stop the program
exp returns "e" raised to a given power
fabs absolute value for floating-point numbers
fclose close a file
feof true if at the end-of-file
ferror checks for a file error
fflush writes the contents of the output buffer
fgetc get a character from a stream
fgetpos get the file position indicator
fgets get a string of characters from a stream
returns the largest integer not greater than a
floor
given value
fmod returns the remainder of a division
fopen open a file
fprintf print formatted output to a file
fputc write a character to a file
fputs write a string to a file
fread read from a file
returns previously allocated memory to the
free
operating system
freopen open an existing stream with a different name
frexp decomposes a number into scientific notation
fscanf read formatted input from a file
fseek move to a specific location in a file
fsetpos move to a specific location in a file
ftell returns the current file position indicator
fwrite write to a file
getc read a character from a file
getchar read a character from STDIN
getenv get environment information about a variable
gets read a string from STDIN
returns a pointer to the current Greenwich Mean
gmtime
Time
isalnum true if a character is alphanumeric
isalpha true if a character is alphabetic
iscntrl true if a character is a control character
isdigit true if a character is a digit
isgraph true if a character is a graphical character
islower true if a character is lowercase
isprint true if a character is a printing character
ispunct true if a character is punctuation
isspace true if a character is a space character
isupper true if a character is an uppercase character
itoa Convert a integer to a string
isxdigit true if a character is a hexadecimal character
labs absolute value for long integers
ldexp computes a number in scientific notation
returns the quotient and remainder of a division,
ldiv
in long integer form
localtime returns a pointer to the current time
log natural logarithm
log10 natural logarithm, in base 10
longjmp start execution at a certain point in the program
malloc allocates memory
searches an array for the first occurrence of a
memchr
character
memcmp compares two buffers
memcpy copies one buffer to another
memmove moves one buffer to another
memset fills a buffer with a character
mktime returns the calendar version of a given time
decomposes a number into integer and fractional
modf
parts
displays a string version of the current error to
perror
STDERR
pow returns a given number raised to another number
printf write formatted output to STDOUT
putc write a character to a stream
putchar write a character to STDOUT
puts write a string to STDOUT
qsort perform a quicksort
raise send a signal to the program
rand returns a pseudo-random number
realloc changes the size of previously allocated memory
remove erase a file
rename rename a file
move the file position indicator to the beginning
rewind
of a file
scanf read formatted input from STDIN
setbuf set the buffer for a specific stream
setjmp set execution to start at a certain point
setlocale sets the current locale
setvbuf set the buffer and size for a specific stream
signal register a function as a signal handler
sin sine
sinh hyperbolic sine
sprintf write formatted output to a buffer
sqrt square root
srand initialize the random number generator
sscanf read formatted input from a buffer
strcat concatenates two strings
finds the first occurrence of a character in a
strchr
string
strcmp compares two strings
compares two strings in accordance to the
strcoll
current locale
strcpy copies one string to another
strcspn searches one string for any characters in another
strerror returns a text version of a given error code
strftime returns individual elements of the date and time
strlen returns the length of a given string
concatenates a certain amount of characters of
strncat
two strings
compares a certain amount of characters of two
strncmp
strings
copies a certain amount of characters from one
strncpy
string to another
finds the first location of any character in one
strpbrk
string, in another string
finds the last occurrence of a character in a
strrchr
string
returns the length of a substring of characters of
strspn
a string
finds the first occurrence of a substring of
strstr
characters
strtod converts a string to a double
strtok finds the next token in a string
strtol converts a string to a long
strtoul converts a string to an unsigned long
converts a substring so that it can be used by
strxfrm
string comparison functions
system perform a system call
tan tangent
tanh hyperbolic tangent
time returns the current calendar time of the system
tmpfile return a pointer to a temporary file
tmpnam return a unique filename
tolower converts a character to lowercase
toupper converts a character to uppercase
ungetc puts a character back into a stream
va_arg use variable length parameter lists
write formatted output with variable argument
vprintf, vfprintf, and vsprintf
lists
vscanf, vfscanf, and vsscanf read formatted input with variable argument lists

Practical 2: WAP to print text on the screen.


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Welcome to C Language\n\n");
printf("I hope you will enjoy");
getch();
}

Output:

Practical 3: WAP to perform arithmetic operation

#include <stdio.h>

int main()
{
int first, second, add, subtract, multiply;
float divide;

printf("Enter two integers\n");


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

add = first + second;


subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting

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


printf("Difference = %d\n", subtract);
printf("Multiplication = %d\n", multiply);
printf("Division = %.2f\n", divide);

return 0;
}

Output :

Practical 4: WAP to swap two numbers with the help of third variable and without using
of third variable

//with the help of third variable


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter the value of A & B:\t");
scanf("%d%d",&a,&b);
c=a;
a=b;
b=c;
printf("The value after swap is:\t%d\n%d",a,b);
getch();
}

Output

//Swapping of 2 numbers without using of third variable


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the value of A & B:\t");
scanf("%d%d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("The value after swap is:\t%d\n%d",a,b);
getch();
}

Output
Practical 5: WAP to find the entered number is even or odd
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the value of A ");
scanf("%d",&a);
if(a%2==0)
printf("The no. is even");
else
printf("the no. is odd");
getch();
}

Output
Practical 6: WAP to find the largest among three numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter the no.s");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("a is big");
else
printf("c is big");
}
else if(b>c)
printf("b is big");
else
printf("c is big");
getch();
}

Output

Practical 7: WAP to find the roots of quadratic equation.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,r,r1,r2,d;
clrscr();
printf("\nEnter the co-efficients\n");
scanf("%f%f%f",&a,&b,&c);
d=(b*b)-(4*a*c);
printf("\nThe value of D is %f",d);
if(d<0)
printf("\nThe root are not real");
if(d>0)
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("\nThe root one is %f",r1);
printf("\nThe root two is %f",r2);
}
if(d==0)
{
r=-b/(2*a);
printf("\nThe roots are equal\n");
printf("Root1=Root2=%f\n",r);
}
getch();
}

Output
Practical 8: WAP to find whether the entered character is upper case , lower case , digit
or special symbol.

Characters ASCII VAlues


A-Z 65-90
a-z 97-122
0-9 48-57
Special symbols 0-47, 58-64, 91-96, 123-127

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character:");
scanf("%c",&ch);
if(ch>=65 && ch<=90)
{
printf("\n Upper case letter");
}
else if(ch>=97 && ch<=122)
{
printf("\n Lower case letter");
}
else if(ch>=48 && ch<=57)
{
printf("\n Digit");
}
else if((ch>=0 && ch<=47) || (ch>=58&& ch<=64) || (ch>=91 && ch<=96) || (ch>=123
&& ch<=127))
{
printf("\n Special symbol");
}
getch();
}

Output1:

Enter a Character: H
Upper case letter

Output2:

Enter a Character: g
Lower case letter

Output3:

Enter a Character: 8
Digit

Output4:

Enter a Character: @
Special symbol

Practical 9: WAP to find the sum of a series 1n+2n+3n+……+mn

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,m,sum=0,i=1,term;
clrscr();
printf("Enter the power of series ");
scanf("%d",&n);
printf("Enter the last no. of series ");
scanf("%d",&m);
while(i<=m)
{
term=pow(i,n);
sum=sum+term;
i++;
}
printf("The sum of term is %d",sum);
getch();
}

Output

Practical 10: WAP to find factorial of given number by using while loop.

#include<stdio.h>
#include <conio.h>
void main()
{
int n,f=1,i=1;
printf("Enter a number: ");
scanf("%d",&n);

while(i<=n)
{
f = f * i;
i++;
}
printf("factorial= %d",f);
getch();

Practical 11: WAP to check whether the entered number is palindrome or not by using
do-while.

#include<stdio.h>
#include<conio.h>
int palindrome(int num);
int rev=0,rem=0;
void main()
{
int num;
printf("\n Enter a number: ");
scanf("%d",&num);
if(num==palindrome(num))
{
printf("\n %d is palindrome",num);
}
else
{
printf("\n %d is not palindrome",num);
}
getch();
}
int palindrome(int num)
{
do
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}while(num>0);
return rev;
}

Output:
Practical 12: WAP to perform arithmetic operation on 1-D Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[11],b,i;
float sum=0,avg;
clrscr();
printf("Enter the value of i(1 to 11) ");
scanf("%d",&i);
for(b=1;b<=i;b++)
{ printf("Enter the values ");
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum of the values is %f\n",sum);
avg=sum/i;
printf("The average of the values is %f",avg);
getch();
}

Output
Practical 13: WAP to perform arithmetic operation on 2-D Array.
// Matrix Multiplication
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3]={0,0,0,0,0,0,0,0,0},i,j,k;
clrscr();
printf("Enter the value of first matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the value of second matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
c[i][j]=a[i][k]*b[k][j]+c[i][j];
}
}
}
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
{
printf("%d",c[i][j]);
printf("\t");
}
}
getch();
}

Output
Practical 14: WAP to perform string manipulation function.

Function What It Does

strcmp() Compares two strings in a case-sensitive way. If the strings

match, the function returns 0.

strncmp() Compares the first n characters of two strings, returning 0 if

the given number of characters match.

strcasecmp() Compares two strings, ignoring case differences. If the strings

match, the function returns 0.

strncasecmp() Compares a specific number of characters between two strings,

ignoring case differences. If the number of characters match, the

function returns 0.

strcat() Appends one string to another, creating a single string out of

two.

strncat() Appends a given number of characters from one string to the end

of another.

strchr() Searches for a character within a string. The function returns

that character’s position from the start of the string as a

pointer.

strrchr() Searches for a character within a string, but in reverse. The

function returns the character’s position from the end of the

string as a pointer.

strstr() Searches for one string inside another string. The function

returns a pointer to the string’s location if it’s

found.

strnstr() Searches for one string within the first n characters of the
second string. The function returns a pointer to the string’s

location if it’s found.

strcpy() Copies (duplicates) one string to another.

strncpy() Copies a specific number of characters from one string to

another.

strlen() Returns the length of a string, not counting the or NULL

character at the end of the string.

// C program for password checking using strcmp() function.

#include <stdio.h>
#include <string.h>
int main()
{
char password[]="taco";
char input[15];
int match;
printf("Password: ");
scanf("%s",input);
match=strcmp(input,password);
if(match==0)
puts("Password accepted");
else
puts("Invalid password. Alert the authorities.");
return(0);
}

Practical 15: WAP to search an element using linear or binary search.


// Linear Search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[11],b,c;
clrscr();
printf("Enter an array ");
for(b=0;b<11;b++)
{
scanf("%d",&a[b]);
}
printf("\nWhich value you want to search");
scanf("%d",&c);
for(b=0;b<11;b++)
{
if(a[b]==c)
{
printf("\nLocation of that value is %d",b+1);
break;
}
}
if(b==11)
printf("\nValue not found in array");
getch();
}

Output
Program 16: WAP to sort list of elements using Bubble sort.

/* Bubble sort code */

#include <stdio.h>

int main()

int array[100], n, c, d, swap;

printf("Enter number of elements\n");

scanf("%d", &n);

printf("Enter %d integers\n", n);

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

scanf("%d", &array[c]);

for (c = 0 ; c < n - 1; c++)

for (d = 0 ; d < n - c - 1; d++)

if (array[d] > array[d+1]) /* For decreasing order use < */

swap = array[d];

array[d] = array[d+1];

array[d+1] = swap;

printf("Sorted list in ascending order:\n");


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

printf("%d\n", array[c]);

return 0;

Output of program:

Program 17: WAP to sort list of elements using Insertion sort.

All Stream I /* Insertion sort ascending order */

#include <stdio.h>

int main()
{
int n, array[1000], c, d, t;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

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


scanf("%d", &array[c]);
}

for (c = 1 ; c <= n - 1; c++) {


d = c;

while ( d > 0 && array[d-1] > array[d]) {


t = array[d];
array[d] = array[d-1];
array[d-1] = t;

d--;
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c <= n - 1; c++) {


printf("%d\n", array[c]);
}

return 0;
}

Output of program:

Program 18: WAP to sort list of elements using Selection sort.


#include <stdio.h>

int main()
{
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);

printf("Enter %d integers\n", n);

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


scanf("%d", &array[c]);

for ( c = 0 ; c < ( n - 1 ) ; c++ )


{
position = c;

for ( d = c + 1 ; d < n ; d++ )


{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}

printf("Sorted list in ascending order:\n");

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


printf("%d\n", array[c]);

return 0;
}

Output of program:
Practical 19: WAP to swap two numbers using call by value and call by reference.
//Call by Value
#include<stdio.h>
#include<conio.h>
void swap(int i,int j)
{
int temp=i;i=j;j=temp;
}
void main()
{
int a,b;
clrscr();
printf("enter the value ");
scanf("%d%d",&a,&b);
swap(a,b);
printf("The value after swap is %d\n%d",a,b);
getch();
}

Output
//Call by Reference
#include<stdio.h>
#include<conio.h>
void swap(int *i,int *j)
{
int temp=(*i);(*i)=(*j);(*j)=temp;
}
void main()
{
int a,b;
clrscr();
printf("enter the value ");
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("The value after swap %d\n%d",a,b);
getch();
}

Output
Practical 20: WAP to find Fibonacci series using recursion.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=0,b=1,c,i,n;
clrscr();
printf("Enter the value of N element ");
scanf("%d",&n);
if(n==0)
printf("%d\n",a);
else
printf("%d\t%d\t",a,b);
for(i=2;i<=n;i++)
{
c=a+b;
printf("%d\t",c);
a=b;
b=c;
}
getch();
}

Output
Program 21: WAP to sort list of elements using Quick sort.

#include<stdio.h>

void quicksort(int number[25],int first,int last)

int i, j, pivot, temp;

if(first<last){

pivot=first;

i=first;

j=last;

while(i<j)

while(number[i]<=number[pivot]&&i<last)

i++;

while(number[j]>number[pivot])

j--;

if(i<j){

temp=number[i];

number[i]=number[j];

number[j]=temp;

}
temp=number[pivot];

number[pivot]=number[j];

number[j]=temp;

quicksort(number,first,j-1);

quicksort(number,j+1,last);

int main(){

int i, count, number[25];

printf("How many elements are u going to enter?: ");

scanf("%d",&count);

printf("Enter %d elements: ", count);

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

scanf("%d",&number[i]);

quicksort(number,0,count-1);

printf("Order of Sorted elements: ");

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

printf(" %d",number[i]);
return 0;

}
Output of program :

Program 22: WAP to sort list of elements using Merge sort.

#include<stdio.h>

void mergesort(int a[],int i,int j);


void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");

for(i=0;i<n;i++)
scanf("%d",&a[i]);

mergesort(a,0,n-1);

printf("\nSorted array is :");


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

return 0;
}

void mergesort(int a[],int i,int j)


{
int mid;

if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}

void merge(int a[],int i1,int j1,int i2,int j2)


{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;

while(i<=j1 && j<=j2) //while elements in both lists


{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}

while(i<=j1) //copy remaining elements of the first list


temp[k++]=a[i++];

while(j<=j2) //copy remaining elements of the second list


temp[k++]=a[j++];

//Transfer elements from temp[] back to a[]


for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

Output of program :
Practical 23: WAP to perform Array of Structure.
#include<stdio.h>
#include<conio.h>
struct student
{
long rollno;
char name[20];
float fee;
}s1;
void main()
{
clrscr();
printf("Enter Roll no: ");
scanf("%d",&s1.rollno);
printf("Enter student name: ");
scanf("%s",s1.name);
printf("Enter fee: ");
scanf("%f",&s1.fee);
printf("\nDetails are:\n\n");
printf("Roll no: %ld\nName: %s\nFee: %5.2f",s1.rollno,s1.name,s1.fee);
getch();
}
Output

Practical 24: WAP to implement pointers.


#include<stdio.h>
#include<conio.h>
void main()
{
int *p;
clrscr();
printf("The size of *p is %d",sizeof(p));
getch();
}

Output
Practical 24: WAP to implement pointers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3]={0,0,0,0,0,0,0,0,0},i,j,k;
int *p=a,*p1=b;
clrscr();
printf("Enter the value of first matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the value of second matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}printf("The sum is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

c[i][j]=(*p)+(*p1);
printf("%d ",c[i][j]);
p++;
p1++;
}
printf("\n");
}
getch();
}

Output
Practical 25: WAP to perform file handling.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f;
clrscr();
f=fopen("Test.txt","w");
if(f==NULL)
{
printf("\n Sorry,File cannot be opened");
printf("\n Program Terminating...");
}
else
{
printf("\n File Opened");
fprintf(f,"%s","Test Successful !");
printf("\n Operation complete,closing the file.");
fclose(f);
}
getch();
}

Output

Practical 25: WAP to perform file handling.


#include<stdio.h>
#include<conio.h>
#define MAX 256
void main()
{
char str[MAX];
FILE *f;
clrscr();
f=fopen("test.txt","r");
while(!feof(f))
{
fgets(str,MAX,f);
printf("%s",str);
}
fclose(f);
getch();
}

Output

Practical 25: WAP to perform file handling.


#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
FILE *f=fopen("nums","wb");
clrscr();
if(f==NULL)
printf("Error in opening file");
else
{
while(num!=1)
{
printf("\nEnter a number: ");
scanf("%d",&num);
putw(num,f);
}
printf("\nFile Created!");
}
getch();
}

Output

Practical beyond Syllabus:

1. Find the largest of 2 no. using condition operator


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the value of A & B\t");
scanf("%d%d",&a,&b);
(a>b)?printf("A is greater"):printf("B is greater");
getch();
}

Output
2. To demonstrate the importance of ampersand(&)operator in scanf
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the value of A ");
scanf("%d",&a);
printf("Enter the value of B ");
scanf("%d",b);
printf("The entered value of A is %d\n",a);
printf("The entered value of B is %d",b);
getch();
}

Output
3. To demonstrate the work of %n
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("C Assigenment%n\n",&a);
/*%n is used to count the character*/
printf("Total no. of character are %d",a);
getch();
}

Output
4. Display decimal, octal & hexadecimal no.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the value");
scanf("%d",&a);
printf("The hexidecimal no. is. %x",a);
printf("\nThe octal no. is. %o",a);
printf("\nThe decimal no. is. %d",a);
getch();
}

Output

5. Check the no. is positive or negative


#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the value");
scanf("%d",&a);
if(a>0)
printf("Entered no. is positive");
else if(a<0)
printf("Entered no. is negative");
else
printf("Entered no. is zero");
getch();
}

Output

6. Given character is digit or not


#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any thing ");
scanf("%c",&ch);
if(isdigit(ch))
printf("Entered value is digit");
else
printf("Entered value is not a digit");
getch();
}

Output

7. Check the no.is divided by 5 or 7 or by both or by no one


#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the no.");
scanf("%d",&a);
if(a%5==0&&a%7==0)
printf("Entered no. is divided by 5 & 7");
else if(a%5==0)
printf("Entered no. is divided by 5");
else if(a%7==0)
printf("Entered no. is divided by 7");
else
printf("Not divided by 5 or 7");
getch();
}

Output
8. To demonstrate the working of preprocessor
#include<stdio.h>
#include<conio.h>
#define N 10
void main()
{
clrscr();
printf( "The result is %d\n",N*N);
getch();
}

Output
9. To demonstrate the use of bitfields
#include<stdio.h>
#include<conio.h>
struct
{
unsigned gender: 1;
unsigned grade: 4;
unsigned bloodgroup:3;
}s1;
void main()
{
clrscr();
printf("Size of student is %d bytes",sizeof(s1));
s1.gender=1;
s1.grade=5;
s1.bloodgroup=6;
printf("\nGener : %d\nGrade : %d\nBlood Group : %d"
,s1.gender,s1.grade,s1.bloodgroup);
printf("\nAddress of student is : %u",&s1);
getch();
}

Output

10.Demonstrate the use of mallock, callock and free function


#include<stdio.h>
#include<conio.h>
void main()
{
int *b1,*b2;
clrscr();
b1=(int*)malloc(100*sizeof(int));
b2=(int*)calloc(100,sizeof(int));
printf("\nMemory allocated to buffer 1 from location %u",b1);
printf("\nMemory allocated to buffer 2 from location %u",b2);
free(b1);
free(b2);
printf("\nNow buffer 1 points to : %u",b1);
printf("\nNow buffer 2 points to : %u",b2);
getch();
}

Output

11.To explain the use of static storage classes


#include<stdio.h>
#include<conio.h>
void change()
{
static int i;
i++;
printf("%d ",i);
}
void main()
{
clrscr();
change();
change();
change();
getch();
}

Output

12.To show different between a and &a


#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the value a ");
scanf("%d",&a);
printf("The value of a is %d",a);
printf("\nthe value of &a is %u",&a);
getch();
}

Output
13. Check the value is vowal or consonant
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character ");
scanf("%c",&ch);
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
printf("Entered character is vowal");
break;
default:
printf("Entered character is consonant");
break;
}
getch();
}

Output
14. Read N no. from user and find average
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a;
float avg,sum=0;
clrscr();
printf("Who many no's you want to enter ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the no.");
scanf("%d",&a);
sum=sum+a;
}
printf("The sum of all no's is %f\n",sum);
avg=sum/n;
printf("The average is %f",avg);
getch();
}

Output
15. Factorial of given no.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,f;
clrscr();
printf("Enter the value ");
scanf("%d",&a);
f=a-1;
while(f>1)
{
a=a*f--;
}
printf("The factorial of given no. %d",a);
getch();
}

Output
16. Convert binary no. to decimal no.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
long int num,d,p=0,r=0;
clrscr();
printf("Enter the binary no.(0 or 1) ");
scanf("%ld",&num);
while(num>0)
{
d=num%10;
num=num/10;
r=r+d*pow(2,p);
p++;
}
printf("The decimal no. is %ld",r);
getch();
}

Output
17. Convert decmal no. to binary no.
#include<stdio.h>
#include<conio.h>
void main()
{
long unsigned int num,sum=0,i=1,x;
clrscr();
printf("Enter the value ");
scanf("%ld",&num);
while(num>0)
{
x=num%2;
sum=x*i+sum;
i=i*10;
num=num/2;
}
printf("After con %ld",sum);
getch();
}

Output
18. Reverse of no.
#include<stdio.h>
#include<conio.h>
void main()
{
long int a,b;
clrscr();
printf("Enter the no. ");
scanf("%ld",&a);
while(a>0)
{
b=a%10;
a=a/10;
printf("%ld",b);
}
getch();
}

Output
19. Check the no. is amstrong or not
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,num,count=0,sum=0,x;
clrscr();
printf("Enter the value ");
scanf("%d",&num);
a=b=num;
while(num>0)
{
x=num%10;
num=num/10;
count++;
}
while(b>0)
{
c=b%10;
sum=sum+pow(c,count);
b=b/10;
}
if(a==sum)
printf("Entered no. is Amstrong");
else
printf("Entered no. is not Amstrong");
getch();
}

Output
20. To find the sum of series 1+ + +……
#include <stdio.h>
#include <conio.h>
void main ()
{
float i,n;
float sum =0;
clrscr();
printf ("enter the terms = ");
scanf ("%f",&n);
for (i=1;i<=n;i++)
{
sum += 1/i;
}
printf ("sum=%f\n",sum);
getch();
}

Output

21. To find the sum of series 1+x


#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n * factorial(n-1));
}
int main()
{
int x,i;
double S=1;
printf("Please input x : ");
scanf("%d", &x); fflush(stdin);
for(i=1; i<=x; i++)
{
S += pow(x,i)/ factorial(i);
}
printf("%lf", S);
getch();
}

Output

You might also like