Computer Programming Lab Manual
Computer Programming Lab Manual
COLLEGE OF ENGINEERING
(AUTONOMOUS)
[Link], NELLORE (DIST)
COMPUTER PROGRAMMING
LAB MANUAL
(R 23 REGULATION)
I BTECH –I SEM
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
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
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.
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.
GCC:
Creating:
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.
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 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!
File⇒New⇒Empty File.
int main()
{
cout<< "Hello, world!" <<endl; return 0;
}
Save the file as " [Link] " in your project directory (e.g., " d:\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] "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 ".
[Link] create more source file or header file under the project: File⇒New File...⇒
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.
PROGRAM:
{
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
Output:
Results:
PROGRAM:
Results:
PROGRAM:
Expected Output:
Enter 3 numbers: 10 20 30
Sum= 60
Average= 20.00
Output :
Results:
PROGRAM:
{
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:
Celsius: 100.005554
Output:
Results:
PROGRAM:
Expected Output:
Output:
Results:
PROGRAM:
Expected Output:
Enter the principal: 10000
Enter the time: 1
Enter the rate: 2
Compound Interest = 10200.00
Output:
Results:
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:
Output:
Results:
PROGRAM:
Expected Output:
Output:
Results
PROGRAM:
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:
PROGRAM:
Output:
Results:
PROGRAM:
Output:
Results:
PRORAM:
Output:
Results:
PROGRAM:
#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;
}
Output:
PROGRAM:
Expected Output:
Enter marks of five subjects: 75.0 76.0 78.0 79.0 85.0
Total marks = 395.0
OUTPUT:
Results:
PROGRAM:
{
// 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:
10 20 30
Largest Number is : 30
Output:
Results:
AIM:To develop a c program find max and min of four numbers using if-else.
PROGRAM:
Output:
Results:
PROGRAM:
Expected Output:
Enter total units consumed: 735
Electricity Bill =Rs 1137.00
Output:
Results:
PROGRAM:
{
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:
Output:
Results:
PROGRAM:
Expected Output:
Enter a year: 2005
2005 is not a leap year
Output :
Results:
PROGRAM:
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:
PROGRAM:
{
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)
{
}
// 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:
PROGRAM:
Output:
Results:
PROGRAM:
Expected Output:
Output:
Results:
PROGRAM:
Output:
Results:
PROGRAM:
Output:
Results:
AIM:To develop a c program find max and min of a 1-d integer array.
PROGRAM:
Output:
Results:
PROGRAM:
Expected Output:
Output:
Results:
PROGRAM:
Expected Output: 3 4 2 7 8 9
Output:
Results:
PROGRAM:
}
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';
}
{
two[i] = '1';
carry = 0;
}
else
{
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s",num, two);
return 0;
Expected Output
Output:
Results:
PROGRAM:
Output:
Results:
PROGRAM:
Output:
Results:
PROGRAM:
Output:
Results:
PROGRAM:
Output:
Results:
PROGRAM:
#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:
Output: SVCN
Output:
Results:
Expected Output:
Output:
Results:
PROGRAM:
#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:
PROGRAM:
#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:
Output:
Results:
PROGRAM:
#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;
}
Output:
Results:
PROGRAM:
#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();
}
Output:
Results:
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");
Expected Output:
Output:
Results:
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)
Expected Output:
Output:
Results:
PROGRAM:
#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:
Results:
PROGRAM:
#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)
{
Expected Output:
Results:
PROGRAM:
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:
PROGRAM:
#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:
Output:
Results:
PROGRAM:
Expected Output:
Enter any number: 123456
Enter number of rotations: 02
After Right rotation the value is = -1904
Output:
Results:
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:
Output:
Results:
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:
PROGRAM:
#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
Output:
Results:
#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++)
{
Expected Output
OUTPUT
Results:
PROGRAM:
#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);
}
}
OUTPUT:
Results:
PROGRAM:
#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:
0 1 1 2 3
Output
Results:
Expected Output
Fibonacci Series: 0 1 1 2 3
Output:
Results:
#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:
PROGRAM:
Expected Output:
Factorial of 5= 120
Output
Results:
PROGRAM:
Expected Output
OUTPUT: 5
OUTPUT
Results:
PROGRAM:
/*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()*/
Output:
Results:
PROGRAM:
#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);
}
Output:
Results:
PROGRAM:
#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:
PROGRAM:
#include<stdio.h>
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
Output:
Results:
PROGRAM:
#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;
}
Special characters: 1
Output:
Results:
#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;
}
Output:
Results:
#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;
}
Output:
Results:
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;
}
[Link]
Welcome
[Link]
Svcn
File .txt:
welcome
svcn
Output:
Results:
PROGRAM:
#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++;
Expected Output
[Link]
Total characters = 30
Total words =5
Total lines =1
Output:
Results:
PROGRAM:
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!
handling.
Results: