0% found this document useful (0 votes)
41 views

CP Lab Programs With Input and Output

C language

Uploaded by

meghana.sk0630
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)
41 views

CP Lab Programs With Input and Output

C language

Uploaded by

meghana.sk0630
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
You are on page 1/ 53

WEEK 1

1) Sample Programs on Flowchart design

1a) Installation and working Tool to draw Flowcharts (Like Flowgorithm, Raptor etc.)

INSTALLATION PROCESS OF FLOWGORITHM SOFTWARE

Overview

Flowgorithm is a popular flowchart tool. In this tutorial, we will download and install the Flowgorithm
flowchart tool on Windows operating system. This is a step-by-step guide to downloading and installing
the tool on a Windows machine.

 Download Flowgorithm
 Open a web browser.
 Navigate to the Flowgorithm official website.

http://www.flowgorithm.org/

Click on the Download tab.

Check the architecture type of the machine to download 32-bit or 64-bit installers. To download the
installer for 64-bit architecture, choose the 64-bit installer and download the file.

The filename would be Flowgorithm-<version>-Setup.


Extract the contents of the folder. Right-click on the folder and choose the Extract All… option.

Install Flowgorithm

The downloaded extracted folder contains the setup files. one is the .msi installer and the other one is
the setup.exe
To install the tool, double-click on the setup.exe file to install the tool. This will launch the install
wizard screen.

The Microsoft Defender might prevent you from running the setup. This is due to the fact that the intaller
is not signed.

The alternative is to click on the More info link. To proceed with the setup click on the Run
anyway button.
Norton File Insight

We have checked the Norton Rating of the Flowgorithm Installer. The rating is Good and
recommended for users by the Norton community.

This will launch the Flowgorithm Setup Wizard screen.

Click on the Next> button.


Read and Accept the End User License Agreement( EULA)

Click on the Next> button.

Accept the default location and click on the Next button to install the tool.

*Optional*

To customize the install location of the tool, click on the Browse… button. Choose the new location for
the tool.
1b) Draw a flowchart to perform arithmetic operations like – sum, average, product, difference,
quotient and remainder of given numbers.

START

INPUT FIRST NUMBER

READ FIRST NUMBER A

INPUT SECOND NUMBER

READ SECOND NUMBER B

COMPUTE SUM=A+B

COMPUTE AVG=SUM/2

COMPUTE PRODUCT =A*B

COMPUTE DIFFERENCE=A-B

COMPUTE QUOTIENT=A/B

COMPUTE REMAINDER=A%B

PRINT SUM, AVG, PRODUCT, DIFFERENCE,


QUOTIENT, REMAINDER
1c) Draw a flowchart to convert days into years, weeks and days.

START

INPUT DAYS

COMPUTE YEARS = DAYS/365

COMPUTE WEEKS = (DAYS % 365)/ 7


COMPUTE DAYS = (DAYS % 365)% 7

PRINT DAYS, WEEKS, YEARS

STOP
WEEK 2
2) Sample Programs on Flowchart design

2a) Draw a flowchart to read input name, marks of 5 subjects of a student and display the name of
the student, the total marks scored, percentage scored.

START

INPUT NAME

READ NAME STUDENT

INPUT 5 MARKS

READ SUB1, SUB2, SUB3, SUB4, SUB5

COMPUTE TOTAL = SUB1 + SUB2 + SUB3 + SUB4 + SUB5

COMPUTE PERCENTAGE = (TOTAL / 500) * 100

PRINT NAME, TOTAL, PERCENTAGE

STOP
2b) Draw a flowchart to find the largest and smallest among three entered numbers and also display
whether the identified largest/smallest number is even or odd.

START

INPUT THREE NUMBERS

READ A, B, C

No If A > B Yes

IF B > C IF A > C

LARGE = B LARGE = C LARGE = A

PRINT LARGE
PRINT ODD PRINT EVEN

2c) Draw a flow chart to check whether the given number is palindrome or not.

START

INPUT A NUMBER

READ NUMBER

REVERSE = 0

TEMPNUM = NUMBER

NO
NUMBER != 0

YES

REM = NUMBER % 10

REVERSE * = 10 + REM

NUMBER = NUMBER / 10

REVERSE =
YES
TEMPNUM

NO
WEEK 3
3) Sample Programs on C Tokens

3a) Write a C program to read the input(N) as floating-point number from the user and display the
number in one-, two- and three-digit floating point numbers. Example: If N = 12.345678, then the
output is 12.3, 12.34, 12.345.

/*Understanding floating-point program*/

# include <stdio.h>

void main ()

float num;

printf("Enter a float number: ");

scanf(“%f”,&num);

printf("You Entered: %f", num);

printf(“%f\n”,num);

printf("%0.1f\n", num);

printf("%0.2f\n", num);

printf("%0.3f\n", num);

OUTPUT:

1) Enter a float number: 12.3214

You Entered: 12.3214

12.3

12.32

12.321

2) Enter a float number: 32.4585

You Entered: 32.4585

32.4
32.46

32.459

3b) Write a C program to swap values of two variables with and without using third variable.

Using third variable

/*Swapping two variables using third variable */

#include<stdio.h>

void main()

int num1,num2,temp;

printf("Enter number1:");

scanf("%d",&num1);

printf("Enter number2:");

scanf("%d",&num2);

printf("Numbers before swapping:number1 = %d \t number2 =%d\n", num1,num2);

temp=num1;

num1=num2;

num2=temp;

printf("Numbers after swapping : number1 =%d\t number2 =%d \n " num1,num2);

OUTPUT:

1) Enter number1: 12

Enter number2: 15

Numbers before swapping: number1=12 number2=15

Numbers after swapping: number1=15 number2=12

2) Enter number1: -10

Enter number2: 15

Numbers before swapping: number1=-10 number2=15

Numbers after swapping: number1=15 number2=-10

ii) Swapping two variables, without using third variable

/*Swapping two variables without using third variable */

#include<stdio.h>

void main()

int num1,num2;
printf("Enter number1:");

scanf("%d",&num1);

printf("Enter number2:");

scanf("%d",&num2);

printf("Numbers before swapping: number1=%d\tnumber2=%d\n",num1,num2);

num1=num1+num2;

num2=num1-num2;

num1=num1-num2;

printf("Numbers after swapping:number1=%d\tnumber2=%d\n" , num1,num2);

1) Enter number1: 12

Enter OUTPUT:

number2: 15

Numbers before swapping: number1=12 number2=15

Numbers after swapping: number1=15 number2=12

2) Enter number1: -10

Enter number2: 15

Numbers before swapping: number1=-10 number2=15

Numbers after swapping: number1=15 number2=-10

3c) Write a C program to Calculate Simple and Compound Interest.

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

int main()
{
float p, t, r, si, ci;
clrscr();
printf("Enter principal amount (p): ");
scanf("%f", &p);
printf("Enter time in year (t): ");
scanf("%f", &t);
printf("Enter rate in percent (r): ");
scanf("%f", &r);
/* Calculating simple interest */
si = (p * t * r)/100.0;

/* Calculating compound interest */


ci = p * ((1+r/100)^ t) - 1);

printf("Simple Interest = %0.3f\n", si);


printf("Compound Interest = %0.3f", ci);
getch();
return(0);
}
OUTPUT:

Enter principal amount (p): 5000


Enter time in year (t): 2
Enter rate in percent (r): 18
Simple Interest = 1800.000
Compound Interest = 1962.000

WEEK 4
4) Sample Programs on Decision statements

4a) Formulate a C program to find whether a given year is a leap year or not.

/*Leap Year or Not*/

#include<stdio.h>

#include<conio.h>

void main()

int year;

printf("Enter a year: ");

scanf("%d", &year);

if((year%4==0&&year%100!=0)||year%400==0)

printf("%d is a leap year", year);

}
else

Printf(“%d is not a leap year”);

getch();

OUTPUT:

1. Enter a year: 2004

2004 is a leap year

2. Enter a year: 1700

1700 is not a leap year

4b) Write a program to compute grade of student using if else ladder.

The grades are assigned as followed:

Marks < 50 F

50≤marks< 60 C

60≤marks<70 B

70≤marks<80 B+

80≤marks<90 A

90≤marks<100 A+

/*To Compute Grade of a Student*/

#include<stdio.h>

void main()

unsigned short int marks;

printf("Enter marks(in range 0-100)of a student:") ;

scanf("%u",&marks);

if(marks>=0 && marks<=100)

if(marks>=90)

printf("Grade A+");

else if(marks>=80)

printf("Grade A");

else if(marks>=70)
printf("Grade B+");

else if(marks>=60)

printf("Grade B");

else if(marks>=50)

printf("Grade P");

else

printf("Fail");

Else

printf("Invalid marks");

OUTPUT:

Enter marks (in range 0-100) of a student: 30

Fail

4c) Write a program that presents the user a choice of 5 favorite drinks: (Coke, Water, Sprite, Juice,
and Milk). Then allow the user to choose a drink by entering a number 1-5. Output which drink they
chose. If the user enters a choice other than 1-5 then it will output "Error. Choice was not valid."

/*Write a program that presents the user a choice of 5 favourite drinks*/

#include<stdio.h>

#include<conio.h>

void main()

int choice;

printf("Menu:\n");

printf("1.coke\n");

printf("2.water\n");

printf("3.sprite\n");

printf("4.juice\n");

printf("5.milk\n");

printf("enter your choice:\n");

scanf("%d",&choice);

switch(choice)
{

case 1:

printf("coke");

break;

case 2:

printf("water");

break;

case 3:

printf("sprite");

break;

case 4:

printf("juice");

break;

case 5:

printf("milk");

break;

default:

printf("Error. Choice was not valid.");

break;

OUTPUT:

Test 1:

Menu:

1. Coke

2. Water

3. Juice

4. Sprite

5. Milk

enter your choice:

Coke

enter your choice:


6

Error. Choice was not valid.

WEEK 5
5) Sample Programs on Loop statements

5a) Ramya is learning about units and tens digit in school. Her teacher gives a task to find the sum of
the ones and tens digit of any given number.

Example: Given number N = 2456, number 6 is in one’s position and the number 5 is at tens position.
Sum of the digits at one’s position and tens position in the given number is: 6 + 5 = 11.

Write a C program that finds the sum of the digits at ones and tens position in the given number.

#include<stdio.h>

void main()

int num,temp,ones_digit,tens_digit,sum=0;

printf("Enter your number:");

scanf("%d",&num);

temp=num;

ones_digit=temp%10;

temp=temp/10;

tens_digit=temp%10;

temp=temp/10;

printf("One's digit of %d is %d\n",num,ones_digit);

printf("Ten's digit of %d is %d\n",num,tens_digit);

sum=ones_digit+tens_digit;

printf("Sum of One's digit and Ten's digit of %d is %d \n",num, sum);

}
OUTPUT:

Enter your number:4567

One's digit of 4567 is 7

Ten's digit of 4567 IS 6

Sum of One's digit and Ten's digit of 4567 is 13

5b) Develop a C program to generate first n terms of Fibonacci series.

#include<stdio.h>

void main()

int f1=0,f2=1,f,num,i;

printf("Enter number of terms:");

scanf("%d",&num);

printf("The first %d terms of Fibonacci series are:", num);

printf("%d\t%d\t",f1,f2);

for(i=2;i<num;i++)

f=f1+f2;

printf("%d\t",f);

f1=f2;

f2=f;

}
OUTPUT:
Enter n Value: 5

01123

5c) Develop a C Program to find the Sum of Series

SUM=1-x2/2! +x4/4!-x6/6!+x8/8!- x10/10!

#include <stdio.h>

#include <math.h>

// Function to calculate the factorial of a number

double factorial(int n) {

if (n == 0 || n == 1) {

return 1;

} else {

return n * factorial(n - 1);

double calculateTerm(int n, double x) {

// Function to calculate each term in the series


double term = pow(-1, n) * pow(x, 2 * n) / factorial(2 * n + 2); // Use factorial function

return term;

int main() {
int i,terms;

double x, sum = 1.0; // Start with the first term of the series

// Input values
printf("Enter the value of x: ");

scanf("%lf", &x);

printf("Enter the number of terms in the series: ");

scanf("%d", &terms);

// Calculate the sum of the series

for (i = 1; i < terms; ++i) { // Start the loop from 1

sum += calculateTerm(i, x);

// Display the result


printf("The sum of the series is: %.4f\n", sum);
return 0;

}
OUTPUT:

Enter the number of terms in the series: 8


Sum of 8 series is 2.718254

Enter the number of terms in the series: 7


Sum of 7 series is 2.718056
Enter the number of terms in the series: 10
Sum of 10 series is 2.718282

WEEK 6
6. Sample Programs on Nested Loop statements

6a) Design a C Program that prints the Floyd triangle in ‘n’ rows.

Example: If n = 4

23

456

7 8 9 10

#include<stdio.h>

#include<conio.h>

void main()

int i,j,k=1;

clrscr();

for(i=1;i<=4;i++)

for(j=1;j<=4-i;j++)

printf(" ");

}
for(j=1;j<=i;j++)

printf("%d ",k++);

printf("\n");

}
}
OUTPUT:
1

23

456

7 8 9 10

6b) Design a C program to generate pyramid of numbers.

131

13531

#include<stdio.h>

#include<conio.h>

void main()

{
int rows,i,space,j,num;

// Input the number of rows for the pyramid

//printf("Enter the number of rows: ");

//scanf("%d", &rows);

// Check if the number of rows is greater than 0

clrscr();

for (i = 1; i <= 3/*rows*/; i++)

num = 1;

// Leading spaces

for (space = 1; space <= 3/*rows*/ - i; space++)

printf(" ");

}
// Left side of the pyramid

for (j = 1; j <= i; j++)

printf("%3d", num);

num += 2;

}
// Right side of the pyramid

num -= 4;

for (j = 1; j < i; j++)

printf("%3d", num);

num -= 2;

printf("\n");

}
OUTPUT:

131

13531

6c) Design a program in C to display the following diamond pattern.

Design a program in C to display the following diamond pattern.

*
***

*****
*******
*********
*******
*****

***
*
#include<stdio.h>

#include<conio.h>

void main()

int i,j;

clrscr();

for(i=1;i<=5;i++)

for(j=1;j<=5-i;j++)

printf(" ");

for(j=1;j<=2*i-1;j++)

printf("*");

printf("\n");

for(i=4;i>=1;i--)

{
for(j=1;j<=5-i;j++)

printf(" ");
}

for(j=1;j<=2*i-1;j++)

printf("*");

printf("\n");

}
OUTPUT:

***
*****
*******
*********
*******

*****
***
*
WEEK 7
7. Sample Programs on arrays
7a. Construct a program which finds the kth smallest element among the given set of elements.
#include<stdio.h>
#define MAX 100

void main()
{
int a[MAX],i,n,j,kth,temp,pos;
printf("Enter how many values you want to read : ");
scanf("%d",&n);
for(i=0; i<n; i++)
{

printf("Enter the value of a[%d] : ",i );


scanf("%d",&a[i]);
}
printf("Enter which smallest element you want: ");
scanf("%d",&kth); for(i=0; i<n; i++)

{
pos=i;
for(j=i+1; j<n; j++) if(a[j]<a[pos])
{
pos=j;

}
temp=a[i]; a[i]=a[pos]; a[pos]=temp;
}
printf("%d is the %dth smallest element",a[kth],kth);

}
OUTPUT:

Enter how many values you want to read: 5


Enter the value of a[0] : 20
Enter the value of a[1] : 30
Enter the value of a[2] : 16
Enter the value of a[3] : 15
Enter the value of a[4] : 1
which smallest element you want: 2
16 is the 2th smallest element
Enter how many values you want to read: 6

Enter the value of a[0] : 32

Enter the value of a[1] : 65

Enter the value of a[2] : 98

Enter the value of a[3] : 74

Enter the value of a[4] : 12

Enter the value of a[5] : 15

Enter which smallest element you want: 4

74 is the 4th smallest element

7b. Several people are standing in a row and need to be divided into two teams. The first person goes
into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and
so on. You are given an array of positive integers (the weights of the people). Return an array of two
integers, where the first element is the total weight of team 1, and the second element is the total
weight of team 2 after the division is complete.

Write a C program that finds the weight of team 1 and team 2 after the division for the above
scenario.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,wt1,wt2;

clrscr();
printf("how many number of elements u want\n");
scanf("%d",&n);
printf("enter elements into the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]); wt1=wt2=0;
for(i=0;i<n;i++)
{
if(a[i]%2==0)
wt1+=a[i];
else
wt2+=a[i];
}
printf("sum of team1 = %d and team 2 = %d\n",wt1,wt2);

}
OUTPUT:

how many number of elements u want

enter elements into the array

12345

sum of team1 = 6 and team 2 = 9

7c. Write a program in C to find the multiplication of two matrices.


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

int A[10][10],B[10][10],C[10][10],r1,c1,r2,c2,i,j,k;

system("cls");

printf("enter the number of rows and cols of matrix A=");


scanf("%d%d",&r1,&c1);

printf("enter the number of rows and col of matrix B=");


scanf("%d%d",&r2,&c2);
if(r2==c1)
{
printf("enter the first matrix element=\n"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("enter the second matrix element=\n"); for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{

scanf("%d",&B[i][j]);
}
}
printf("multiply of the matrix=\n"); for(i=0;i<r1;i++)
{

for(j=0;j<c2;j++)
{ C[i][j]=0;
for(k=0;k<c1;k++)
{ C[i][j]+=A[i][k]*B[k][j];
}

}
}
//for printing result for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)

{
printf("%d\t",C[i][j]);
}
printf("\n");
}

}
else
{

printf("matrix multiplication is not possible\n");

}
OUTPUT:
enter the number of rows and cols of matrix A=2 3

enter the number of rows and col of matrix B=3 2

enter the first matrix element=

123

456

enter the second matrix element=

78

9 10

11 12

multiply of the matrix=

58 4
139 4

8. Sample Programs on string

8a) Write a C program to Insert a sub string into a given main string from a given position.

#include <stdio.h>

#include <string.h>

int main()

char a[30], b[30], c[30];

int pos = 0, i = 0, l, la, lb, lc, j;

puts("Enter a string");

gets(a);

puts("Enter sub string");

gets(b);

puts("enter position for insertion");

scanf("%d", &pos);

la = strlen(a);

lb = strlen(b);

l = pos + lb;

lc = la + lb;
for (i = 0; i < pos; i++)

c[i] = a[i];

j = 0;

for (i = pos; i <= l; i++)

c[i] = b[j];

j++;

j = pos;

for (i = l; i < lc; i++)

c[i] = a[j];

j++;

c[i] = '\0';

puts("String after Insertion is:");

printf("%s", c);

return 0;

OUTPUT:

Enter a string

Hello World

Enter sub string

, beautiful

enter position for insertion

String after Insertion is:

Hello, beautiful World

8b) Write a C program to determine if given string is palindrome or not.


#include <stdio.h>

#include <string.h>

int main()

char str[100]; int i, len, flag; flag = 0;

printf("\n Please Enter any String : ");

gets(str);

len = strlen(str);

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

if(str[i] != str[len - i - 1])

flag = 1;

break;

if(flag == 0)

printf("\n %s is a Palindrome String", str);

else

printf("\n %s is Not a Palindrome String", str);

return 0;

OUTPUT:

Please Enter any String:

level

level is a Palindrome String

8C) Given a string, return the character that appears the minimum number of times in the string. The
string will contain only ascii characters, from the ranges (“a”-”z”,”A”-”Z”,0-9), and case matters. If there
is a tie in the minimum number of times a character appears in the string return the character that
appears first in the string.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include<conio.h>

char findMinFrequencyChar(const char *str) {

int count[128] = {0}; // Assuming ASCII characters

// Count the frequency of each character in the string

int i,j;

char minChar = '\0';

int minFreq = -1;

clrscr();

for (i = 0; str[i] != '\0'; ++i) {

if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0' && str[i] <= '9'))

count[(int)str[i]]++;

// Find the character with the minimum frequency


for (j = 0; j < 128; ++j) {

if ((count[j] > 0) && ((minFreq == -1) || (count[j] < minFreq))) {

minChar = (char)j;

minFreq = count[j];

return minChar;

int main() {

char *input = (char *)malloc(1000000 * sizeof(char)); // Dynamic memory allocation

if (input == NULL) {

fprintf(stderr, "Memory allocation failed\n");

return 1;
}

// Input the string

scanf("%s", input);

// Find and output the character with the minimum frequency

printf("%c\n", findMinFrequencyChar(input));

// Free dynamically allocated memory

free(input);

getch();

return 0;

OUTPUT:

hello world

WEEK 9

9. Sample Programs on Functions

9a) Create a calculator that takes a number, a basic math operator (+, -, *, /, ^), and a second number all from user
input, and have it print the result of the mathematical operation. The mathematical operations should be
wrapped inside of functions.

#include <stdio.h>

#include <math.h>

// Function to add two numbers

double add(double num1, double num2)

return num1 + num2;

}
// Function to subtract second number from the first double
subtract(double num1, double num2)

return num1 - num2;


}

// Function to multiply two numbers

double multiply(double num1, double num2)

return num1 * num2;

// Function to divide first number by the second

double divide(double num1, double num2)

if (num2 != 0)

return num1 / num2;

else

printf("Error: Division by zero!\n"); return 0.0;

// Function to calculate the power of a number

double power(double base, double exponent)

return pow(base, exponent);

int main() {

double num1, num2, result; char operator;

// Get input from the user

printf("Enter first number: ");

scanf("%lf", &num1);

printf("Enter operator (+, -, *, /, ^): ");

scanf(" %c", &operator);

printf("Enter second number: ");

scanf("%lf", &num2);

// Perform the corresponding operation

switch (operator)
{

case '+':

result = add(num1, num2);

break;

case '-':

result = subtract(num1, num2);

break;

case '*':

result = multiply(num1, num2);

break;

case '/':

result = divide(num1, num2);

break;

case '^':

result = power(num1, num2);

break;

default:

printf("Error: Invalid operator\n");

return 1; // Exit with an error code

// Print the result

printf("Result: %.2lf\n", result);

return 0; // Exit successfully

OUTPUT:

Enter first number: 5

Enter operator (+, -, *, /, ^): *

Enter second number: 3

Result: 15.00

9b) Write a C program that accepts a decimal number and display its binary representation using user defined
functions.

#include<stdio.h>

#include<stdlib.h>

int main()
{

int a[10],n,i;

system ("cls");

printf("Enter the number to convert: ");

scanf("%d",&n);

for(i=0;n>0;i++)

a[i]=n%2;

n=n/2;

printf("\nBinary of Given Number is=");

for(i=i-1;i>=0;i--)

printf("%d",a[i]);

return 0;

OUTPUT:

Enter the number to convert: 19

Binary of Given Number is=10011

9c) Write a c Program to find the sum of a five-digit number using command line arguments.

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

if (argc != 2) {

printf("Usage: %s <five-digit-number>\n", argv[0]);

return 1; // Return an error code

int num = atoi(argv[1]); // Convert the command line argument to an integer

if (num < 10000 || num > 99999) {

printf("Please enter a valid five-digit number.\n");

return 1; // Return an error code


}

int sum = 0;

while (num != 0) {

sum += num % 10;

num /= 10;

printf("Sum of the digits: %d\n", sum);

return 0; // Return successfully

OUTPUT:

./program_name 12345

Sum of the digits: 15

WEEK 10

10. Sample Programs on pointers and structures

10 a) Write a C program to implement pointer arithmetic.

#include<stdio.h>

int main()

int no1,no2;

int *ptr1,*ptr2;

int sum,sub,mult;

float div;

printf("Enter number1:\n");

scanf("%d",&no1);

printf("Enter number2:\n");

scanf("%d",&no2);

ptr1=&no1;//ptr1 stores address of no1

ptr2=&no2;//ptr2 stores address of no2


sum=(*ptr1) + (*ptr2);

sub=(*ptr1) - (*ptr2);

mult=(*ptr1) * (*ptr2);

div=(*ptr1) / (*ptr2);

printf("sum= %d\n",sum);

printf("subtraction= %d\n",sub);

printf("Multiplication= %d\n",mult);

printf("Division= %f\n",div);

return 0;

OUTPUT:

Enter number1:

10

Enter number2:

sum= 15

subtraction= 5

Multiplication= 50

Division= 2.000000

10 b) Define a structure called cricket that describes the following information: Player name, team
name and batting average Using the structure Cricket, declare an array player and write a C program
that reads information about all the players and print team-wise list containing names of players
with their batting average?

#include <stdio.h>

#define N 100

// STRUCTURE DECLARATION

typedef struct

char playerName[20];

char teamName[20];

int battingAvg;

} cricket;

int main()
{

int n, i;

cricket player[N]; // Fix: Removed the extra closing brace

printf("Enter no.of players(n):\n");

scanf("%d", &n);

printf("Enter players' details (name, team, attingAvg):\n");

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

printf("\n Player %d \n", i + 1);

printf("Enter name of the Player:\n");

scanf("%s", player[i].playerName);

printf("Enter team name:\n");

scanf("%s", player[i].teamName);

printf("Enter batting average:\n");

scanf("%d", &player[i].battingAvg); // Fix: Use %f for float

printf("\n\n PLAYER'S NAME TEAM NAME BATTING AVERAGE \n");

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

printf("%s\t\t %s\t\t %d \n", player[i].playerName, player[i].teamName, player[i].battingAvg);

return 0;

OUTPUT:

Enter no.of players(n):

Enter players' details (name, team, battingAvg):

Player 1

Enter name of the Player:


John

Enter team name:

TeamA

Enter batting average:

45

Player 2

Enter name of the Player:

Alice

Enter team name:

TeamB

Enter batting average:

32

Player 3

Enter name of the Player:

Bob

Enter team name:

TeamA

Enter batting average:

38

PLAYER'S NAME TEAM NAME BATTING AVERAGE

John TeamA 45

Alice TeamB 32

Bob TeamA 38
WEEK 11

11 a) Write a C program to print the bill details of ‘N’ number of customers with the following data:
meter number, customer name, no of units consumed, bill date, last date to deposit and city. The
bill is to be calculated according to the following conditions: No. of units Charges For first 100 units
Rs.0.75 per unit for the next 200 units Rs.1.80 per unit for the next 200 units Rs. 2.75 per unit.

#include <stdio.h>

#define N 100

// Structure to store customer details

typedef struct {

int meterNumber;

char customerName[50];

int unitsConsumed;

char billDate[15];

char lastDate[15];

char city[20];

} Customer;

Customer customers[N];

// Function to calculate the bill based on the given conditions

float calculateBill(int units) {

float bill = 0.0;

if (units <= 100) {

bill = units * 0.75;

} else if (units <= 300) {

bill = 100 * 0.75 + (units - 100) * 1.80;

} else {

bill = 100 * 0.75 + 200 * 1.80 + (units - 300) * 2.75;

return bill;

int main() {
int n,i;

printf("Enter the number of customers (n): ");

scanf("%d", &n);

// Input details for each customer

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

printf("\nCustomer %d details:\n", i + 1);

printf("Meter Number: ");

scanf("%d", &customers[i].meterNumber);

printf("Customer Name: ");

scanf("%s", customers[i].customerName);

printf("Units Consumed: ");

scanf("%d", &customers[i].unitsConsumed);

printf("Bill Date: ");

scanf("%s", customers[i].billDate);

printf("Last Date to Deposit: ");

scanf("%s", customers[i].lastDate);

printf("City: ");

scanf("%s", customers[i].city);

// Print bill details for each customer

printf("\n\nBill Details:\n");

printf("%-15s %-20s %-20s %-15s %-15s %-10s %-10s\n", "Meter Number", "Customer Name",
"Units Consumed", "Bill Date", "Last Date", "City", "Bill Amount");

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

float billAmount = calculateBill(customers[i].unitsConsumed);

printf("%-15d %-20s %-20d %-15s %-15s %-10s %-10.2f\n",

customers[i].meterNumber, customers[i].customerName, customers[i].unitsConsumed,

customers[i].billDate, customers[i].lastDate, customers[i].city, billAmount);

}
return 0;

OUTPUT:

Enter the number of customers (n): 2

Customer 1 details:

Meter Number: 123

Customer Name: Prabhu

Units Consumed: 150

Bill Date: 2023-01-01

Last Date to Deposit: 2023-01-15

City: Anantapur

Customer 2 details:

Meter Number: 456

Customer Name: Kalyan

Units Consumed: 250

Bill Date: 2023-01-02

Last Date to Deposit: 2023-01-16

City: Hindupur

Bill Details:

Meter Number Customer Name Units Consumed Bill Date Last Date City Bill Amount

123 Prabhu 150 2023-01-01 2023-01-15 Anantapur 168.75

456 Kalyan 250 2023-01-02 2023-01-16 Hindupur 347.50

11 b) Write a C program that takes input for a student’s credits and marks to determine whether
the student is eligible for promotion to the nest year and calculate their CGPA.

#include <stdio.h>
// Function to determine eligibility and calculate CGPA

void calculatePromotionAndCGPA(int credits, float marks)

{
float cgpa;

if (marks >= 40.0 && credits >= 25)


{

printf("Congratulations! You are eligible for promotion to the next year.\n");

// Calculate CGPA (assuming a simple formula)

cgpa = marks / 10.0;

printf("Your CGPA is: %.2f\n", cgpa);

Else

printf("Sorry, you are not eligible for promotion to the next year.\n");

int main() {

int credits;

float marks;

// Input for student's credits

printf("Enter the number of credits: ");

scanf("%d", &credits);

// Input for student's marks

printf("Enter the marks: ");

scanf("%f", &marks);

// Calculate promotion eligibility and CGPA

calculatePromotionAndCGPA(credits, marks);

return 0;

OUTPUT:

Enter the number of credits: 30

Enter the marks: 50

Congratulations! You are eligible for promotion to the next year.

Your CGPA is: 5.00


WEEK 12
12. Sample Programs on Files

12 a) Write a C program to write and read 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;

OUTPUT:

Enter file name to create: example.txt

File created successfully.

Data written successfully.

Contents of file is :

ABC

ABC

12 b) 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;

}
OUTPUT:
Enter the filename to open for reading:
input.txt
Enter the filename to open for writing:
output.txt
Contents copied to output.txt

12 c) Write a C program to merge two files into the third file using command-line arguments.

#include <stdio.h>

#include <stdlib.h>

int main()

// Open two files to be merged

FILE *fp1 = fopen("file1.txt", "r");

FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result

FILE *fp3 = fopen("file3.txt", "w");

char c;

if (fp1 == NULL || fp2 == NULL || fp3 == NULL)

puts("Could not open files");

exit(0);

// Copy contents of first file to file3.txt

while ((c = fgetc(fp1)) != EOF)

fputc(c, fp3);

// Copy contents of second file to file3.txt

while ((c = fgetc(fp2)) != EOF)

fputc(c, fp3);
printf("Merged file1.txt and file2.txt into file3.txt");

fclose(fp

1);

fclose(fp

2);

fclose(fp

3);

return 0;

}
OUTPUT:

Assume file1.txt contains: Hello,

Assume file2.txt contains: World!

Hello,World!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy