0% found this document useful (0 votes)
2 views26 pages

Ps New

The document contains a series of C programming exercises for a second semester BCA student, Patel Ishan Rakeshbhai, including tasks like creating and printing a 3x3 matrix, multiplying two matrices, concatenating names and surnames, defining structures for items and books, checking for Armstrong numbers, calculating factorials using recursion, and performing matrix operations. Each exercise includes sample code, input prompts, and expected outputs. The document serves as a practical guide for programming concepts and implementation in C.

Uploaded by

ishanpatel445
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)
2 views26 pages

Ps New

The document contains a series of C programming exercises for a second semester BCA student, Patel Ishan Rakeshbhai, including tasks like creating and printing a 3x3 matrix, multiplying two matrices, concatenating names and surnames, defining structures for items and books, checking for Armstrong numbers, calculating factorials using recursion, and performing matrix operations. Each exercise includes sample code, input prompts, and expected outputs. The document serves as a practical guide for programming concepts and implementation in C.

Uploaded by

ishanpatel445
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/ 26

FYBCA SEM-2 Patel Ishan Rakeshbhai

DIV: G ROLL NO: 1637

C programs
1. Write a program to create 2D array of size 3*3 and print the
matrix.
Input:
#include <stdio.h>
int main() {
int matrix[3][3];
// Taking input from the user
printf("Enter 9 elements for the 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {


scanf("%d", &matrix[i][j]);
}
}
// Printing the matrix
printf("The 3x3 matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {

printf("%d ", matrix[i][j]);


}
printf("\n");

return 0;
}

1|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Output:
Enter 9 elements for the 3x3 matrix:
123

456
789

The 3x3 matrix is:


123
456
789

2. Write a program for multiplication of two matrixes.


Input:
#include <stdio.h>

#define SIZE 3 // Define the matrix size (3x3)

int main() {

int A[SIZE][SIZE], B[SIZE][SIZE], result[SIZE][SIZE] = {0};

// Taking input for first matrix


printf("Enter 9 elements for first 3x3 matrix:\n");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
scanf("%d", &A[i][j]);

}
}

// Taking input for second matrix


printf("Enter 9 elements for second 3x3 matrix:\n");
for (int i = 0; i < SIZE; i++) {

2|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

for (int j = 0; j < SIZE; j++) {


scanf("%d", &B[i][j]);
}
}

// Multiplying matrices
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
for (int k = 0; k < SIZE; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}

// Printing the resultant matrix


printf("Resultant Matrix after multiplication:\n");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%d ", result[i][j]);

}
printf("\n");
}

return 0;
}

Output:
Enter elements of Matrix A (3x3):
123
456
789

3|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Enter elements of Matrix B (3x3):


987
654
321

Resultant Matrix (A × B):


30 24 18
84 69 54
138 114 90

3. Write a program to take input of 5 names and surnames in


different two-dimensional arrays. Then concatenate (join) names
with their surname in a third 2D array.
Input:
#include <stdio.h>
#include <string.h>

#define SIZE 5
#define MAX_LENGTH 50

int main() {
char names[SIZE][MAX_LENGTH], surnames[SIZE][MAX_LENGTH],
fullNames[SIZE][MAX_LENGTH * 2];

// Taking input for names


printf("Enter 5 names:\n");
for (int i = 0; i < SIZE; i++) {
scanf("%s", names[i]);
}

// Taking input for surnames


printf("Enter 5 surnames:\n");

4|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

for (int i = 0; i < SIZE; i++) {


scanf("%s", surnames[i]);
}

// Concatenating names with surnames


for (int i = 0; i < SIZE; i++) {
strcpy(fullNames[i], names[i]); // Copy the name
strcat(fullNames[i], " "); // Add space between name and surname
strcat(fullNames[i], surnames[i]); // Append surname
}

// Printing full names


printf("\nFull Names after concatenation:\n");
for (int i = 0; i < SIZE; i++) {
printf("%s\n", fullNames[i]);
}

return 0;

Output:
Enter 5 first names:
John
Alice
Michael

Emma
David

Enter 5 surnames:
Smith
Johnson

5|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Brown
Williams
Jones

Full Names:
John Smith
Alice Johnson
Michael Brown
Emma Williams
David Jones

4. Define a structure item with following fields item code, name and
quantity. Write a program that takes input of structure and display
in proper format.
Input:
#include <stdio.h>

// Define the structure


struct item {
int itemCode;
char name[50];
int quantity;
};

int main() {
struct item product; // Declare a structure variable

// Taking input from user


printf("Enter item code: ");
scanf("%d", &product.itemCode);

printf("Enter item name: ");

6|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

scanf(" %[^\n]", product.name); // To read a string with spaces

printf("Enter quantity: ");


scanf("%d", &product.quantity);

// Displaying the item details


printf("\nItem Details:\n");
printf("Item Code: %d\n", product.itemCode);
printf("Item Name: %s\n", product.name);
printf("Quantity: %d\n", product.quantity);

return 0;
}

Output:
Enter Item Code: 101
Enter Item Name: Wireless Mouse
Enter Quantity: 25

Item Details:
Item Code: 101
Item Name: Wireless Mouse
Quantity: 25

5. Create a structure of book in which declare the member as


book_id, book_name, price, qty. Take the information of five books
and calculate the total amount for each book and find out the
book_name which has highest total amount.
Input:
#include <stdio.h>

7|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

#include <string.h>

#define SIZE 5

// Define the structure


struct book {
int book_id;
char book_name[50];
float price;
int qty;
};

int main() {
struct book books [SIZE]; // Array of structures to store 5 books
float total_amount[SIZE];
float max_amount = 0;
int max_index = 0;

// Taking input for 5 books

printf("Enter details of 5 books:\n");


for (int i = 0; i < SIZE; i++) {
printf("\nBook %d:\n", i + 1);
printf("Enter book ID: ");
scanf("%d", &books[i].book_id);

printf("Enter book name: ");

scanf(" %[^\n]", books[i].book_name); // Reads multi-word book name

printf("Enter book price: ");


scanf("%f", &books[i].price);

printf("Enter quantity: ");

8|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

scanf("%d", &books[i].qty);

// Calculate total amount for each book


total_amount[i] = books[i].price * books[i].qty;

// Find the book with the highest total amount


if (total_amount[i] > max_amount) {
max_amount = total_amount[i];
max_index = i;
}
}

// Displaying book details and total amounts


printf("\nBook Details and Total Amounts:\n");
printf("----------------------------------------------------\n");
printf("Book ID | Book Name | Price | Qty | Total Amount\n");
printf("----------------------------------------------------\n");
for (int i = 0; i < SIZE; i++) {
printf("%-8d | %-17s | %-6.2f | %-3d | %.2f\n", books[i].book_id, books[i].book_name,
books[i].price, books[i].qty, total_amount[i]);
}
printf("----------------------------------------------------\n");

// Display the book with the highest total amount


printf("\nBook with Highest Total Amount:\n");
printf("Book Name: %s\n", books[max_index].book_name);

printf("Total Amount: %.2f\n", max_amount);

return 0;
}

Output:

9|Page
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Enter details of 5 books:

Book 1:

Enter book ID: 101


Enter book name: C Programming
Enter book price: 350.50
Enter quantity: 3

Book 2:
Enter book ID: 102
Enter book name: Data Structures
Enter book price: 400.75
Enter quantity: 5

Book 3:
Enter book ID: 103
Enter book name: Operating Systems
Enter book price: 300.25

Enter quantity: 2

Book 4:
Enter book ID: 104
Enter book name: Computer Networks
Enter book price: 450.00
Enter quantity: 4

Book 5:
Enter book ID: 105
Enter book name: Algorithms
Enter book price: 500.90
Enter quantity: 6

10 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Book Details and Total Amounts:


----------------------------------------------------
Book ID | Book Name | Price | Qty | Total Amount

----------------------------------------------------
101 | C Programming | 350.50 | 3 | 1051.50
102 | Data Structures | 400.75 | 5 | 2003.75
103 | Operating Systems | 300.25 | 2 | 600.50
104 | Computer Networks | 450.00 | 4 | 1800.00
105 | Algorithms | 500.90 | 6 | 3005.40
----------------------------------------------------

Book with Highest Total Amount:


Book Name: Algorithms
Total Amount: 3005.40

11 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

6. Write a User Define function Armstrong that returns 1 if its


argument is an Armstrong number and returns zero otherwise.
Input:
#include <stdio.h>
#include <math.h>

// Function to check Armstrong number


int Armstrong(int num) {
int originalNum, remainder, result = 0, n = 0;

originalNum = num;

// Count number of digits


while (originalNum != 0) {
originalNum /= 10;
n++;
}

originalNum = num;

// Calculate sum of digits raised to the power of n


while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);

originalNum /= 10;
}

// Return 1 if Armstrong, otherwise return 0


return (result == num) ? 1 : 0;
}

12 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

int main() {
int number;

// Input number from user


printf("Enter a number: ");
scanf("%d", &number);

// Check if Armstrong number


if (Armstrong(number))
printf("%d is an Armstrong number.\n", number);
else
printf("%d is not an Armstrong number.\n", number);

return 0;
}

Output:
Enter a number: 9474

9474 is an Armstrong number.

Enter a number: 123


123 is not an Armstrong number.

7. Write a program to find the factorial of a given number by using a


recursive function.
Input:
#include <stdio.h>
// Recursive function to calculate factorial
long long factorial(int n) {
if (n == 0 || n == 1) // Base case: factorial of 0 or 1 is 1
return 1;

13 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

else
return n * factorial(n - 1); // Recursive call
}
int main() {

int num;
// Input number from user
printf("Enter a number: ");
scanf("%d", &num);
// Check for negative numbers
if (num < 0)
printf("Factorial of a negative number is not defined.\n");
else
printf("Factorial of %d is %lld\n", num, factorial(num));
return 0;
}
Output:
Test 1: Positive Number
Enter a number: 5
Factorial of 5 is 120

Test 1: Positive Number


Enter a number: 5
Factorial of 5 is 120

Test 1: Positive Number


Enter a number: 5

Factorial of 5 is 120

8. Write a menu-driven program to generate 2 matrix and perform


the different Matrix Operation such as: (Use the concept of UDF):
1.Addition (), 2.Subtraction ()Multiplication()

14 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Input:
#include <stdio.h>

#define SIZE 3 // Define matrix size (3x3)

// Function to take input for a matrix


void inputMatrix(int matrix[SIZE][SIZE], char name) {
printf("Enter elements for Matrix %c (%dx%d):\n", name, SIZE, SIZE);
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
scanf("%d", &matrix[i][j]);
}
}
}

// Function to display a matrix


void displayMatrix(int matrix[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {

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

// Function to add two matrices

void addition(int A[SIZE][SIZE], int B[SIZE][SIZE], int result[SIZE][SIZE]) {


for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}

15 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

// Function to subtract two matrices


void subtraction(int A[SIZE][SIZE], int B[SIZE][SIZE], int result[SIZE][SIZE]) {

for (int i = 0; i < SIZE; i++) {


for (int j = 0; j < SIZE; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
}

// Function to multiply two matrices


void multiplication(int A[SIZE][SIZE], int B[SIZE][SIZE], int result[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
result[i][j] = 0; // Initialize result cell
for (int k = 0; k < SIZE; k++) {
result[i][j] += A[i][k] * B[k][j];
}

}
}
}

int main() {
int A[SIZE][SIZE], B[SIZE][SIZE], result[SIZE][SIZE];
int choice;

// Take input for both matrices


inputMatrix(A, 'A');
inputMatrix(B, 'B');

// Menu-driven operations

16 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

do {
printf("\nChoose a Matrix Operation:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");

printf("3. Multiplication\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
addition(A, B, result);
printf("\nResultant Matrix after Addition:\n");
displayMatrix(result);
break;

case 2:
subtraction(A, B, result);
printf("\nResultant Matrix after Subtraction:\n");

displayMatrix(result);
break;

case 3:
multiplication(A, B, result);
printf("\nResultant Matrix after Multiplication:\n");
displayMatrix(result);

break;

case 4:
printf("Exiting program...\n");
break;

17 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);

return 0;
}

Output:
Enter elements for Matrix A (3x3):
123
456
789

Enter elements for Matrix B (3x3):


987
654
321

Choose a Matrix Operation:


1. Addition
2. Subtraction
3. Multiplication
4. Exit
Enter your choice: 1
Resultant Matrix after Addition:

10 10 10
10 10 10
10 10 10

Choose a Matrix Operation:


3

18 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Resultant Matrix after Multiplication:


30 24 18
84 69 54
138 114 90

Enter your choice: 4


Exiting program...

Python
9. Write a python program to check given number is even or odd
using user define function.
Input:

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))

else:
print("{0} is Odd".format(num))

Output 1:
Enter a number: 43
43 is Odd
Output 2:
Enter a number: 18

18 is Even

10. Write a program to check prime numbers.

19 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Input:
# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = False

if num == 0 or num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# If factor is found, set flag to True
flag = True

# Break out of loop


break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:

print(num, "is a prime number")

Output:
29 is a prime number

11. Write a program to convert a ASCII value to a char. & char. to ASCII value.

20 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Input:
# Python program to print
# ASCII Value of Character

# In c we can assign different


# characters of which we want ASCII value

c = 'g'
# print the ASCII value of assigned character in c
print("The ASCII value of '" + c + "' is", ord(c))

Output:
("The ASCII value of 'g' is", 103)

12. Write a program to print sum of N numbers.


Input:
# Sum of natural numbers up to num

num = 16

if num < 0:
print("Enter a positive number")
else:
sum = 0
# Use while loop to iterate until zero
while(num > 0):

sum += num
num -= 1
print("The sum is", sum)
Output:
The sum is 136

21 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

13. Write a program to print even numbers between two numbers.


Input:
start = 1
end = 10

# Using list comprehension to find even numbers


res = [i for i in range(start, end + 1) if i % 2 == 0]

# Printing the list of even numbers


print(res)
Output:

[2, 4, 6, 8, 10]

14. Write a program to sort words in Alphabetical order.


Input:
# Program to sort alphabetically the words form a string provided by the user

my_str = "Hello this Is an Example With cased letters"

# To take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in my_str.split()]

# sort the list

words.sort()

# Display the sorted words

print ("The sorted words are:")


for word in words:

22 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

print(word)
Output:
The sorted words are:
an
cased
example
hello
is
letters
this
with

15. Write a python script to read CSV file and display first 3 records
and last 3 records from data.
Input:
# Python program to read CSV file without header

# Import necessary packages


import csv

# Open file

with open('samplecsv.csv') as file_obj:

# Skips the heading


# Using next() method
heading = next(file_obj)

# Create reader object by passing the file

# object to reader method


reader_obj = csv.reader(file_obj)

# Iterate over each row in the csv file


# using reader object
for row in reader_obj:
print(row)

23 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Output:
['1', 'Akhil', '4']
['2', 'Babu', '3']
['3', 'Nikhil', '5']

16. Write a python script to read CSV file of Employee data with
field (eno, ename, salary). Perform the following operations:
1. Retrieve the maximum and minimum salary.
2. Display range of rows from [2:5]
3. Display all rows in reverse order.
4.Display all Odd number rows.
Input:

import pandas as pd

# Read CSV file


file_path = "employee_data.csv" # Replace with actual file path

df = pd.read_csv(file_path)

# 1. Retrieve the maximum and minimum salary


max_salary = df['salary'].max()
min_salary = df['salary'].min()
print(f"Maximum Salary: {max_salary}")
print(f"Minimum Salary: {min_salary}")

# 2. Display range of rows from [2:5]


print("Rows from index 2 to 5:")
print(df.iloc[2:5])

# 3. Display all rows in reverse order


print("Data in reverse order:")

24 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

print(df.iloc[::-1])

# 4. Display all Odd number rows (assuming 1-based indexing for human readability)
print("Odd number rows:")

print(df.iloc[::2])
Output:

eno,ename,salary
101,John,50000
102,Alice,60000
103,Bob,55000
104,Eve,65000
105,Charlie,70000
106,David,72000

Maximum Salary: 72000


Minimum Salary: 50000

Rows from index 2 to 5:

eno ename salary


2 103 Bob 55000
3 104 Eve 65000
4 105 Charlie 70000

Employee Data in Reverse Order:


eno ename salary

5 106 David 72000


4 105 Charlie 70000
3 104 Eve 65000
2 103 Bob 55000
1 102 Alice 60000
0 101 John 50000

25 | P a g e
Sascmabca college
FYBCA SEM-2 Patel Ishan Rakeshbhai
DIV: G ROLL NO: 1637

Odd Numbered Rows (Index 1,3,5...):


eno ename salary
1 102 Alice 60000

3 104 Eve 65000


5 106 David 72000

26 | P a g e
Sascmabca college

You might also like