C Programming Lab Course Overview
C Programming Lab Course Overview
Course Objectives:
The course aims to give students hands – on experience and train them on the
concepts of the C- programming language.
Course Outcomes:
CO1: Read, understand, and trace the execution of programs written in C language.
CO2: Select the right control structure for solving the problem.
CO3: Develop C programs which utilize memory efficiently using programming
constructs like pointers.
CO4: Develop, Debug and Execute programs to demonstrate the applications of
arrays,functions, basic concepts of pointers in C.
UNIT I
WEEK 1
Objective: Getting familiar with the programming environment on the computer and
writing the first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab1: Familiarization with programming environment
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
VI/VIM:
Vim (Vi Improved), as the name suggests is an improved clone of the text
editor. The text editor was originally developed by Billy Joy in 1976 for the
proprietary Unix operating system. Bram Moolenar later enhanced vi and released it
as vim in 1991.
Vim is a powerful command-line-based text editor that has enhanced the
functionalities of the old Unix Vi text editor. It is one the most popular and widely
used text editors among System Administrators and programmers that is why many
users often refer to it as a programmer’s editor. It enables syntax highlighting when
writing code or editing configuration files.
The UNIX vi editor is a full-screen editor and has two modes of operation:
1. Command mode commands which cause action to be taken on the file, and
2. Insert mode in which entered text is inserted into the file. In the command mode,
every character typed is a command that does something to the text file being edited;
a character typed in the command mode may even cause the vi editor to enter the
insert mode.
In the insert mode, every character typed is added to the text in the file; pressing
the (Escape) key turns off the Insert [Link] there are several vi commands, just
a handful of these is usually sufficient for beginning vi users.
Emacs (Editor Macros) was developed by David A Moon in 1976 making it one of
the oldest pieces of software which exists today. GNU Emacs, the most used
variant(fork) of Emacs, was released in 1985 by Richard Stallman, the founder of
GNU/Linux.
Emacs is a highly advanced, extensible, and customizable text editor that also offers
an interpretation of the Lisp programming language at its core. Different extensions
can be added to support text editing functionalities.
Starting with Turbo C, we need to install the IDE in the system. TC works only with
the DOS systems. But, we see it running on the windows machine too. Yes. It is
running there. But there is a virtual machine named as "New Technology Virtual DOS
Machine". We can find the virtual machine in the location "C:\windows\system32\" as
"[Link]". We can do all the operations which are supported by DOS. And this is
the greatest drawback. We can do only the operations supported by DOS. There are
some other compilers for C which can be used with Windows programming. But we
will talk about them later.
To compile with Turbo C, just start the IDE, type the code and and press CTRL+F9.
But DO NOT forget to save the code at first. To save the code "ALT+F --> S"
combination will be used.
There is a common problem with the beginners in Turbo C that once they start an
infinite loop by accident, they can't get over it, and they have to close the terminal. It
results in loosing the code. To overcome this problem, saving the code before each
compilation is ultimate solution. And to terminate an infinite loop, we can press
"CTRL+C".
Now about the files. Every time we work with Turbo C compiler, it generates four
files we can access. The first one is the code file itself. Let us consider that we are
working with a file "sample.c".
One thing to remember that since Turbo C is working on NTVDM, it will support a
file name with DOS convention. That is, it must have a maximum 8 characters long
name and maximum 3 characters extension, and off-course it should start with an
alphabet or underscore and must consist of alphabets, numbers and underscore, and
nothing else.
Each time we edit and save the file, TC (Turbo C) saves the current version of file as
current name, in present scenario "sample.c". TC also provides a backup file which is
the last version of the current file, named same as the file but with an extension "bak",
"[Link]" in our scenario. We have to remember that only one backup exists for
each file, that is the last backup.
To compile the code, we press F9. In this stage TC compiles the code, and generates
an object file with extension "obj", "[Link]" in our scenario. Then Linker
converts the object code into executable code, with extension ".exe", "[Link]".
These are the four files we can access.
Location of all these files are by default "\tc\bin". We can see all files here and can
execute the application directly by clicking on it.
Now, I think it enough for us about TC. Other features and functionalities, we can
explore on our own.
GCC works with the command line interface of Linux based system. We should check
for if GCC is already installed in the system. To check it just type the word " GCC" in
the terminal. If it is installed, it will show an error that no input file found. Otherwise
you will need to install it. To install it, just type the command "sudo apt-get install
GCC" and follow the instruction.
To start, we will open any text editor, and type in the code. After typing the code save
the file with extension "c". Continuing our assumption, let us name it "sample.c".
To execute the code, at first move to the directory where the file is saved. Then type
the command "gcc sample.c". If code has no errors it shows nothing and just returns
to another prompt. If there are any problems in the code, it lists all of them with line
and column numbers. We just find them, debug them and rerun the command. And
repeat the process till each there are no bugs in the code.
On the successful compilation of the code, executable file is generated named "[Link]".
To execute this file type "./[Link]". It runs the program. On this stage we can find some
logical errors in program such as infinite loop. To break the loop, same combination
of keys work here too, "CTRL+C".
About the files generated during the compilation of code in GCC, only file generated
is executable file.
Source Code:
#include <stdio.h>
int main(){
int testInteger;
Scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
Output: Number:4
WEEK 2
SourceCode:
#include <stdio.h>
int main(){
int num1, num2, num3, sum;
float avg;
Printf ("Enter the First Number = ");
Scanf ("%d",&num1);
printf("Enter the Second Number = ");
scanf("%d",&num2);
printf("Enter the Third Number = ");
scanf("%d",&num3);
sum = num1 + num2 + num3;
avg = sum / 3;
printf("\nThe Sum of Three Numbers= %d", sum);
printf("\nThe Average of Three Numbers = %.2f\n", avg);
}
Input:
Enter the First Number = 22.5
Enter the Second Number = 55.9
Enter the Third Number = 128.7
Output:
The Sum of Three Numbers = 207.10
The Average of Three Numbers = 69.03
SourceCode:
#include <stdio.h>
float fahrenheit_to_celsius(float f)
{
return ((f - 32.0) * 5.0 / 9.0);
}
int main()
{
float f = 40;
printf("Temperature in Degree Celsius : %0.2f",fahrenheit_to_celsius(f));
return 0;
}
SourceCode:
# include <conio.h>
# include <stdio.h>
# include <stdlib.h>
int main(){
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;
}
input:
Output:
WEEK 3
Objective: Learn how to define variables with the desired data-type, initialize them
with appropriate values and how arithmetic operators can be used with variables and
constants.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
Lab 3: Simple computational problems using arithmetic expressions.
i) Finding the square root of a given number
SourceCode:
#include <math.h>
#include <stdio.h>
// Function to find the square-root of N
double findSQRT(double N) { return sqrt(N); }
// Driver Code
int main()
{
// Given number
int N = 12;
// Function call
printf("%f ", find SQRT(N));
return 0;
}
Output:
3.464102
SourceCode:
#include <stdio.h>
// For using pow function we must
// include math.h
#include<math.h>
// Driver code
int main()
{
// Principal amount
double principal = 10000;
// Annual rate of interest
double rate = 5;
// Time
double time = 2;
// Calculating compound Interest
double Amount = principal *((pow((1 + rate / 100), time)));
double CI = Amount - principal;
printf("Compound Interest is : %lf",CI);
return 0;
}
Output:
Compound interest is 1025
SourceCode:
#include <stdio.h>
#include <math.h>
int main(){
float side One, side Two, side Three, s, area;
Printf("Enter the length of three sides of triangle\n");
Scanf("%f %f %f", &side One, &side Two, &side Three);
s = (sideOne + sideTwo + sideThree)/2;
area = sqrt(s*(s-sideOne)*(s-sideTwo)*(s-sideThree));
printf("Area of triangle : %0.4f\n", area);
return 0;
}
Input:
345
Output:
input:
Output:
SourceCode:
#include<stdio.h>
#include<conio.h>
int main()
{
int d,u,a,t;
printf("Enter the value of u =");
scanf("%d",&u);
printf("Enter the value of t =");
scanf("%d",&t);
printf("Enter the value of a =");
scanf("%d",&a);
printf("Travelled distance d = %d",d=u*t+a*t^2);
getch();
return 0;
}
Output:
Enter the value of u =25
Enter the value of t =45
Enter the value of a =34
Travelled distance d = 2653
UNIT II
WEEK 4
Objective: Explore the full scope of expressions, type-compatibility of variables &
constants
and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
Tutorial4: Operators and the precedence and as associativity:
Lab4: Simple computational problems using the operator’ precedence and
associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii)Find the maximum of three numbers using conditional operator
SourceCode:
# include <stdio.h>
void main()
{
int a, b, c, max ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
max = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("\nThe maximum number is : %d", max) ;
}
input:
Enter three numbers:9 1 4
Output:
The maximum number is:9
iv) Take mark of 5 subjects in integers, and find the total, average in float
SourceCode:
#include<stdio.h>
Int main()
{
int total_subjects;
float total,average,percentage,marks;
//taking input from the user
printf("Enter no. of subjects: \n");
scanf("%d", &total_subjects);
printf("Enter marks for each subject: \n");
for(int i = 0; i < total_subjects; i++)
{
scanf("%f",&marks);
total = total + marks;
}
average = total / total_subjects;
percentage = (total / total_subjects * 100) / 100;
printf("Total Marks of %d Subjects = %0.2f\n",total_subjects,total);
printf("Average Marks = %.2f\n", average);
printf("Percentage = %.2f", percentage);
return 0;
}
input:
Enter no. of subjects:
6
Enter marks of each subject:
89
75
83
97
78
90
Output:
Total marks of 6 subjects = 512
Average Marks = 85.3
Percentage = 85.3
WEEK 5
Objective: Explore the full scope of different variants of “if construct” namely if-
else, null else, if-else if*-else, switch and nested-if including in what scenario each
one of them can be used and how to use them. Explore all relational and logical
operators while writing conditionals for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
SourceCode:
#include <stdio.h>
int main( void )
{
int a, b, c, d;
int largest, smallest;
printf( "Enter four integers (separate them with spaces): " );
Scanf( "%d %d %d %d", &a, &b, &c, &d );
largest = smallest = a;
if ( largest < b )
{
largest = b;
}
else if ( b < smallest )
{
smallest = b;
}
if ( largest < c )
{
largest = c;
}
else if ( c < smallest )
{
smallest = c;
}
if ( largest < d )
{
largest = d;
}
else if ( d < smallest )
{
smallest = d;
}
printf( "\nLargest: %d\n", largest );
printf( "Smallest: %d", smallest );
return 0;
}
input:
Enter four integers (separate them with spaces): 3 2 1 4
Output:
Largest: 4
Smallest: 1
SourceCode:
# include<stdio.h>
# include<math.h>
int main () {
float a,b,c,r1,r2,d;
printf ("Enter the values of a b c: ");
Scanf (" %f %f %f", &a, &b, &c);
d= b*b - 4*a*c;
if (d>0) {
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d==0) {
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("Roots are equal =%f %f", r1, r2);
}
else
printf("Roots are imaginary");
return 0;
}
Output:
Case 1:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000
Case 2:
Enter the values of a b c: 1 2 1
Roots are equal =-1.000000 -1.000000
Case 3:
Enter the values of a b c: 1 1 4
Roots are imaginary
SourceCode:
# include<stdio.h>
# include<math.h>
int main () {
float a,b,c,r1,r2,d;
printf ("Enter the values of a b c: ");
scanf (" %f %f %f", &a, &b, &c);
d= b*b - 4*a*c;
if (d>0) {
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d==0) {
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("Roots are equal =%f %f", r1, r2);
}
else
printf("Roots are imaginary");
return 0;
}
Output:
Case 1:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000
Case 2:
Enter the values of a b c: 1 2 1
Roots are equal =-1.000000 -1.000000
Case 3:
Enter the values of a b c: 1 1 4
Roots are imaginary
iv)Write a C program to simulate a calculator using switch case.
SourceCode:
// C Program to make a Simple Calculator
// Using switch case
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{
char ch;
double a, b;
while (1) {
printf("Enter an operator (+, -, *, /), "
"if want to exit press x: ");
scanf(" %c", &ch);
// to exit
if (ch == 'x')
exit(0);
printf("Enter two first and second operand: ");
scanf("%lf %lf", &a, &b);
// Using switch case we will differentiate
// operations based on different operator
switch (ch) {
// For Addition
case '+':
printf("%.1lf + %.1lf = %.1lf\n", a, b, a + b);
break;
// For Subtraction
case '-':
printf("%.1lf - %.1lf = %.1lf\n", a, b, a - b);
break;
// For Multiplication
case '*':
printf("%.1lf * %.1lf = %.1lf\n", a, b, a * b);
break;
// For Division
case '/':
printf("%.1lf / %.1lf = %.1lf\n", a, b, a / b);
break;
// If operator doesn't match any case constant
default:
printf(
"Error! please write a valid operator\n");
}
printf("\n");
}
}
Output:
Enter an operator (+, -, *, /), if want to exit press x: +Enter two first and second
operand: 7 8
7.0 + 8.0 = 15.0
Enter an operator (+, -, *, /), if want to exit press x: -Enter two first and second
operand: 8 9
8.0 - 9.0 = -1.0
Enter an operator (+, -, *, /), if want to exit press x: *Enter two first and second
operand: 8 7
8.0 * 7.0 = 56.0
Enter an operator (+, -, *, /), if want to exit press x: /Enter two first and second
operand: 8 3
8.0 / 3.0 = 2.7
Enter an operator (+, -, *, /), if want to exit press x: x
SourceCode:
#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);
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
printf("%d is not a leap year.", 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;
}
Output 1:
Enter a year: 1900
1900 is not a leap year.
Output 2
Enter a year: 2012
2012 is a leap year.
WEEK 6
Objective: Explore the full scope of iterative constructs namely while loop, do-while
loop and for loop in addition to structured jump constructs like break and continue
including when each of these statements is more appropriate to use.
Suggested Experiments/Activities:
SourceCode:
#include <stdio.h>
int main()
{
int nbr, i = 1, f = 1;
printf("Enter a number to calculate its factorial: ");
scanf("%d", &nbr);
while(i <= nbr)
{
f = f * i;
i++;
}
printf("%d! = %ld\n", nbr, f);
return 0;
}
Output:
Enter a number to calculate its factorial: 3
3! = 6
SourceCode:
// C Program to check for prime number using Naive Approach
#include <stdio.h>
// Function to check prime number
void checkPrime(int N)
{
// initially, flag is set to true or 1
int flag = 1;
// loop to iterate through 2 to N/2
for (int i = 2; i <= N / 2; i++) {
// if N is perfectly divisible by i
// flag is set to 0 i.e false
if (N % i == 0) {
flag = 0;
break;
}
}
if (flag) {
printf("The number %d is a Prime Number\n", N);
}
else {
printf("The number %d is not a Prime Number\n", N);
}
return;
}
// driver code
int main()
{
int N = 546;
checkPrime(N);
return 0;
}
Output:
The number 546 is not a Prime Number
sine series.
SourceCode:
#include <stdio.h>
#include <math.h>
int fac(int x)
{
int i,fac=1;
for(i=1;i<=x;i++)
fac=fac*i;
return fac;
}
int main()
{
float x,Q,sum=0;
int i,j,limit;
printf("Enter the value of x of sinx series: ");
scanf("%f",&x);
printf("Enter the limit upto which you want to expand the series: ");
scanf("%d",&limit);
Q=x;
x = x*(3.1415/180);
for(i=1,j=1;i<=limit;i++,j=j+2)
{
if(i%2!=0)
{
sum=sum+pow(x,j)/fac(j);
}
else
sum=sum-pow(x,j)/fac(j);
}
printf("Sin(%0.1f): %f",Q,sum);
return 0;
}
Output:
Enter the value of x of sine series: 40
Enter the limit upto which you want to expand the series: 5
Sin(40.0): 0.642772
cos series.
SourceCode:
#include <stdio.h>
const double PI = 3.142;
//will return the sum of cos(x)
double series_sum(double x, int n) {
x = x * (PI / 180.0);
double result = 1;
double s = 1, fact = 1, pow = 1;
for (int i = 1; i < 5; i++) {
s = s * -1;
fact = fact * (2 * i - 1) * (2 * i);
pow = pow * x * x;
result = result + s * pow / fact;
}
return result;
}
//main function
int main() {
float x = 10;
int n = 3;
printf("%lf
", series_sum(x, n));
return 0;
}
Input: x = 10, n = 3
Output: 0.984804
Input: x = 8, n = 2
Output: 0.990266
SourceCode:
// C program to check whether
// a number is palindrome or not
#include <stdio.h>
// Driver code
int main()
{
// Define variables
// This is our given number
int original_number = 12321;
// This variable stored reversed digit
int reversed = 0;
int num = original_number;
// Execute a while loop to reverse
// digits of given number
while (num != 0)
{
int r = num % 10;
reversed = reversed * 10 + r;
num /= 10;
}
// Compare original_number with
// reversed number
if (original_number == reversed)
{
printf(" Given number %d is a palindrome number",original_number);
}
else
{
printf(" Given number %d is not a palindrome number",
original_number);
}
return 0;
}
SourceCode:
// C program to print right half pyramid pattern of star
#include <stdio.h>
int main()
{
int rows;
printf("Number of rows: ");
scanf("%d", &rows);
// first loop for printing rows
for (int i = 1; i <= rows; i++) {
// second loop for printing similar number in each
// rows
for (int j = 1; j <= i; j++) {
printf("%d ", i);
}
printf("\n");
}
return 0;
}
Input:
Number of rows: 5
Output:
1
22
333
4444
55555
UNIT III
WEEK 7:
Objective: Explore the full scope of Arrays construct namely defining and initializing
1-D and 2-D and more generically n-D arrays and referencing individual array
elements from the defined array. Using integer 1-D arrays, explore search solution
linear search.
Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7:1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.
SourceCode:
SourceCode:
#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("Enter 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;
}
Output:
SourceCode:
#include <stdio.h>
/* Function to reverse arr[] from start to end*/
void rvereseArray(int arr[], int start, int end)
{
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver function to test above functions */
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
rvereseArray(arr, 0, n - 1);
printf("Reversed array is \n");
printArray(arr, n);
return 0;
}
Output:
123456
Reversed array is
654321
SourceCode:
#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{
two[i] = one[i];
}
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s",num, two);
return 0;
}
Output:
Enter the binary number
1000010
Ones' complement of binary number 1000010 is 0111101
Two's complement of binary number 1000010 is 0111110
v) Eliminate duplicate elements in an array.
SourceCode:
#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]);
}
}
Output:
Enter size of the array
10
Enter Elements of the array:
1124356571
Entered element are:
1124356571
After deleting the duplicate element, the Array is:
1243567
WEEK 8:
Objective: Explore the difference between other arrays and character arrays that can
be used as Strings by using null character and get comfortable with string by doing
experiments that will reverse a string and concatenate two strings. Explore sorting
solution bubble sort using integer arrays.
Suggested Experiments/Activities:
Tutorial 8: 2 D arrays, sorting and Strings.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
SourceCode:
#include <stdio.h>
int main() {
// Declare a 2D array with 3 rows and 4 columns
int matrix[3][4];
// Assign values to the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = i * 4 + j;
}
}
// Print the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
0123
4567
8 9 10 11
SourceCode:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18
SourceCode:
// C program for implementation of Bubble sort
#include <stdio.h>
// Swap function
void swap(int* arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver code
int main()
{
int arr[] = { 5, 1, 4, 2, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
printf("Sorted array: ");
printArray(arr, N);
return 0;
}
Output:
Sorted array:
12458
v) Concatenate two strings without built-in functions
SourceCode:
// C Program to concatenate two
// strings without using built-in function
#include <stdio.h>
int main()
{
// Get the two Strings to be concatenated
char str1[100] = "Geeks", str2[100] = "World";
// Declare a new Strings
// to store the concatenated String
char str3[100];
int i = 0, j = 0;
printf("\n First string: %s", str1);
printf("\n Second string: %s", str2);
// Insert the first string
// in the new string
while (str1[i] != '\0') {
str3[j] = str1[i];
i++;
j++;
}
// Insert the second string
// in the new string
i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
// Print the concatenated string
printf("\n Concatenated string: %s", str3);
return 0;
}
SourceCode:
#include <stdio.h>
#include <string.h>
int main()
{
char Str[100], RevStr[100];
int i, j, len;
printf("\n Please Enter any String : ");
gets(Str);
j = 0;
len = strlen(Str);
for (i = len - 1; i >= 0; i--)
{
RevStr[j++] = Str[i];
}
RevStr[i] = '\0';
printf("\n String after Reversing = %s", RevStr);
return 0;
}
Input:
Please enter any string:Hello
Output:
String after Reversing: olleH
WEEK 9:
Objective: Explore pointers to manage a dynamic array of integers, including
memory allocation & value initialization, re-sizing changing and reordering the
contents of an array and memory de-allocation using malloc (), calloc (), realloc () and
free () functions. Gain experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereference.
i) Write a C program to find the sum of a 1D array using malloc()
SourceCode:
#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:
Enter limit of the array: 5
Enter element 01: 100
Enter element 02: 200
Enter element 03: 300
Enter element 04: 400
Enter element 05: 500
ii) Write a C program to find the total, average of n students using structures
SourceCode:
iii) Enter n students data using calloc() and display failed students list
SourceCode:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5
iv) Read student name and marks from the command line and display the
student details along with the total.
SourceCode:
SourceCode:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = (int*)realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
WEEK 10:
Objective: Experiment with C Structures, Unions, bit fields and self-referential
structures (Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bit fields, Self-Referential Structures, Linked lists
SourceCode:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num; //Data of the node
struct node *nextptr; //Address of the next node
}*stnode;
void createNodeList(int n); // function to create the list
void displayList(); // function to display the list
int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\
n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL) //check whether the fnnode is NULL and if so no memory
allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL; // links the address field to NULL
tmp = stnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);
fnNode->num = num; // links the num field of fnNode with num
fnNode->nextptr = NULL; // links the address field of fnNode with NULL
tmp->nextptr = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->nextptr;
}
}
}
}
void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}
Output:
SourceCode:
// C program to illustrate differences
// between structure and Union
#include <stdio.h>
#include <string.h>
// declaring structure
struct struct_example {
int integer;
float decimal;
char name[20];
};
// declaring union
union union_example {
int integer;
float decimal;
char name[20];
};
void main()
{
// creating variable for structure
// and initializing values difference
// six
struct struct_example s = { 18, 38, "geeksforgeeks" };
// creating variable for union
// and initializing values
union union_example u = { 18, 38, "geeksforgeeks" };
printf("structure data:\n integer: %d\n"
"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
printf("\nunion data:\n integer: %d\n"
"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
// difference two and three
printf("\nsizeof structure : %d\n", sizeof(s));
printf("sizeof union : %d\n", sizeof(u));
// difference five
printf("\n Accessing all members at a time:");
[Link] = 183;
[Link] = 90;
strcpy([Link], "geeksforgeeks");
printf("structure data:\n integer: %d\n "
"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
[Link] = 183;
[Link] = 90;
strcpy([Link], "geeksforgeeks");
printf("\nunion data:\n integer: %d\n "
"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
printf("\n Accessing one member at time:");
printf("\nstructure data:");
[Link] = 240;
printf("\ninteger: %d", [Link]);
[Link] = 120;
printf("\ndecimal: %f", [Link]);
strcpy([Link], "C programming");
printf("\nname: %s\n", [Link]);
printf("\n union data:");
[Link] = 240;
printf("\ninteger: %d", [Link]);
[Link] = 120;
printf("\ndecimal: %f", [Link]);
strcpy([Link], "C programming");
printf("\nname: %s\n", [Link]);
// difference four
printf("\nAltering a member value:\n");
[Link] = 1218;
printf("structure data:\n integer: %d\n ""decimal: %.2f\nname: %s\n",
[Link], [Link], [Link]);
[Link] = 1218;
printf("union data:\n integer: %d\n"" decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
}
Output:
structure data:
integer: 18
decimal: 38.00
name: geeksforgeeks
union data:
integer: 18
decimal: 0.00
name: _x0012_
sizeof structure : 28
sizeof union : 20
union data:
integer: 240
decimal: 120.000000
name: C programming
SourceCode:
#include <stdio.h>
#define INT_BITS 32
/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n
at last, do bitwise or of n<<d with n >>(INT_BITS -
d) */
return (n << d) | (n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
/* In n>>d, first d bits are 0. To put last 3 bits of at
first, do bitwise or of n>>d with n <<(INT_BITS- d) */
return (n >> d) | (n << (INT_BITS - d));
}
/* Driver program to test above functions */
void main()
{
int n = 16;
int d = 2;
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
printf(" Right Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
}
Output:
Left Rotation of 16 by 2 is 64 Right Rotation of 16 by 2 is 4
iv) Write a C program to copy one structure variable to another structure of the
same type.
SourceCode:
UNIT V
WEEK 11:
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing
some experiments by parameter passing using call by value. Basic methods of
numerical integration
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent,
Lab 11: Simple functions using call by value, solving differential equations using
Euler’s theorem.
i) Write a C function to calculate NCR value.
SourceCode:
#include <stdio.h>
int factorial(int n) {
if(n == 0)
return 1;
int factorial = 1;
for (int 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;
}
Input: N = 5, r = 2
Output: 10
ii) Write a C function to find the length of a string.
SourceCode:
// C program to find the length of string
#include <stdio.h>
#include <string.h>
int main()
{
char Str[1000];
int i;
printf("Enter the String: ");
scanf("%s", Str);
for (i = 0; Str[i] != '\0'; ++i);
printf("Length of Str is %d", i);
return 0;
}
Output:
Enter the String: Hello
Length of Str is 5
SourceCode:
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
// printing the matrix a[][]
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
// computing the transpose
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
// printing the transpose
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
Output:
Entered matrix:
1 4 0
-5 2 7
Transpose of the matrix:
1 -5
4 2
0 7
SourceCode:
#include<stdio.h>
#include<conio.h>
#define f(x,y) x+y
int main()
{
float x0, y0, xn, h, yn, slope;
int i, n;
clrscr();
printf("Enter Initial Condition\n");
printf("x0 = ");
scanf("%f", &x0);
printf("y0 = ");
scanf("%f", &y0);
printf("Enter calculation point xn = ");
scanf("%f", &xn);
printf("Enter number of steps: ");
scanf("%d", &n);
/* Calculating step size (h) */
h = (xn-x0)/n;
/* Euler's Method */
printf("\nx0\ty0\tslope\tyn\n");
printf("------------------------------\n");
for(i=0; i < n; i++)
{
slope = f(x0, y0);
yn = y0 + h * slope;
printf("%.4f\t%.4f\t%0.4f\t%.4f\n",x0,y0,slope,yn);
y0 = yn;
x0 = x0+h;
}
/* Displaying result */
printf("\nValue of y at x = %0.2f is %0.3f",xn, yn);
getch();
return 0;
}
Output:
Enter Initial Condition
x0 = 0
y0 = 1
Enter calculation point xn = 1
Enter number of steps: 10
x0 y0 slope yn
------------------------------
0.0000 1.0000 1.0000 1.1000
0.1000 1.1000 1.2000 1.2200
0.2000 1.2200 1.4200 1.3620
0.3000 1.3620 1.6620 1.5282
0.4000 1.5282 1.9282 1.7210
0.5000 1.7210 2.2210 1.9431
0.6000 1.9431 2.5431 2.1974
0.7000 2.1974 2.8974 2.4872
0.8000 2.4872 3.2872 2.8159
0.9000 2.8159 3.7159 3.1875
WEEK 12:
Objective: Explore how recursive solutions can be programmed by writing recursive
functions that can be invoked from the main by programming at-least five distinct
problems that have naturally recursive solutions.
Suggested Experiments/Activities:
Tutorial 12: Recursion, the structure of recursive calls
Lab 12: Recursive functions
i) Write a recursive function to generate Fibonacci series.
SourceCode:
#include<stdio.h>
int main()
{
int first=0, second=1, i, n, sum=0;
printf("Enter the number of terms: ");
scanf("%d",&n);
//accepting the terms
printf("Fibonacci Series:");
for(i=0 ; i<n ; i++)
{
if(i <= 1)
{
sum=i;
}
//to print 0 and 1
else
{
sum=first + second;
first=second;
second=sum;
//to calculate the remaining terms.
//value of first and second changes as a new term is printed.
}
printf(" %d",sum)
}
return 0;
}
Output:
Enter the number of terms:5
Fibonacci series:0 1 1 2 3
SourceCode:
#include <stdio.h>
// Function to return the
// minimum of two numbers
int Min(int Num1, int Num2)
{
return Num1 >= Num2
? Num2
: Num1;
}
// Utility function to calculate LCM
// of two numbers using recursion
int LCMUtil(int Num1, int Num2, int K)
{
// If either of the two numbers
// is 1, return their product
if (Num1 == 1 || Num2 == 1)
return Num1 * Num2;
// If both the numbers are equal
if (Num1 == Num2)
return Num1;
// If K is smaller than the
// minimum of the two numbers
if (K <= Min(Num1, Num2)) {
// Checks if both numbers are
// divisible by K or not
if (Num1 % K == 0 && Num2 % K == 0) {
// Recursively call LCM() function
return K * LCMUtil(
Num1 / K, Num2 / K, 2);
}
// Otherwise
else
return LCMUtil(Num1, Num2, K + 1);
}
// If K exceeds minimum
else
return Num1 * Num2;
}
// Function to calculate LCM
// of two numbers
void LCM(int N, int M)
{
// Stores LCM of two number
int lcm = LCMUtil(N, M, 2);
// Print LCM
printf("%d", lcm);
}
// Driver Code
int main()
{
// Given N & M
int N = 2, M = 4;
// Function Call
LCM(N, M);
return 0;
}
Input: N = 2, M = 4
Output: 4
iii) Write a recursive function to find the factorial of a number.
SourceCode:
// C program to find factorial
// of given number
#include <stdio.h>
// Driver code
int main()
{
int num = 5;
printf("Factorial of %d is %d",
num, factorial(num));
return 0;
}
Output:
Factorial of 5 is 120
iv) Write a C Program to implement Ackermann function using recursion.
SourceCode:
// C program to illustrate Ackermann function
#include <stdio.h>
int ack(int m, int n)
{
if (m == 0){
return n+1;
}
else if((m > 0) && (n == 0)){
return ack(m-1, 1);
}
else if((m > 0) && (n > 0)){
return ack(m-1, ack(m, n-1));
}
}
int main(){
int A;
A = ack(1, 2);
printf("%d", A);
return 0;
}
Output:
A (1, 2) = 4
SourceCode:
#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()*/
Output :
/* C program to find sum of Series : 1+2+3+4+....+N */
Enter number of terms : 15
Using Recursion ::
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120
WEEK 13:
Objective: Explore the basic difference between normal and pointer variables,
Arithmetic operations using pointers and passing variables to functions using pointers
Suggested Experiments/Activities:
Tutorial 13: Call by reference, dangling pointers
SourceCode:
#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:
Enter two numbers: 10 20
Before swapping in main
Value of num1 = 10
Value of num2 = 20
After swapping in swap function
Value of num1 = 20
Value of num2 = 10
After swapping in main
Value of num1 = 20
Value of num2 = 10
SourceCode:
#include<stdio.h>
int *fun()
{
static int x = 5;
return &x;
}
int main()
{
int *ptr = fun ();
printf ("%d", *ptr);
return 0;
}
Output:
5
iii) Write a C program to copy one string into another using pointer.
SourceCode:
#include<stdio.h>
#include<conio.h>
void main()
{
char *str1, *str2;
int i;
clrscr();
printf("Enter the string : ");
scanf("%s", str2);
for(i = 0; *str2 != '\0'; i++, str1++, str2++)
*str1 = *str2;
*str1 = '\0';
str1 = str1 - i;
printf("\nThe copied string is : %s", str1);
getch();
}
Output:
Enter the string : bhuvan
The copied string is : bhuvan
SourceCode:
#include <stdio.h>
int main()
{
//1
char inputString[100];
int upper Count, lower Count, special Count, digit Count, i;
//2
printf("Enter a String : ");
gets(inputString);
//3
printf("String input is %s ", inputString);
//4
Upper Count = lower Count = special Count = digit Count = 0;
//5
for (i = 0; inputString[i] != '\0'; i++)
{
//6
if (inputString[i] >= 'A' && inputString[i] <= 'Z')
{
upperCount++;
}
else if (inputString[i] >= 'a' && inputString[i] <= 'z')
{
lowerCount++;
}
else if (inputString[i] >= '0' && inputString[i] <= '9')
{
digitCount++;
}
else
{
specialCount++;
}
}
//7
printf("\nUpper case count : %d \n", upperCount);
printf("Lower case count : %d \n", lowerCount);
printf("Digit count : %d \n", digitCount);
printf("Special character count : %d \n", specialCount);
return 0;
}
Output :
Enter a String : Hello world 112@#$
String input is Hello world 112@#$
Upper case count : 1
Lower case count : 9
Digit count : 3
Special character count : 5
WEEK14:
Objective: To understand data files and file handling with various file I/O functions. Explore
the differences between text and binary files.
Suggested Experiments/Activities:
Tutorial 14: File handling
SourceCode:
#include< stdio.h >
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("\n Enter 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:
Enter file name to create : [Link]
File created successfully.
Data written successfully.
Contents of file is :
ABC
ii) Write a C program to write and read text into a binary file using fread() and
fwrite()
SourceCode:
#include<stdio.h>
int main()
{
FILE *fp = NULL;
short x[10] = {1,2,3,4,5,6,5000,6,-10,11};
short result[10];
int i;
fp=fopen("[Link]", "w+");
if(fp != NULL)
{
fwrite(x, sizeof(short), 10 /*20/2*/, fp);
rewind(fp);
fread(result, sizeof(short), 10 /*20/2*/, fp);
}
else
return 1;
printf("Result\n");
for (i = 0; i < 10; i++)
printf("%d = %d\n", i, (int)result[i]);
fclose(fp);
return 0;
}
output:
Result
0=1
1=2
2=3
3=4
4=5
5=6
6 = 5000
7=6
8 = -10
9 = 11
SourceCode:
#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:
Enter the filename to open for reading
[Link]
Enter the filename to open for writing
[Link]
Contents copied to [Link]
iv) Write a C program to merge two files into the third file using command-line
arguments.
SourceCode:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *sourceFile1;
FILE *sourceFile2;
FILE *destFile;
char sourcePath1[100];
char sourcePath2[100];
char destPath[100];
char ch;
/* Input path of files to merge to third file */
printf("Enter first source file path: ");
scanf("%s", sourcePath1);
printf("Enter second source file path: ");
scanf("%s", sourcePath2);
printf("Enter destination file path: ");
scanf("%s", destPath);
/*
* Open source files in 'r' and
* destination file in 'w' mode
*/
sourceFile1 = fopen(sourcePath1, "r");
sourceFile2 = fopen(sourcePath2, "r");
destFile = fopen(destPath, "w");
/* fopen() return NULL if unable to open file in given mode. */
if (sourceFile1 == NULL || sourceFile2 == NULL || destFile == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read/write privilege.\n");
exit(EXIT_FAILURE);
}
/* Copy contents of first file to destination */
while ((ch = fgetc(sourceFile1)) != EOF)
fputc(ch, destFile);
/* Copy contents of second file to destination */
while ((ch = fgetc(sourceFile2)) != EOF)
fputc(ch, destFile);
printf("\nFiles merged successfully to '%s'.\n", destPath);
/* Close files to release resources */
fclose(sourceFile1);
fclose(sourceFile2);
fclose(destFile);
return 0;
}
Output:
Enter first source file path: data\[Link]
Enter second source file path: data\[Link]
Enter destination file path: data\[Link]
Files merged successfully to 'data\[Link]'.
iv) Find no. of lines, words and characters in a file
SourceCode:
#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 words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
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;
}
SourceCode:
#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);
}
Output :
Enter the value of n : 4
.com