[go: up one dir, main page]

0% found this document useful (0 votes)
51 views25 pages

CP 24-25 Programs

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)
51 views25 pages

CP 24-25 Programs

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/ 25

/* Exp 1: Program to demonstrate functions like printf(), scanf(), getchar(), putchar(),

gets(), puts() */

#include<stdio.h>
#include<conio.h>
void main()
{
int division;
int roll_number,total_marks;
char name[50];
float percentage;
clrscr();
printf("\n Enter students name : ");
//scanf("%s",name);
gets(name);
printf(" Enter students division : ");
//scanf("%c",&division);
division=getchar();
printf(" Enter students roll number : ");
scanf("%d",&roll_number);
printf(" Enter students total marks : ");
scanf("%d",&total_marks);
percentage=total_marks/6.0;
printf("\n\n Details entered by you : \n\n");
// printf(" Students name : %s \n",name);
printf(" Students name : ");
puts(name);
// printf(" Students division : %c \n",division);
printf(" Students division : ");
putchar(division);
printf("\n Students roll number : %d",roll_number);
printf("\n Students percentage : %.2f",percentage);
getch();
}

// Output
// Exp 2: C program to demonstrate various operators
#include<stdio.h>
#include<conio.h>
void main()
{
int a=13,b=4,c=8,d=156,lowest;
clrscr();

printf("\n Arithmatic operators \n");


printf(" %d + %d = %d \n",a,b,a+b);
printf(" %d - %d = %d \n",a,b,a-b);
printf(" %d * %d = %d \n",a,b,a*b);
printf(" %d / %d = %d \n",a,b,a/b);
printf(" %d %% %d = %d \n",a,b,a%b);

printf("\n Relational operators \n");


if(a>b)
printf(" %d is greater than %d",a,b);
else // b>a
printf(" %d is greater than %d",b,a);
if(a<b)
printf("\n %d is less than %d",a,b);
else // b<a
printf("\n %d is less than %d",b,a);
if(a==b)
printf("\n Both a and b are equal");
else // a!=b
printf("\n %d and %d are not equal",a,b);

printf("\n\n Logical operators ");


if(a>b && a>c)
printf("\n %d is greater than %d and %d",a,b,c);
if(c>a || c>b)
printf("\n %d is greater than either %d or %d",c,a,b);

printf("\n\n Bitwise operators ");


printf("\n Bitwise AND %d & %d = %d",a,b,a&b);
printf("\n Bitwise OR %d | %d = %d",a,b,a|b);
printf("\n Bitwise EX-OR %d ^ %d = %d",a,b,a^b);
printf("\n Bitwise LEFT SHIFT %d << %d = %d",c,b,c<<b);
printf("\n Bitwise RIGHT SHIFT %d >> %d = %d",d,b,d>>b);
printf("\n Bitwise NOT of %d = %d",c,~c);

printf("\n\n Ternary/Conditional operator ");


lowest = a<b ? ( a<c ? a:c ) : ( b<c ? b:c );
printf("\n Lowest number between %d, %d, and %d is %d",a,b,c,lowest);
getch();
}
// Output
// Ex 3: Program demonstrating nested if elese construct
#include<stdio.h>
#include<conio.h>
void main()
{
int score;
clrscr();
printf("Enter the student's score (between 0 to 100 only): ");
scanf("%d", &score);
// Check if the score is within the valid range
if (score < 0 || score > 100)
{
printf("Invalid score! Please enter a score between 0 and 100.\n");
getch();
return 1; // Exit the program with an error code
}
// Assign grade based on score
if (score >= 90 && score <= 100)
{
printf("Your Grade: A\n");
}
else if (score >= 80 && score <= 89)
{
printf("Your Grade: B\n");
}
else if (score >= 70 && score <= 79)
{
printf("Your Grade: C\n");
}
else if (score >= 60 && score <= 69)
{
printf("Your Grade: D\n");
}
else if (score >= 50 && score <= 59)
{
printf("Your Grade: E\n");
}
else
{
printf("Your Grade: F. You have failed!!\n");
}
getch();
}

//Output
//Exp4: C Program to demonstrate switch case construct
#include <stdio.h>
#include<conio.h>
void main()
{
int score;
clrscr();

printf("Enter the student's score (between 0 to 100 only): ");


scanf("%d", &score);

// Check if the score is within the valid range


if (score < 0 || score > 100)
{
printf("Invalid score! Please enter a score between 0 and 100.\n");
getch();
return 1; // Exit the program with an error code
}

// Divide the score by 10 to get a simplified range for switch-case


switch (score / 10)
{
case 10: // for score 100
case 9:
printf("Grade: A\n");
break;
case 8:
printf("Grade: B\n");
break;
case 7:
printf("Grade: C\n");
break;
case 6:
printf("Grade: D\n");
break;
case 5:
printf("Grade: E\n");
break;
default:
printf("Grade: F\n");
break;
}

getch();
}
// Output
//Exp 5: Armstrong number using while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int n, n1, rem,num=0;
clrscr();
printf(" Enter a positive integer: ");
scanf("%d",&n);
n1=n;
while(n1!=0)
{
rem=n1%10;
num+=rem*rem*rem;
n1/=10;
}
if(num==n)
printf("\n %d is an Armstrong number.",n);
else
printf("\n %d is not an Armstrong number.",n);
getch();
}

// Output
//Exp 6: Armstrong number using do-while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int n, n1, rem,num=0;
clrscr();
printf(" Enter a positive integer: ");
scanf("%d",&n);
n1=n;
do
{
rem=n1%10;
num+=rem*rem*rem;
n1/=10;
}while(n1!=0);
if(num==n)
printf("\n %d is an Armstrong number.",n);
else
printf("\n %d is not an Armstrong number.",n);
getch();
}

// Output
// Exp7: Program to generate multiplication table of user entered number
#include<stdio.h>
#include<conio.h>

void main()
{
int num, i;
clrscr();

// Asking user to input a number


printf("Enter a number to generate its multiplication table: ");
scanf("%d", &num);

// Generating table using a for loop


printf("Multiplication table of %d:\n", num);
for(i = 1; i <= 12; i++)
{
printf("%d x %d = %d\n", num, i, num * i);
}

getch();
}

//Output
//Exp8: Program to demonstrate continue statement

#include<stdio.h>
#include<conio.h>
void main()
{
int num, choice, i;
clrscr();

// Asking user for input


printf("Enter a number up to which you want to print: ");
scanf("%d", &num);

// Asking the user to choose between odd or even numbers


printf("Choose:\n1. Even numbers\n2. Odd numbers\n");
scanf("%d", &choice);

// Print even or odd numbers based on user choice


if (choice == 1)
{
printf("Even numbers up to %d are:\n", num);
for (i = 1; i <= num; i++)
{
if (i % 2 != 0)
{
continue; // Skip odd numbers
}
printf("%d ", i);
}
}
else if (choice == 2)
{
printf("Odd numbers up to %d are:\n", num);
for (i = 1; i <= num; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
printf("%d ", i);
}
}
else
{
printf("Invalid choice! Please select 1 for even or 2 for odd numbers.\n");
}
getch();
}
// Output
//Exp9: Program to demonstrate call by value and call by reference
#include<stdio.h>
#include<conio.h>
// Function to swap numbers using call by value
void swapByValue(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("After swapping (Call by Value): a = %d, b = %d\n", a, b);
}

// Function to swap numbers using call by reference


void swapByReference(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

void main()
{
int num1, num2;
clrscr();

// Input two numbers from user


printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

// Original numbers
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

// Call by value
swapByValue(num1, num2);
// The original numbers remain unchanged after call by value
printf("After Call by Value (Main): num1 = %d, num2 = %d\n", num1, num2);

// Call by reference
swapByReference(&num1, &num2);
// The original numbers are swapped after call by reference
printf("After Call by Reference (Main): num1 = %d, num2 = %d\n", num1, num2);

getch();
}
// Output

Explanation:

1. swapByValue:
o This function takes two integers as arguments.
o Inside the function, the values are swapped, but the change does not reflect
outside the function because it's call by value.
2. swapByReference:
o This function takes two pointers to integers as arguments (int *a, int *b).
o It swaps the values at the memory locations pointed to by the pointers, directly
changing the original variables in the main function.
/*Exp10: Program to find sum of first n natural numbers using recursion*/

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

// Recursive function to find the sum of natural numbers


int sumOfNaturalNumbers(int n)
{
if (n == 0)
{
return 0; // Base case: if n is 0, return 0
}
else
{
return n + sumOfNaturalNumbers(n - 1); // Recursive case
}
}

void main()
{
int n,sum;
clrscr();
// Input number from user
printf("Enter a number: ");
scanf("%d", &n);

// Calling recursive function to find the sum


sum = sumOfNaturalNumbers(n);

// Output the sum


printf("Sum of first %d natural numbers is: %d\n", n, sum);

getch();
}

// Output
/*Exp11: Program to find GCD of two numbers by using Recursion*/
#include<stdio.h>
#include<conio.h>
// Recursive function to find GCD of two numbers
int gcd(int a, int b)
{
if (b == 0)
{
return a; /* Base case: if second number becomes 0, return first number*/
}
else {
return gcd(b, a % b); // Recursive case
}
}

void main()
{
int num1, num2,result;
clrscr();
// Input two numbers from user
printf(" Enter two numbers: ");
scanf("%d %d", &num1, &num2);

// Calling the recursive function to find GCD


result = gcd(num1, num2);

// Output the GCD


printf(" GCD of %d and %d is: %d\n", num1, num2, result);
getch();
}

//Output
//Exp12: Program to find minimum and maximum number in an array
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, min, max, arr[15];
clrscr();
// Input the size of the array
printf("Enter the number of elements in the array(max 15): ");
scanf("%d", &n);

// Input the elements of the array


printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// Initialize min and max with the first element


min = arr[0];
max = arr[0];

// Traverse the array to find min and max


for (i = 1; i < n; i++)
{
if (arr[i] < min)
{
min = arr[i]; // Update min if the current element is smaller
}
if (arr[i] > max)
{
max = arr[i]; // Update max if the current element is larger
}
}

// Output the result


printf("Minimum element in the array: %d\n", min);
printf("Maximum element in the array: %d\n", max);
getch();
}

// Output
/* Exp13: Program to find length of a string and comparing two strings
without using standard string functions like strlen(), strcmp() */
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[50], str2[50];
int i=0, j=0, k=0, same=0, len1, len2;
clrscr();
//string length finding
printf("\n Enter any string : ");
gets(str1);
while(str1[i]!='\0')
i++;
len1=i;
printf("\n Length of entered string '%s' is %d",str1,len1);

//string comparison part


printf("\n\n Enter another string to compare with first one : ");
gets(str2);
while(str2[j]!='\0')
j++;
len2=j;
if(len1 == len2)
{
while(k<len1)
{
if(str1[k] == str2[k])
i++;
else
break;
}
if(k==len1)
{
same=1;
printf("\n The two strings are equal ");
}
}
if(len1 != len2)
printf("\n The two strings are not equal");
if(same==0)
{
if(str1[k]>str2[k])
printf("\n\n '%s' is greater than '%s'",str1,str2);
else if(str1[k]<str2[k])
printf("\n\n '%s' is greater than '%s'",str2,str1);
}
getch();
}

// Output
/* Exp14: Program to multiply two matrices */
#include<stdio.h>
#include<conio.h>
void main()
{
int row1, col1, row2, col2,firstMatrix[5][5];
int secondMatrix[5][5], result[5][5],i,j,k;

// Get dimensions of the first matrix


printf("Enter the number of rows and columns for the first matrix: ");
scanf("%d %d", &row1, &col1);

// Get dimensions of the second matrix


printf("Enter the number of rows and columns for the second matrix: ");
scanf("%d %d", &row2, &col2);

// Check if the matrices can be multiplied


if (col1 != row2)
{
printf("Error: Matrices cannot be multiplied!\n");
getch();
return 1;
}
// Input for the first matrix
printf("Enter elements of the first matrix:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
scanf("%d", &firstMatrix[i][j]);
}
}

// Input for the second matrix


printf("Enter elements of the second matrix:\n");
for (i = 0; i < row2; i++) {
for (j = 0; j < col2; j++) {
scanf("%d", &secondMatrix[i][j]);
}
}

// Initialize the result matrix to zero


for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
result[i][j] = 0;
}
}

// Matrix multiplication
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < col1; k++) {
result[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

// Print the resulting matrix


printf("Resulting matrix after multiplication:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

getch();
}

// Output
//Exp15: Program to demonstrate nested structure
#include<stdio.h>
#include<conio.h>
// Define a structure for the employee
struct Employee
{
int empCode, salary;
char name[50];
struct
{
int day;
int month;
int year;
} dateOfJoining;
};

void main()
{
struct Employee employees[10]; // Array to store 10 employee records
int i;
clrscr();
// Read the details of each employee
for (i = 0; i < 3; i++)
{
printf("Enter details for employee %d:\n", i + 1);
printf("Employee Salary: ");
scanf("%d", &employees[i].salary);
printf("Employee Code: ");
scanf("%d", &employees[i].empCode);
fflush(stdin);
printf("Employee Name: ");
gets(employees[i].name); // Read string with spaces

printf("Date of Joining (dd mm yyyy): ");


scanf("%d %d %d", &employees[i].dateOfJoining.day,
&employees[i].dateOfJoining.month, &employees[i].dateOfJoining.year);

printf("\n");
}

// Display the details of all employees


printf("Employee Records:\n");
for (i = 0; i < 3; i++)
{
printf("Employee %d:\n", i + 1);
printf("Code: %d\n", employees[i].empCode);
printf("Name: %s\n", employees[i].name);
printf("Salary: %d\n", employees[i].salary);
printf("Date of Joining: %d.%d.%d\n\n",
employees[i].dateOfJoining.day,
employees[i].dateOfJoining.month,
employees[i].dateOfJoining.year);
}

getch();
}
/* Output
Employee Salary: 32400
Employee Code: 3
Employee Name: Ramesh Sahu
Date of Joining (dd mm yyyy): 24 9 2010

Employee Records:
Employee 1:
Code: 1
Name: Sunil Shende
Salary: 24500
Date of Joining: 12.4.2005

Employee 2:
Code: 2
Name: Kirti Kumari
Salary: 12500
Date of Joining: 30.5.1999

Employee 3:
Code: 3
Name: Ramesh Sahu
Salary: 32400
Date of Joining: 24.9.2010
*/
/*Exp16: Program to demonstrate pointer arithmetic using array */
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5] = {10, 20, 30, 40, 50},i; // Initialize an array of 5 integers
int *ptr = arr; // Pointer pointing to the first element of the array
clrscr();
// Print the array elements using pointer arithmetic
printf("Array elements using pointer arithmetic:\n");
for (i = 0; i < 5; i++)
{
printf("Element %d: %d\n", i, *(ptr + i)); // Accessing element using pointer
arithmetic
}

// Demonstrating pointer increment and address calculations


printf("\nPointer arithmetic (addresses and values):\n");
for (i = 0; i < 5; i++)
{
printf("Address of arr[%d] = %p, Value = %d\n", i, (ptr + i), *(ptr + i)); //
Pointer arithmetic
}

// Demonstrating incrementing the pointer itself


printf("\nDemonstrating pointer incrementing:\n");
for (i = 0; i < 5; i++)
{
printf("Value at ptr (Element %d): %d\n", i, *ptr);
ptr++; // Increment the pointer to point to the next element in the array
}

getch();
}

/* Output

Array elements using pointer arithmetic:


Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
Pointer arithmetic (addresses and values):
Address of arr[0] = FFEC, Value = 10
Address of arr[1] = FFEE, Value = 20
Address of arr[2] = FFF0, Value = 30
Address of arr[3] = FFF2, Value = 40
Address of arr[4] = FFF4, Value = 50

Demonstrating pointer incrementing:


Value at ptr (Element 0): 10
Value at ptr (Element 1): 20
Value at ptr (Element 2): 30
Value at ptr (Element 3): 40
Value at ptr (Element 4): 50
*/
/* Exp 17: Program Demonstrating simple file oprations */
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

void main()
{
FILE *filePtr; // File pointer
char data[100]; // Buffer to store data
char readBuffer[100]; // Buffer to read data from file
clrscr();
// 1. Creating (or opening) a file for writing
filePtr = fopen("example.txt", "w");
if (filePtr == NULL)
{
printf("Error! Could not create file.\n");
exit(1); // Exit if file creation fails
}

// 2. Writing to the file


printf("Enter some text to write to the file: ");
fgets(data, sizeof(data), stdin); // Read input from user

fprintf(filePtr, "%s", data); // Write the user input to the file


printf("Data written to the file successfully.\n");

// Close the file after writing


fclose(filePtr);

// 3. Opening the file for reading


filePtr = fopen("example.txt", "r");
if (filePtr == NULL)
{
printf("Error! Could not open file for reading.\n");
exit(1);
}

// 4. Reading from the file


printf("Data read from the file:\n");
while (fgets(readBuffer, sizeof(readBuffer), filePtr) != NULL)
{
printf("%s", readBuffer); // Print the contents of the file
}
// 5. Closing the file
fclose(filePtr);

getch();
}

/* Output
Enter some text to write to the file: Hi this is demo for file operations
Data written to the file successfully.
Data read from the file:
Hi this is demo for file operations
*/

Explanation:

Creating and opening a file (fopen):

fopen("example.txt", "w"): Opens or creates the file example.txt in write mode


("w"). If the file exists, it will be overwritten; if it doesn’t exist, it will be created.
If fopen fails to create or open the file, it returns NULL, and the program exits
with an error.

Writing to a file (fprintf):

fprintf(filePtr, "%s", data): Writes the user input (data) to the file using the file
pointer (filePtr).

Reading from a file (fgets):

fgets(readBuffer, sizeof(readBuffer), filePtr): Reads a line from the file into the
buffer (readBuffer).
The loop continues reading until the end of the file.

Closing the file (fclose):

The fclose(filePtr) function is used to close the file after both writing and reading
operations.

You might also like