0% found this document useful (0 votes)
9 views100 pages

Computer Programming Lab Manual

The document is a lab manual for the Computer Programming course at Sree Venkateswara College of Engineering, detailing the vision and mission of the institute and department, along with program educational objectives, outcomes, and specific outcomes. It covers tools like Turbo C, GCC, and Code Blocks IDE, providing instructions for creating, editing, compiling, and executing C programs. Additionally, it includes a list of shortcut keys for Turbo C and outlines the process for writing and running simple programs.

Uploaded by

harikrishnasvcn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views100 pages

Computer Programming Lab Manual

The document is a lab manual for the Computer Programming course at Sree Venkateswara College of Engineering, detailing the vision and mission of the institute and department, along with program educational objectives, outcomes, and specific outcomes. It covers tools like Turbo C, GCC, and Code Blocks IDE, providing instructions for creating, editing, compiling, and executing C programs. Additionally, it includes a list of shortcut keys for Turbo C and outlines the process for writing and running simple programs.

Uploaded by

harikrishnasvcn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SREE VENKATESWARA

COLLEGE OF ENGINEERING
(AUTONOMOUS)
[Link], NELLORE (DIST)

AFFILIATED TO JNTU, ANANTAPUR.

COMPUTER PROGRAMMING
LAB MANUAL
(R 23 REGULATION)
I BTECH –I SEM

(COMMON TO ALL BRANCHES)

DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
NAME OF THE STUDENT

[Link]

YEAR

BRANCH
SREE VENKATESWARA COLLEGE OF ENGINEERING
(An UGC Autonomous Institution)
Accredited by NBA, NAAC with Grade ‘A’ , UGC 2(f) Recognized &ISO 9001:: 2015 Certified
(Approved by AICTE, New Delhi and Affiliated to JNTUA, Ananthapuramu)
( Polytechnic Wing, recognized by SBTET,Govt. of AP, Institution Code :: 445)
North Rajupalem, Kodavaluru(V&M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision of the Institute

 Be a best institute to originate and foster skilled engineers and create


changemaker’s for the development of nation with a phenomenal wisdom
with morals, values and societal responsibilities.

Mission of the Institute

 M1: To impart graduate with quality education and use innovative


teaching-learning process to excel in their careers.
 M2: To build an ecosystem and play a vital role in strengthening
innovative research and entrepreneurship skills among graduates.
 M3: To produce engineers with moral values and social responsibility,
and address societal needs for better nation.
SREE VENKATESWARA COLLEGE OF ENGINEERING
(An UGC Autonomous Institution)
Accredited by NBA, NAAC with Grade ‘A’ , UGC 2(f) Recognized &ISO 9001:: 2015 Certified
(Approved by AICTE, New Delhi and Affiliated to JNTUA, Ananthapuramu)
( Polytechnic Wing, recognized by SBTET,Govt. of AP, Institution Code :: 445)
North Rajupalem, Kodavaluru(V&M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision of the Department

 To produce the globally competent professionals in the field of computer


science and engineering with socio economic and ethical values.

Mission of the Department

 M1: To provide state-of-the-art computer science and engineering


facilities through innovative teaching and learning practices. 
 M2: To prepare the graduates for higher learning, emphasizing research
and entrepreneurship.
 M3: To inculcate ethical values, leadership qualities, and professional
behaviour to improve the living standards of society. 
SREE VENKATESWARA COLLEGE OF ENGINEERING
(An UGC Autonomous Institution)
Accredited by NBA, NAAC with Grade ‘A’ , UGC 2(f) Recognized &ISO 9001:: 2015 Certified
(Approved by AICTE, New Delhi and Affiliated to JNTUA, Ananthapuramu)
( Polytechnic Wing, recognized by SBTET,Govt. of AP, Institution Code :: 445)
North Rajupalem, Kodavaluru(V&M) , S.P.S.R Nellore (Dt)-524316
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Educational Objectives

PEO-1: To provide the graduates with effectively applying mathematics,


science, and engineering methodologies for analyzing, designing, and
implementing software solutions for real-world problems.

PEO-2: To become recognized professional engineers with a demonstrated


commitment to lifelong learning, continuous learning, and self-improvement to
change in computer science engineering.

PEO-3: To train the graduates to have basic interpersonal skills and a sense of
social responsibility that covers them a way to become good team members and
leaders.
SREE VENKATESWARA COLLEGE OF ENGINEERING
(An UGC Autonomous Institution)
Accredited by NBA, NAAC with Grade ‘A’ , UGC 2(f) Recognized &ISO 9001:: 2015 Certified
(Approved by AICTE, New Delhi and Affiliated to JNTUA, Ananthapuramu)
( Polytechnic Wing, recognized by SBTET,Govt. of AP, Institution Code :: 445)
North Rajupalem, Kodavaluru(V&M) , S.P.S.R Nellore (Dt)-524316
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Outcomes (PO’s)

PO_1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.
PO_2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO_3 Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO_4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO_5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
PO_6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO_7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO_8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO_9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO_10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO_11 Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO_12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
SREE VENKATESWARA COLLEGE OF ENGINEERING
(An UGC Autonomous Institution)
Accredited by NBA, NAAC with Grade ‘A’ , UGC 2(f) Recognized &ISO 9001:: 2015 Certified
(Approved by AICTE, New Delhi and Affiliated to JNTUA, Ananthapuramu)
( Polytechnic Wing, recognized by SBTET,Govt. of AP, Institution Code :: 445)
North Rajupalem, Kodavaluru(V&M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Specific Outcomes (PSO’s)

PSO-1: Domain-specific knowledge: Acquire knowledge of hardware


functionality, design, and development of software components required to
process the information.

PSO-2: Problem-solving skills: Analyze data, identify data structures, design


suitable algorithms, develop and maintain software for real-world problems.
INDEX
[Link]. Date Name of the Program Page Remarks
No.
[Link]. Date Name of the Program Page Remarks
No.
WEEK-1

Exposure towards Turbo C, gcc, Code Blocks IDE

Turbo C:

It was a software development tool for writing programs in the C language. As an IDE, it
included a source code editor, a fast compiler, a linker and an offline help file for
reference. Version 2 included a built-in debugger. Turbo C was a follow-up product to
Borland's Turbo Pascal, which had gained widespread use in educational
institutions because the Pascal language was suited for teaching programming to students.

Although Turbo C was initially developed by a different company, it shared a lot of features with Turbo
Pascal, namely, the look-and-feel of the interface and the various programming and debugging tools
included.

However, it was not as successful as Turbo Pascal because of competition from other
C products such as Microsoft C, Watcom C, Lattice C, etc. Nevertheless, Turbo C still had
the advantage in compile speed and price.

The first version was released on May 13, 1987, and it offered the first-ever edit-compile-
run environment for software development on IBM PCs. Turbo C was not originally
developed by Borland but was bought from Bob Jervis and was initially called Wizard C.
Turbo Pascal did not have pull-down menus before this time, and it was only on its fourth
version that it received a face lift to look like Turbo C.

Borland as a company no longer develops and sells these products, but Turbo C still live
son as a free download from various online repositories, although it is really an old
technology without real technical support and is no longer viable for modern software
development. Turbo C eventually evolved into Turbo C++, then into Borland C++ and,
finally, into C++ Builder.

COMPUTER PROGRAMMING LAB (23A05101P) 1


Turbo C features:

Inline assembly with full access to the C language symbolic structures and names –This
allowed programmer to write some assembly language codes right into their programs
without the need for a separate assembler. Support for all memory models -- This had to do
with the segmented memory architecture used by 16-bit processors of that era, where each
segment was limited to 64 kilobytes (Kb).The models were called tiny, small, medium,
large and huge, which determined the size of the data used by a program, as well as the
size of the program itself. For example, with the tiny model, both the data and the program
must fit within a single 64-Kb segment. In the small model, the data and the program each
used a different 64- Kb segment. So in order to create a program larger than 64 Kb or one
that manipulates data larger than 64 Kb, the medium, large and huge memory models had
to be used. In contrast, 32-bit processors used a flat memory model and did not have this
limitation. Speed or size optimization -- The compiler could be configured to produce an
executable program that was either fast or small in size, but not both. Constant folding --
This feature allowed the Turbo C compiler to evaluate constant expressions during
compile time rather than during run time.

Short cut Keys in Turbo C:


 F1 For Help
 F2 Save
 F3 Open
 F4 Go to cursor
 F5 Zoom
 F6 Next
 F7 Trace into
 F8 Step over
 F9 Make
 F10 Menu
 Alt+X Quit
 Alt+Bksp Undo
 Shift+Alt+Bksp Redo
 Shift+Del Cut
 Ctrl+Ins Copy
 Shift+Ins Paste
 Ctrl+Del Clear
 Ctrl+L Search again
 Alt+F7 Previous error
 Alt+F8 Next error
 Ctrl+F9 Run
 Ctrl+F2 Program reset
 Alt+F9 Compile
 Alt+F4 Inspect
 Ctrl+F4 Evaluate/Modify

COMPUTER PROGRAMMING LAB (23A05101P) 2


 Ctrl+F3 Call stack
 Ctrl+F8 Toggle breakpoint
 Ctrl+F5 Size/Move
 Alt+F3 Close
 Alt+F5 User screen
 Alt+0 List all
 Shift+F1 Index
 Ctrl+F1 Topic search
 Alt+F1 Previous topic
 Ctrl+F7 Add watch

GCC:

The GNU Compiler Collection (GCC) is a compiler


[Link] produced by the GNU Project
[Link] supporting various programming languages
[Link] wiki/ Programming_ language. GCC is a key component of the
GNU tool chain [Link] the standard compiler for
most projects related to GNU [Link] and Linux
[Link] org/wiki/Linux, the most notable is the Linux kernel
[Link]

The Free Software Foundation[Link]


(FSF) distributes GCC under the GNU General Public License
[Link] GCC has played
an important role in the growth of free software ([Link]
Free_software), as both a tool and an example. When it was first released in 1987, GCC
1.0 was named the GNU C Compiler since it only handled the C programming language
[Link] It was extended to compile
C++ [Link] in December of that year. Front
ends[Link] were later developed for Objective-C

Creating / Editing / Compiling and Executing C Programs in Linux:

Creating:

i. Open any Text Editor like Vi/Emacs/Gedit from terminal.


Ex: vi filename.c
ii. Enter the program in the file.
iii. Save the file: Go Last Line Mode (Esc + Shift :), type wq.

Compiling: Method 1:
$ gcc filename.c
If No syntactical errors it gives $ prompt.
If any syntactical errors are there in the program, it displays the errors.

COMPUTER PROGRAMMING LAB (23A05101P) 3


Correct the errors by opening the file using vi filename.c
$

Method 2:
$ gcc– o filename filename.c
If No syntactical errors it gives $ prompt.
If any syntactical errors are there in the program, it displays the errors.
Correct the errors by opening the file using vi filename.c
$

Executing:
For Method 1:
$ ./[Link]

For Method 2:
$ ./filename

Code Blocks IDE:

Code Blocks is an open-source, cross-platform (Windows, Linux, MacOS), and free


C/C++ IDE. It supports many compilers, such as GNU GCC (MinGW and Cygwin) and
MS Visual C++. It supports interactive debugging (via GNU GDB or MS CDB). Code
Blocks is surprisingly versatile, and in my opinion, much better than the Visual Studio
suite. The mother site of Code Blocks is [Link] ([Link] Code blocks
.org/).

Code::Blocks is a free C, C++ and Fortran IDE built to meet the most demanding needs of
its users. It is designed to be very extensible and fully configurable.

Finally, an IDE with all the features you need, having a consistent look, feel and operation
across platforms. Built around a plug in framework, Code::Blocks can be extended
with plugins. Any kind of functionality can be added by installing/coding a plugin. For
instance, compiling and debugging functionality is already provided by plugins!

COMPUTER PROGRAMMING LAB (23A05101P) 4


Writing Toy Programs (without Creating a Project):

To write toy programs (such as few-line simple programming exercises):

File⇒New⇒Empty File.

Enter (copy and paste) the following codes:

// First C++ program to say Hello #include <iostream>

using namespace std;

int main()
{
cout<< "Hello, world!" <<endl; return 0;
}

Save the file as " [Link] " in your project directory (e.g., " d:\project).

Build (Compile and Link): Select "Build" menu⇒Build (Ctrl-F9).

Run: Select "Build" menu⇒Run (Ctrl-F10).

The drawback is you cannot debug program without creating a project.

Writing Programs (under Project)

Other than the few-line toy programs, you shall create a project for each of your
application. A project contains related files such as source codes, header files, and relevant
resources. Also, under CodeBlocks, you can only debug your program under a project -
single-file program (in previous section) debugging is not supported.

[Link]⇒New⇒Project...⇒Console Application⇒Go.

[Link] "Console Application" wizard appears: Next Select "C++"⇒Next.

[Link] "Project Title", enter " HelloProject ". In "Folder to create project in", set to your

working directory, e.g., " d:\project ". Accept the default for the rest⇒Next.

A project directory " HelloProject " will be created under " d:\project ", with a
project configuration filename of " [Link] ". You could later create more
project sunder this working directory " d:\project ".

In "Compiler" field, accept the defaults of "GNU GCC Compiler"⇒ Finish.

4. Under the "Management" pane⇒Choose "Projects" tab⇒Expand the project node

COMPUTER PROGRAMMING LAB (23A05101P) 5


"HelloProject "⇒Expand "Source" node⇒Double-click " [Link] ", which is a
template program tosay "Hello, world!".

[Link] build the program, select "Build" menu⇒Build.

[Link] run the program, select "Build" menu⇒Run.

[Link] create more source file or header file under the project: File⇒New File...⇒

Select C/C++ source or C/C++ header. C++⇒Next.

In "Filename with full path"

Click the "Navigate" (...) button to navigate to the project directory and enter the
new file name. Check both the "Debug" and "Release" boxes (or "All")

Finish.

COMPUTER PROGRAMMING LAB (23A05101P) 6


AIM: To develop a c program using printf()

PROGRAM:

//W.A.C.P USING printf( )


#include <stdio.h>
int main()

{
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;

Expected Output: Hello, World!

Output:

Results:

AIM:To develop a c program using printf( ),scannf( )

PROGRAM:

//W.A.C.P using printf( ) ,scanf( )


#include<stdio.h>
int main()
{
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
Expected Output:
enter a number: 10
cube of number is: 1000
Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 7


WEEK-2

AIM:To develop a c program sum and average of 3 numbers

PROGRAM:

// W.A.C.P To find sum and average of 3 numbers .


#include <stdio.h>
int main()
{
int a, b, c, sum;
float avg;
// Asking for input
printf("Enter 3 numbers: \n");
scanf("%d %d %d", &a, &b, &c);
// Calculating sum
sum = a + b + c;
// Calculating average of 3 numbers
avg = sum / 3;
// Displaying output
printf("Sum = %d \n", sum);
printf("Average = %.2f", avg);
return 0;
}

Expected Output:

Enter 3 numbers: 10 20 30

Sum= 60

Average= 20.00

Output :

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 8


AIM:To develop a c program conversion of Fahrenheit to Celsius and vice versa.

PROGRAM:

//[Link] of Fahrenheit to Celsius and vice versa.


#include<stdio.h>
int main()

{
float fahrenheit, celsius;
//get the limit of fibonacci series
printf("Enter Fahrenheit:");
scanf("%f",&fahrenheit);
celsius = (fahrenheit - 32)*5/9;
printf("Celsius: %f", celsius);
return 0;

Expected Output:

Enter Fahrenheit: 212.01

Celsius: 100.005554

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 9


AIM:To develop a c program simple interest calculation

PROGRAM:

//W.A.C.P Simple interest calculation


# include <conio.h>
# include <stdio.h>
# include <stdlib.h>
int main()

//Simple interset program


int principal, rate, time, interest;
printf("Enter the principal: ");
scanf("%d", &principal);
printf("Enter the rate: ");
scanf("%d", &rate);
printf("Enter the time: ");
scanf("%d", &time);
interest = principal * rate * time / 100;
printf("The Simple interest is %d", interest);
return 0;

Expected Output:

Enter the principal: 10000

Enter the rate: 2

Enter the time: 1

The Simple interest is 200

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 10


WEEK-3

AIM:To develop a c program to calculate Compound Interest.

PROGRAM:

/* W.A.C.P to calculate Compound Interest */


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

float principle, rate, time, CI;


/* Input principle, time and rate */
printf("Enter principle (amount): ");
scanf("%f", &principle);
printf("Enter time: ");
scanf("%f", &time);
printf("Enter rate: ");
scanf("%f", &rate);
/* Calculate compound interest */
CI = principle* (pow((1 + rate / 100), time));
/* Print the resultant CI */
printf("Compound Interest = %f", CI);
return 0;

Expected Output:
Enter the principal: 10000
Enter the time: 1
Enter the rate: 2
Compound Interest = 10200.00

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 11


AIM:To develop a c program find the square root of a given number

PROGRAM:
//W.A.C.P Find square root of a given number
#include<stdio.h>
int main()
{
float number, square;
printf("Please Enter any integer Value : ");
scanf("%f", &number);
square = number * number;
printf("square of a given number %.2f is = %.2f", number, square);
return 0;
}

Expected Output:

Please Enter any integer Value : 10.00

square of a given number 10.00 is = 100.00

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 12


AIM:To develop a c program area of a triangle using heron’s formulae

PROGRAM:

//W.A.C.P Area of a triangle using heron’s formulae


#include <stdio.h>
#include <math.h>
int main()
{
float sideOne, sideTwo, sideThree, s, area;
printf("Enter the length of three sides of triangle\n");
scanf("%f %f %f", &sideOne, &sideTwo, &sideThree);
s = (sideOne + sideTwo + sideThree)/2;
area = sqrt(s*(s-sideOne)*(s-sideTwo)*(s-sideThree));
printf("Area of triangle : %0.4f\n", area);
return 0;
}

Expected Output:

Enter the length of three sides of triangle

2.5 2.5 2.5

Area of triangle : 2.7063

Output:

Results

COMPUTER PROGRAMMING LAB (23A05101P) 13


AIM:To develop a c program distance travelled by the equation d = ut + at^2 */

PROGRAM:

//W.A.C.P distance travelled by the equation d = ut + at^2


#include<stdio.h>
int main()
{
float u, a, d;
int t;
printf("\nEnter the value of a : ");
scanf("%f", & a);
printf("\nEnter the value of u : ");
scanf("%f", & u);
printf("\nEnter the value of t : ");
scanf("%d", & t);
d = (u * t) + (a * t * t) / 2;
printf("\n The Distance : %.2f", d);
return 0;
}

Expected Output:
Enter the value of a :10t.0
Enter the value of u :20.5
Enter the value of a : 5.0
The Distance : 227.50

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 14


WEEK-4

AIM:To develop a c program for solving the expression A + B * C + (D * E) + F * G;

PROGRAM:

// Program for solving the expression A + B * C + (D * E) + F * G;


#include <stdio.h>
int main()
{
int A = 5, B = 3, C = 2, D = 4, E = 6, F = 7, G = 8;
// Evaluate the expression
int result = A + B * C + (D * E) + F * G;
// Print the result
printf("Result of the expression: %d\n", result);
return 0;
}

Expected Output: Result of the expression: 91

Output:

Results:

AIM:To develop a c program for solving the expression A/B*C-B+A*D/3

PROGRAM:

// Program for solving the expression A/B*C-B+A*D/3


#include <stdio.h>
int main()
{
int A = 15, B = 3, C = 5, D = 10;
// Evaluate the expression
float result = (float)A / B * C - B + (float)(A * D) / 3;
// Print the result
printf("Result of the expression: %.2f\n", result);
return 0;
}

Expected Output: Result of the expression:72.00

Output:
Results:

COMPUTER PROGRAMMING LAB (23A05101P) 15


AIM:To develop a c program for solving the expression A+++B---A

PRORAM:

//Program for solving the expression A+++B---A


#include <stdio.h>
int main()
{
int A = 10, B = 5;
// Evaluate the expression
int result = A++ + B-- - A;
// Print the result
printf("Result of the expression: %d\n", result);
return 0;
}

Expected Output: Result of the expression: 4

Output:

Results:

AIM:To develop a c program for solving the expression J= (i++) + (++i)

PROGRAM:

//Program for solving the expression J= (i++) + (++i)

#include <stdio.h>
int main()
{
int i = 5;
int J;
// Evaluate the expression
J = (i++) + (++i);
// Print the result
printf("Result of the expression: J = %d\n", J);
return 0;
}

Expected Output: Result of the expression: J = 12

Output:

COMPUTER PROGRAMMING LAB (23A05101P) 16


AIM:To develop a c program to calculate total, average and percentage of five subjects in
float.

PROGRAM:

//[Link] calculate total, average and percentage of five subjects in float


#include <stdio.h>
int main()

float eng, phy, chem, math, comp;


float total, average, percentage;
/* Input marks of all five subjects */
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);
/* Calculate total, average and percentage */
total = eng + phy + chem + math + comp;
average = total / 5.0;
percentage = (total / 500.0) * 100;
/* Print all results */
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f\n", average);
printf("Percentage = %.2f", percentage);
return 0;

Expected Output:
Enter marks of five subjects: 75.0 76.0 78.0 79.0 85.0
Total marks = 395.0

Average marks =78.60


Percentage =78.60

OUTPUT:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 17


AIM:To develop a c program to find largest among three numbers using ternary operator.

PROGRAM:

//W.A.C.P to find largest among three numbers using ternary operator


#include<stdio.h>
void main()

{
// Variable declaration
int a,b,c,larg;
printf("Enter three number\n");
scanf("%d %d %d",&a,&b, &c);
// Largest among a, b and c
larg = a>b?a>c?a:c:b>c?b:c;
//Display largest number
printf("Largest Number is : %d",larg);

Expected Output:

Enter three number

10 20 30

Largest Number is : 30

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 18


WEEK-5

AIM:To develop a c program find max and min of four numbers using if-else.

PROGRAM:

//W.A.C.P to find max and min of four numbers using if-else.


#include <stdio.h>
int max(int x, int y)
{
if(x > y)
{
return x;
}
else
{
return y;
}
}
int main()
{
int a = 5, b = 8, c = 2, d = 3;
int left_max = max(a, b);
int right_max = max(c, d);
int final_max = max(left_max, right_max);
printf("Maximum number is: %d", final_max);

Expected Output: Maximum number is: 8

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 19


AIM:To develop a c program to calculate total electricity bill.

PROGRAM:

//[Link] calculate total electricity bill


#include <stdio.h>
int main()
{
int unit;
float amt, total_amt, sur_charge;
printf("Enter total units consumed: ");
scanf("%d", &unit);
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}
sur_charge = amt * 0.20;
total_amt = amt + sur_charge;
printf("Electricity Bill = Rs. %.2f", total_amt);
return 0;

Expected Output:
Enter total units consumed: 735
Electricity Bill =Rs 1137.00
Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 20


AIM:To develop a c program find the roots of the quadratic equation

PROGRAM:

// W.A.C.P tofind the roots of the quadratic equation


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

{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
else if (discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
else
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart,
realPart, imagPart);
}
return 0;

Expected Output:

Enter coefficients a, b and c: 5.1 6.2 7.0

root1 = -61+1.001 and root2 = -0.61-1.00i

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 21


AIM:To develop a c program to find given year is a leap year or not.

PROGRAM:

//[Link] find given year is a leap year 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.", year);
}
else if (year % 100 == 0)
{
printf("%d is not a leap year.", year);
}

// leap year if not divisible by 100


// but divisible by 4
else if (year % 4 == 0)
{
printf("%d is a leap year.", year);
}
// all other years are not leap years
else
{
printf("%d is not a leap year.", year);
}
return 0;

Expected Output:
Enter a year: 2005
2005 is not a leap year

Output :

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 22


WEEK-6

AIM:To develop a c program factorial of a given number using any loop.

PROGRAM:

//W.A.C.P find factorial of a given number using any loop.


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

int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for (i = 1; i<= n; ++i)
{
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}
Expected Output:

Enter an integer: 5

Factorial of 5 = 120

Output

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 23


AIM:To develop a c program given no is prime or not.

PROGRAM:

//W.A.C.P given no is prime or not.


#include <stdio.h>
int main()

{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i<= n / 2; ++i)
{

// if n is divisible by i, then n is not prime


// change flag to 1 for non-prime number
if (n % i == 0)
{
flag = 1;
break;
}

}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
Expected Output:
Enter a positive integer: 235
235 is not a prime number.
Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 24


AIM:To develop a sine values.

PROGRAM:

//W.A.C.P to compute sine values


#include<stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150
main ( )
{
int angle;
float x,y;
angle = 0;
printf("Angle sin(angle)");
while(angle <= MAX)
{
x = (PI/MAX)*angle;
y = sin(x);
printf("%15d\n %13.4f", angle, y);
angle = angle + 10;
}
return 0;
}
Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 25


AIM:To develop a cosine values.

PROGRAM:

// W.A.C.P to compute cosine values


#include<stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150
main ( )
{
int angle;
float x,y;
angle = 0;
printf("Angle cos(angle)");
while(angle <= MAX)
{
x = (PI/MAX)*angle;
y = cos(x);
printf("%15d %13.4f", angle, y);
angle = angle + 10;
}
return 0;
}

Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 26


AIM:To develop a checking a number is palindrome or not.

PROGRAM:

// W.A.C.P checking a number is palindrome or not.


#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, s = 0;
clrscr();
printf("Enter a number:\t");
scanf("%d", &a);
c = a;
// the number is reversed inside the while loop.
while(a > 0)
{
b = a%10;
s = (s*10)+b;
a = a/10;
}
// here the reversed number is compared with the given number.
if(s == c)
{
printf("The number %d is a palindrome", c);
}
else
{
printf("The number %d is not a palindrome", c);
}
getch();
}
Expected Output:
Enter a number:252

The number 252 is a palindrome

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 27


AIM:To develop a c program to construct a pyramid of numbers.

PROGRAM:

// W.A.C.P TO toconstruct a pyramid of numbers.


#include <stdio.h>
#include <stdlib.h>
int main()
{
int rows,i,j,k,l=1;
printf("Enter number of rows you want: ");
scanf("%d",&rows);
printf("Pyramid pattern 1\n");
for(i=1; i<=rows; i++)
{
for(j=1; j<=rows-i; j++)
{
printf(" ");
}
for(k=1; k<=i; k++, l++)
{
printf("%d ",l);
}
printf("\n");
}
return 0;
}
Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 28


WEEK-7

AIM:To develop a c program find max and min of a 1-d integer array.

PROGRAM:

// W.A.C.P to find max and min of a 1-d integer array.


#include<stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int a[50], size, i, big, small;
printf("\nEnter the size of the array: ");
scanf("%d", &size);
printf("\n\nEnter the %d elements of the array: \n\n", size);
for(i = 0; i< size; i++)
scanf("%d", &a[i]);
big = a[0]; // initializing
/* from 2nd element to the last element find the bigger element than big
and
update the value of big */
for(i = 1; i< size; i++)
{
if(big < a[i]) // if larger value is encountered
{
big = a[i]; // update the value of big
}
}
printf("\n\nThe largest element is: %d", big);
small = a[0]; // initializing
/* from 2nd element to the last element find the smaller element than small and
update the value of small */
for(i = 1; i< size; i++)
{
if(small>a[i]) // if smaller value is encountered
{
small = a[i]; // update the value of small
}
}
printf("\n\nThe smallest element is: %d", small);
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 29


Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 30


AIM:To develop a c program linear search on 1d array.

PROGRAM:

//[Link] search on 1d array.


#include<stdio.h>
int main()
{
int a[20],i,x,n;
printf("How many elements?");
scanf("%d",&n);
printf("Enter array elements:n");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
printf("nEnter element to search:");
scanf("%d",&x);
for(i=0;i<n;++i)
if(a[i]==x)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");
return 0;
}

Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 31


AIM:To develop a c program reverse of an integer array.

PROGRAM:

//W.A.C.P to reverse of an integer array.


#include <stdio.h>
#include <stdlib.h>
#define n 6
int main()
{
int arr[n] = {9, 8, 7, 2, 4, 3};
int temp,i;
for(i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
for(i = 0; i< n; i++)
{
printf("%d,", arr[i]);
}
}

Expected Output: 3 4 2 7 8 9

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 32


AIM:To develop a c program 2’s complement of the given binary number.

PROGRAM:

// W.A.C.P find 2’s complement of the given binary number.


#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main()
{
int i, carry = 1;
char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
printf("Enter the binary number");
gets(num);
for(i = 0; i< SIZE; i++)
{
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1')
{
one[i] = '0';
}

}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s",num, one);
for(i = SIZE - 1; i>= 0; i--)
{
if(one[i] == '1' && carry == 1)
{
two[i] = '0';
}

else if(one[i] == '0' && carry == 1)

{
two[i] = '1';
carry = 0;

}
else
{

COMPUTER PROGRAMMING LAB (23A05101P) 33


two[i] = one[i];
}

two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s",num, two);
return 0;

Expected Output

Enter the binary number : 11011011

Ones complement of binary number 11011011 is 00100100

Two's complement of binary number 11011011 is 00100101

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 34


AIM:To develop a c program to eliminate duplicate elements in an array

PROGRAM:

//[Link] eliminate duplicate elements in an array


#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[50],i,j,k, count = 0, dup[50], number;
printf("Enter size of the array");
scanf("%d",&number);
printf("Enter Elements of the array:");
for(i=0;i<number;i++)
{
scanf("%d",&a[i]);
dup[i] = -1;
}
printf("Entered element are: ");
for(i=0;i<number;i++)
{
printf("%d ",a[i]);
}
for(i=0;i<number;i++)
{
for(j = i+1; j < number; j++)
{
if(a[i] == a[j])
{
for(k = j; k <number; k++)
{
a[k] = a[k+1];
}
j--;
number--;
}
}
}
printf("After deleting the duplicate element the Array is:");
for(i=0;i<number;i++)
{
printf("%d ",a[i]);
}
return 0; }

COMPUTER PROGRAMMING LAB (23A05101P) 35


Expected Output:

Enter size of the array : 5

Entered element are: 3 5 6 5 2


After deleting the duplicate element the Array is: 3 5 6 2

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 36


WEEK-8

AIM:To develop a c program addition of two matrices

PROGRAM:

//[Link] of two matrices


#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 37


Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 38


AIM:To develop a c program multiplication of two matrices.

PROGRAM:

//[Link] of two matrices


#include<stdio.h>
int main() {
int a[5][5], b[5][5], c[5][5], n, x, y, z;

printf("Enter the value of N (N <= 5): ");


scanf("%d", & n);
printf("Enter the elements of Matrix-1: \n");

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


for (y = 0; y < n; y++) {
scanf("%d", & a[x][y]);
}
}
printf("Enter the elements of Matrix-2: \n");
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
scanf("%d", & b[x][y]);
}
}
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
c[x][y] = 0;
for (z = 0; z < n; z++) {
c[x][y] += a[x][z] * b[z][y];
}
}
}
printf("The product of the two matrices is: \n");
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
printf("%d\t", c[x][y]);
}
printf("\n");
}
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 39


Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 40


AIM:To develop a c program to sort array elements using bubble sort

PROGRAM:

/*[Link] sort array elements using bubble sort


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

COMPUTER PROGRAMMING LAB (23A05101P) 41


Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 42


AIM:To develop a c program concatenate two strings.

PROGRAM:

//[Link] oncatenate two strings.

#include <stdio.h>
int main()
{
char str1[50], str2[50], i, j;
printf("\nEnter first string: ");
scanf("%s",str1);
printf("\nEnter second string: ");
scanf("%s",str2);
for(i=0; str1[i]!='\0'; ++i);
for(j=0; str2[j]!='\0'; ++j, ++i)
{
str1[i]=str2[j];
}
str1[i]='\0';
printf("\nOutput: %s",str1);
return 0;
}

Expected Output:

Enter first string: SV

Enter second string: CN

Output: SVCN

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 43


AIM:To develop a c program reverse a string.
PROGRAM:
//[Link] a string
#include <stdio.h>
#include <string.h>
int main()
{
char str[40]; // declare the size of character string
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);
// use strrev() function to reverse a string
printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}

Expected Output:

Enter a string to be reversed : SVCN

After the reverse of a string: NCVS

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 44


AIM:To develop a c program reverse of a string using functions.

PROGRAM:

//[Link] of a string using functions.

#include<stdio.h>
#include <string.h>
// function definition of the revstr()
void revstr(char *str1)
{
int i, len, temp;
len = strlen(str1); // use strlen() to get the length of str string
// use for loop to iterate the string
for (i = 0; i < len/2; i++)
{
// temp variable use to temporary hold the string
temp = str1[i];
str1[i] = str1[len - i - 1];
str1[len - i - 1] = temp;
}
}
int main()
{
char str[50]; // size of char string
printf (" Enter the string: ");
gets(str); // use gets() function to take string
printf (" \n Before reversing the string: %s \n", str);
// call revstr() function
revstr(str);
printf (" After reversing the string: %s", str);
}

Expected Output:
Enter the string: Welcome
Before reversing the string: Welcome
After reversing the string: emocleW

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 45


AIM:To develop a c program Reverse of a string using recursive function.

PROGRAM:

/*[Link] of a string using recursive function.

#include <stdio.h>
#include <string.h>
void revstr(char *str1)
{
// declare static variable
static int i, len, temp;
len = strlen(str1); // use strlen() to get the length of str string
if (i<len/2)
{
// temp variable use to temporary hold the string
temp = str1[i];
str1[i] = str1[len - i - 1];
str1[len - i - 1] = temp;
i++;
revstr(str1); // recusively calls the revstr() function
}
}
int main()
{
char str1[50]; // size of char string
printf (" Enter the string: ");
gets(str1); // use gets() function to take string
printf (" \n Before reversing the string: %s \n", str1);
// call revstr() function
revstr(str1);
printf (" After reversing the string: %s", str1);
}

Expected Output:

Enter the string: SVCN


Before reversing the string: SVCN
After reversing the string: NCVS

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 46


WEEK-9

AIM:To develop a c program find the sum of a 1d array using malloc ( )

PROGRAM:

//W.A.C.P to find the sum of a 1d array using malloc ( )

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr; //declaration of integer pointer
int limit; //to store array limit
int i; //loop counter
int sum; //to store sum of all elements
printf("Enter limit of the array: ");
scanf("%d", &limit);
//declare memory dynamically
ptr = (int*)malloc(limit * sizeof(int));
//read array elements
for (i = 0; i< limit; i++)
{
printf("Enter element %02d: ", i + 1);
scanf("%d", (ptr + i));
}
//print array elements
printf("\nEntered array elements are:\n");
for (i = 0; i< limit; i++)
{
printf("%d\n", *(ptr + i));
}
//calculate sum of all elements
sum = 0; //assign 0 to replace garbage value
for (i = 0; i< limit; i++)
{
sum += *(ptr + i);
}
printf("Sum of array elements is: %d\n", sum);//free memory
free(ptr); //hey, don't forget to free dynamically allocated memory.
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 47


Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 48


AIM:To develop a c program find total,average of n students using structures.

PROGRAM:

/*W.A.C.P to find total,average of n students using structures.

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

{ int rl;
char nm[20];
int m1;
int m2;
int m3;
int t;
float per;
};
void main()
{
struct student a;
clrscr();
printf(" Enter RollNo, Name amd three sub marks\n");
scanf("%d%s%d%d%d", &[Link], &[Link], &a.m1, &a.m2, &a.m3);
a.t = a.m1 + a.m2 + a.m3;
[Link] = a.t / 3.0;
printf("rollno=%d\n", [Link]);
printf("Name=%sk\n", [Link]);
printf("m1=%d\n", a.m1);
printf("m2=%d\n", a.m2);
printf("m3=%d\n", a.m3);
printf("total=%d\n", a.t);
printf("per=%f\n", [Link]);
getch();
}

COMPUTER PROGRAMMING LAB (23A05101P) 49


Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 50


AIM:To develop a c program n st udent data using calloc( ) and display failed student
list

PROGRAM:

//[Link] student data using calloc( ) and display failed student list

# include <string.h>
# include <stdio.h>
struct student
{
char name[10];
int m[3];
int total;
char result[5];
}*p,*s;
void main()
{
int i,j,l,n;
clrscr();
printf("Enter the no. of students : ");
scanf("%d",&n);
p=(struct student*)malloc(n*sizeof(struct student));
s=p;
for(i=0;i<n;i++)
{
printf("Enter a name : ");
scanf("%s",&p->name);
p-> total=0;l=0;
for(j=0;j<3;j++)
{
one:printf("Enter Marks of %d Subject : ",j+1);
scanf("%d",&p->m[j]);
if((p->m[j])>100)
{
printf("Wrong Value Entered");
goto one;
}
p->total+=p->m[j];
if(p->m[j]<40)
l=1;
}
if(l==0)
strcpy(p->result,"PASS");

COMPUTER PROGRAMMING LAB (23A05101P) 51


else
strcpy(p->result,"FAIL");
p++;
}
for(i=0;i<n;i++)
{
printf("\n%s\t%s",s->name,s->result);
s++;
}
getch();
}

Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 52


AIM:To develop a c program read student name and marks from the command line and
display the student details along with total */

PROGRAM:

/* W.A.C.P read student name and marks from the command line and display the student
details along with total */
#include <stdio.h>
struct student
{
int roll;
char name[50];
int marks;
};
void main()
{
struct student s[10];
int i, n, sum = 0;
float average = 0;
printf("Enter the number of students : ");
scanf("%d", &n);
for (i = 0; i< n; i++)
{
printf("Enter the details of student - %d\n", i+1);
printf("Enter the roll number : ");
scanf("%d", &s[i].roll);
printf("Enter the name : ");
scanf("%s", s[i].name);
printf("Enter total marks : ");
scanf("%d", &s[i].marks);
}
for (i = 0; i< n; i++)
{
sum = sum + s[i].marks;
}
average = (float)sum / n;
printf("Class average : %f\n", average);
printf("RollNo\tStudentName\tTotalMarks\tAboveAverage(Y/N)\n");
for (i = 0; i< n; i++)
{
printf("%4d", s[i].roll);
printf("%15s", s[i].name);
printf("%15d", s[i].marks);
if(s[i].marks>= average)

COMPUTER PROGRAMMING LAB (23A05101P) 53


printf("\tYes");
else printf("\tNo");
printf("\n");
}
}

Expected Output:

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 54


AIM:To develop a c program to implement realoc( )

PROGRAM:

//[Link] implement realoc( )

#include<stdio.h>
//To use realloc in our program
#include<stdlib.h>
intmain()
{
char *ptr;
ptr = NULL;

/*
*since the ptr is NULL,
*it will act like malloc function
*/
ptr = realloc(ptr,10);
if(ptr != NULL)
printf("Memory created successfully\n");
return0;
}

Expected Output:

COMPUTER PROGRAMMING LAB (23A05101P) 55


Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 56


WEEK-10

AIM:To develop a c program single linked list using structures

PROGRAM:

//[Link] linked list using structures

#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void deleteStart (struct Node **head)
{
struct Node *temp = *head;
// if there are no nodes in Linked List can't delete
if (*head == NULL)
{
printf ("Linked List Empty, nothing to delete");
return;
}
// move head to next node
*head = (*head)->next;
printf ("\n%d deleted\n", temp->data);
free (temp);
}
void insertStart (struct Node **head, int data)
{
// dynamically create memory for this newNode
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));
// assign data value
newNode->data = data;
// change the next node of this newNode
// to current head of Linked List
newNode->next = *head;
//re-assign head to this newNode
*head = newNode;
printf ("\n%d Inserted\n", newNode->data);
}
void display (struct Node *node)
{

COMPUTER PROGRAMMING LAB (23A05101P) 57


printf ("\nLinked List: ");
// as linked list will end when Node is Null
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
printf ("\n");
}
int main ()
{
struct Node *head = NULL;
// Need '&' i.e. address as we need to change head
insertStart (&head, 100);
insertStart (&head, 80);
insertStart (&head, 60);
insertStart (&head, 40);
insertStart (&head, 20);
// No Need for '&' as not changing head in display operation
display (head);
deleteStart (&head);
deleteStart (&head);
display (head);
return 0;
}

Expected Output:

COMPUTER PROGRAMMING LAB (23A05101P) 58


Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 59


AIM:To develop a c program structures and unions

PROGRAM:

//[Link] and unions


#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}

Expected Output:
size of union = 32 bytes
size of structure =38 bytes

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 60


AIM:To develop a c program to left shift rotation for given number.

PROGRAM:

//[Link] left shift rotation for given number.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int number, rotate, Msb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--)
{
Msb = (number >> size) & 1;
number = (number << 1) | Msb;
}
printf("After Left rotation the value is = %d",number);
return 0;
}

Expected Output:

Enter any number: 123456


Enter number of rotations: 02
After Left rotation the value is =-30461

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 61


AIM:To develop a c program right shift rotation for a given number.

PROGRAM:

/*[Link] shift rotation for a given number.


#include<stdio.h>
#include<stdlib.h>
int main(){
int number,rotate, Lsb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--)
{
Lsb = number & 1;
number = (number >> 1) &(~(1<<size));
number=number|(Lsb<<size);
}
printf("After right rotation the value is = %d",number);
return 0;
}

Expected Output:
Enter any number: 123456
Enter number of rotations: 02
After Right rotation the value is = -1904

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 62


AIM:To develop a c program to copy one structure variable to another structure of the
same type.

PROGRAM:

/*[Link] copy one structure variable to another structure of the same type.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Student
{
char *name;
int age;
}
Student;
int main(int argc, char *argv[])
{
Student std1;
Student std2;
[Link] = (char *)malloc(10);
[Link] = 20;
strcpy([Link], "John");
printf("std1->name: %s, age: %d\n", [Link], [Link]);
std2 = std1;
[Link] = (char *)malloc(10);
strcpy([Link], [Link]);
printf("std2->name: %s, age: %d\n", [Link], [Link]);
free([Link]);
free([Link]);
return 0;
}

Expected Output:

std1->name: john, age: 20

std2->name: john, age: 20

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 63


WEEK-11

AIM:To develop a c program t he total number of ways for selecting r elements out of n options
are nCr = (n!) / (r! * (n-r)!)
where n! = 1 * 2 * . . . * n. */

PROGRAM:

//[Link] number of ways for selecting r elements out of n options are nCr = (n!) / (r! * (n-
r)!)
where n! = 1 * 2 * . . . * n. */

#include <stdio.h>
int factorial(int n)
{
int factorial = 1,i;
if(n == 0)
return 1;
for (i = 2; i<= n; i++)
factorial = factorial * i;
return factorial;
}
int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main()
{
int n = 5, r = 3;
printf("%d", nCr(n, r));
return 0;
}

Expected Output : 10

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 64


AIM:To develop a c program to find length of a string.

PROGRAM:

//W.A.C.P to find length of a string.

#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
int i, length;
printf("Enter a string: ");
scanf("%s", str);
length = 0;
for (i = 0; str[i] != '\0'; i++)
{
length++;
}
printf("The length of the string is: %d\n", length);
}

Expected Output

Enter a string: svcn

The length of the string is: 4

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 65


AIM:To develop a c program to transpose of a matrix.
PROGRAM:
//[Link] find transpose of a matrix.

#include <stdio.h>
void transpose(int arr[10][10], int m, int n, int brr[10][10]) //Function Definition
{
int i,j;
for(i=0;i<m;i++) //Transpose Matrix initialization
{
for( j=0;j<n;j++)
{
brr[j][i]=arr[i][j]; //Store elements in the transpose matrix
}
}
printf("\nAfter transpose the elements are...\n");
for( i=0;i<m;i++) //Print the transpose matrix
{
for( j=0;j<n;j++)
{
printf("%d ",brr[i][j]);
}
printf("\n");
}
}
int main()
{
int m,n,i,j,arr[10][10],brr[10][10]; //Matrix Size
Declaration
printf("Enter the number of rows and column: \n");
scanf("%d %d",&m,&n); //Matrix Size Initialization
printf("\nEnter the elements of the matrix: \n");
for(int i=0;i<m;i++) //Matrix Initialization
{
for(int j=0;j<n;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("\nThe elements in the matrix are: \n");
for(int i=0;i<m;i++) //Print the matrix
{
for(int j=0;j<n;j++)
{

COMPUTER PROGRAMMING LAB (23A05101P) 66


printf("%d ",arr[i][j]);
}
printf("\n");
}
transpose(arr,m,n,brr); //Function Call
return 0;
}

Expected Output

OUTPUT

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 67


AIM:To develop a c program numerical integration of differential equations using euler’s
theorem.

PROGRAM:

//W.A.C.P numerical integration of differential equations using euler’s theorem.

#include<stdio.h>
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}

COMPUTER PROGRAMMING LAB (23A05101P) 68


Expected Output

OUTPUT:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 69


WEEK-12

AIM:To develop a c program Fibonacci Series in C without recursion.

PROGRAM:

//[Link] Series without recursion

#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}

Expected Output:

Enter the number of elements: 5

0 1 1 2 3

Output

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 70


AIM:Todevelop a c program Fibonacci series using recursion .
PROGRAM:

//[Link] series using recursion .


#include<stdio.h>
void printFibonacci(int n)
{
static int n1=0,n2=1,n/3;
if(n>0)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}

Expected Output

Enter the number of elements: 5

Fibonacci Series: 0 1 1 2 3

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 71


AIM:To develop a c program recursive function lcm of two numbers.
PROGRAM:
//W.A.R.F TO FIND THE LCM OF TWO NUMBERS

#include <stdio.h>
int lcm(int n1, int n2)
{
static int lowestcm = 1;
if(lowestcm%n1 == 0 && lowestcm%n2 == 0)
{
return lowestcm;
}
else
{
lowestcm++;
lcm(n1,n2);
return lowestcm;
}
}

int main()
{
int n1 = 4, n2 = 8;
printf("L.C.M of %d and %d is %d.", n1, n2, lcm(n1, n2));
return 0;
}

Expected Output

L.C.M of 4 and 8 is 8.

Output

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 72


AIM:To develop a c program factorial of a number using recusion.

PROGRAM:

//W.A.C.P factorial of a number using recusion.


#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Expected Output:

Enter a positive integer:5

Factorial of 5= 120

Output

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 73


AIM:To develop a c program to implement Ackermann function using recursion.

PROGRAM:

//W.A.C.P to implement Ackermann function using recursion.


#include<stdio.h>
int A(int m, int n);
main()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\nOUTPUT :: %d\n",A(m,n));
}
int A(int m, int n)
{
if(m==0)
return n+1;
else if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
}

Expected Output

Enter two numbers :: 2 1

OUTPUT: 5

OUTPUT

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 74


AIM:To develop a c program to find sum of series: 1+2+3+4+....+N

PROGRAM:

//W.A.C.P to find sum of series: 1+2+3+4+....+N


#include<stdio.h>
int series(int n);
int rseries(int n);
int main( )
{
int n;
printf("Enter number of terms : ");
scanf("%d", &n);
printf("\b\b Using Recursion :: \n");
printf("\b\b = %d\n", series(n)); /* \b to erase last +sign */
printf("\n\b\b Using Recursion :: \n");
printf("\b\b = %d\n\n\n", rseries(n));
return 0;
}/*End of main()*/
/*Iterative function*/
int series(int n)
{
int i, sum=0;
for(i=1; i<=n; i++)
{
printf("%d + ", i);
sum+=i;
}
return sum;
}/*End of series()*/

/*Recursive function*/
int rseries(int n)
{
int sum;
if(n == 0)
return 0;
sum = (n + rseries(n-1));
printf("%d + ",n);
return sum;
}/*End of rseries()*/

COMPUTER PROGRAMMING LAB (23A05101P) 75


Expected Output

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 76


WEEK-13

AIM:To develop a c program to swap two number using call by reference

PROGRAM:

//W.A.C.P to swap two number using call by reference

#include <stdio.h>
/* Swap function declaration */
void swap(int * num1, int * num2);
int main()
{
int num1, num2;
/* Input numbers */
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
/* Print original values of num1 and num2 */
printf("Before swapping in main n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);
/* Pass the addresses of num1 and num2 */
swap(&num1, &num2);
/* Print the swapped values of num1 and num2 */
printf("After swapping in main n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);
return 0;
}
// Function to swap two numbers
void swap(int * num1, int * num2)
{
int temp;
// Copy the value of num1 to some temp variable
temp = *num1;
// Copy the value of num2 to num1
*num1= *num2;
// Copy the value of num1 stored in temp to num2
*num2= temp;
printf("After swapping in swap function n");
printf("Value of num1 = %d \n", *num1);
printf("Value of num2 = %d \n\n", *num2);
}

COMPUTER PROGRAMMING LAB (23A05101P) 77


Expected Output

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 78


AIM:To develop a c program demonstrate dangling pointer problem.

PROGRAM:

//W.A.C.P demonstrate dangling pointer problem.

#include <stdio.h>
#include <stdlib.h>
int main() {
// 4 bytes of int memory block (64bit compiler)
// allocated using malloc() during runtime
int *ptr = (int *)malloc(sizeof(int)); // normal pointer
*ptr = 10;
// memory block deallocated using free() function
free(ptr);
// here ptr acts as a dangling pointer
printf("%d", *ptr);
// prints garbage value in the output console
return 0;
}

Expected Output

1010

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 79


AIM:To develop a c program copy one string into another using pointer.

PROGRAM:

//W.A.C.P to copy one string into another using pointer.

#include<stdio.h>

void copy_string(char*, char*);

main()
{
char source[100], target[100];
printf("Enter source string\n");
gets(source);
copy_string(target, source);
printf("Target string is \"%s\"\n", target);
return 0;
}
void copy_string(char *target, char *source)
{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '\0';
}

Expected Output

Enter source string : svcn

Target string is “svcn”

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 80


AIM:To develop a c program to Count Uppercase, Lowercase, and Special Characters in
String

PROGRAM:

//W.A.C.P Count Uppercase, Lowercase, and Special Characters in String .

#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[100];
int i;
int upper=0,lower=0,special=0;;
printf("Please enter the string \n");
gets(str);
// For Uppercase
for(i=0; str[i] != '\0'; i++){
if(str[i]>='A' && str[i]<='Z') {
upper++;
}
// For Lowercase
else if(str[i]>='a' && str[i]<='z') {
lower++;
}
// For special
else
{
special++;
}
}
printf("\nUpper case letters: %d",upper);
printf("\nLower case letters: %d",lower);
printf("\nSpecial characters: %d",special);
getch();
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 81


Expected Output:

Please enter the string: SVCN&jn

Upper case letters: 4

Lower case letters: 2

Special characters: 1

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 82


WEEK-14

AIM:To develop a c program to read and write text into a file.


PROGRAM:
//[Link] read and write text into a file.

#include<stdio.h>
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("\nEnter file name to create :");
scanf("%s",fName);
/*creating (open) a file*/
fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
/*writting into file*/
putc('A',fp);
putc('B',fp);
putc('C',fp);
printf("\nData written successfully.");
fclose(fp);
/*again open file to read data*/
fp=fopen(fName,"r");
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}
printf("Contents of file is :\n");
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
fclose(fp);
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 83


Expected Output

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 84


AIM:To develop a c program copy the contents of one file to another file.
PROGRAM:

//W.A.C.P copy the contents of one file to another file.

#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 85


Expected Output

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 86


AIM:To develop a c program merge two files into the third file using command
arguments.

Let the given two files be [Link] and [Link]. The following are steps to merge.
1) Open [Link] and [Link] in read mode.
2) Open [Link] in write mode.
3) Run a loop to one by one copy characters of [Link] to [Link].
4) Run a loop to one by one copy characters of [Link] to [Link].
5) Close all files.

To successfully run the below program [Link] and [Link] must exits in same
folder.

PROGRAM:

//[Link] two files into the third file using command arguments.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("[Link]", "r");
FILE *fp2 = fopen("[Link]", "r");
// Open file to store the result
FILE *fp3 = fopen("[Link]", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to [Link]
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to [Link]
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged [Link] and [Link] into [Link]");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}

COMPUTER PROGRAMMING LAB (23A05101P) 87


Expected Output

[Link]

Welcome

[Link]

Svcn

File .txt:

welcome

svcn

Merged [Link] and [Link] into [Link]

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 88


AIM:To develop a c program to count number of characters, words and lines in a text
file

PROGRAM:

//W.A.C.P to count number of characters, words and lines in a text file.

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];

char ch;
int characters, words, lines;
/* Input path of files to merge to third file */
printf("Enter source file path: ");
scanf("%s", path);
/* Open source files in 'r' mode */
file = fopen(path, "r");
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/** Logic to count characters, words and lines.*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check new line */
if (ch == '\n' || ch == '\0')
lines++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;

COMPUTER PROGRAMMING LAB (23A05101P) 89


lines++;
}

/* Print file statistics */


printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
/* Close files to release resources */
fclose(file);
return 0;
}

Expected Output

[Link]

Sree venkateswara college of engineering

Enter source file path: data/[Link]

Total characters = 30
Total words =5
Total lines =1

Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 90


AIM:To develop a c program to print last N characters of a given file.

PROGRAM:

//[Link] print last N characters of a given file.


#include<stdio.h>
int main()
{
FILE *fp;
char ch;
int num;
long length;
printf("Enter the value of num : ");
scanf("%d", &num);

fp = fopen("[Link]", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - num), SEEK_SET);
do
{
ch = fgetc(fp);
putchar(ch);
}
while (ch != EOF);
fclose(fp);
return(0);
}

Expected Output

[Link]

Hello, World!

Welcome to C file handling.

Enter the value of num :9

handling.

COMPUTER PROGRAMMING LAB (23A05101P) 91


Output:

Results:

COMPUTER PROGRAMMING LAB (23A05101P) 92

You might also like