0% found this document useful (0 votes)
15 views22 pages

Assignment 4 Solution

The document contains multiple C code snippets that perform various tasks, including calculating the sum of digits, sorting student data by marks, printing Pascal's triangle, grading based on answers, and performing basic arithmetic operations. Each code segment is accompanied by explanations of its functionality and sample runs demonstrating its output. The overall structure emphasizes user interaction and dynamic memory management in C programming.

Uploaded by

Sohair Shahzad
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)
15 views22 pages

Assignment 4 Solution

The document contains multiple C code snippets that perform various tasks, including calculating the sum of digits, sorting student data by marks, printing Pascal's triangle, grading based on answers, and performing basic arithmetic operations. Each code segment is accompanied by explanations of its functionality and sample runs demonstrating its output. The overall structure emphasizes user interaction and dynamic memory management in C programming.

Uploaded by

Sohair Shahzad
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/ 22

Code :

#include <stdio.h>

// Function to calculate the sum of digits of a number


int sum_of_digits(int num) {
int sum = 0;
int last_digit;
while (num > 0) {
last_digit = num % 10; // Extract the last digit
sum += last_digit; // Add the last digit to the sum
num /= 10; // Remove the last digit
}
return sum;
}

// Function to get data from the user


void get_data(int cards[], int n) {
for (int i = 0; i < n; i++) {
printf("Enter number of card %d: ", i + 1);

1
scanf("%d", &cards[i]);
}
}

// Function to sort cards based on the sum of their digits


void sort(int cards[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (sum_of_digits(cards[j]) > sum_of_digits(cards[j + 1]))
{
// Swap cards[j] and cards[j+1]
int temp = cards[j];
cards[j] = cards[j + 1];
cards[j + 1] = temp;
}
}
}
}

// Function to display sorted cards


void display(int cards[], int n) {
printf("Sorted cards:\n");
for (int i = 0; i < n; i++) {
printf("%d\n", cards[i]);
}
}

// Main function
int main() {
int n;

printf("How many cards do you have? ");


scanf("%d", &n);

int cards[n];

2
get_data(cards, n);
sort(cards, n);
display(cards, n);

return 0;
}

Code:

#include <stdio.h>
#include <string.h>

#define SIZE 7

// Function to sort data by marks in descending order


void sort_by_marks(int roll_no[], char names[][20], float marks[], int
n) {

3
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (marks[j] < marks[j + 1]) {
// Swap marks
float temp_marks = marks[j];
marks[j] = marks[j + 1];
marks[j + 1] = temp_marks;

// Swap roll numbers


int temp_roll = roll_no[j];
roll_no[j] = roll_no[j + 1];
roll_no[j + 1] = temp_roll;

// Swap names
char temp_name[20];
strcpy(temp_name, names[j]);
strcpy(names[j], names[j + 1]);
strcpy(names[j + 1], temp_name);
}
}
}
}

// Function to search and print data based on roll number


void search_by_roll(int roll_no[], char names[][20], float marks[],
int n, int search_roll) {
for (int i = 0; i < n; i++) {
if (roll_no[i] == search_roll) {
printf("Roll No: %d, Name: %s, Marks: %.2f\n", roll_no[i],
names[i], marks[i]);
return;
}
}
printf("Roll number %d not found.\n", search_roll);
}

4
// Function to search and print data based on name
void search_by_name(int roll_no[], char names[][20], float marks[],
int n, char search_name[]) {
for (int i = 0; i < n; i++) {
if (strcmp(names[i], search_name) == 0) {
printf("Roll No: %d, Name: %s, Marks: %.2f\n", roll_no[i],
names[i], marks[i]);
return;
}
}
printf("Name %s not found.\n", search_name);
}

// Main function
int main() {
int roll_no[SIZE] = {1001, 1002, 1004, 1005, 1007, 1008, 1009};
char names[SIZE][20] = {"Salman", "Zubair", "Ahsan", "Farah",
"Hassan", "Kamran", "Mariyum"};
float marks[SIZE] = {75.5, 80.0, 64.0, 78.0, 65.0, 54.0, 60.0};

int choice, roll_search;


char name_search[20];

do {
printf("\nMenu:\n");
printf("1. Sort by marks\n");
printf("2. Search by roll number\n");
printf("3. Search by name\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:

5
sort_by_marks(roll_no, names, marks, SIZE);
printf("Data sorted by marks (descending):\n");
for (int i = 0; i < SIZE; i++) {
printf("Roll No: %d, Name: %s, Marks: %.2f\n",
roll_no[i], names[i], marks[i]);
}
break;

case 2:
printf("Enter roll number to search: ");
scanf("%d", &roll_search);
search_by_roll(roll_no, names, marks, SIZE,
roll_search);
break;

case 3:
printf("Enter name to search: ");
scanf("%s", name_search);
search_by_name(roll_no, names, marks, SIZE,
name_search);
break;

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

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

return 0;
}

6
Explanation:

1. sort_by_marks:
o Sorts the data based on marks in descending order.
o Uses the Bubble Sort algorithm to swap roll_no, names, and marks together to
maintain the correct mapping.
2. search_by_roll:
o Searches for a record using the roll number.
o Iterates through the roll_no array and prints the corresponding data if a match is
found.
3. search_by_name:
o Searches for a record using the name.
o Compares each name in the array using strcmp and prints the corresponding data if a
match is found.
4. Main Menu:
o Provides options to sort, search by roll number, or search by name.
o Keeps running until the user chooses to exit.

Sample Run:

Input:
Menu:
1. Sort by marks
2. Search by roll number
3. Search by name
4. Exit
Enter your choice: 1

Output:
Data sorted by marks (descending):
Roll No: 1002, Name: Zubair, Marks: 80.00
Roll No: 1005, Name: Farah, Marks: 78.00
Roll No: 1001, Name: Salman, Marks: 75.50

7
Roll No: 1007, Name: Hassan, Marks: 65.00
Roll No: 1004, Name: Ahsan, Marks: 64.00
Roll No: 1009, Name: Mariyum, Marks: 60.00
Roll No: 1008, Name: Kamran, Marks: 54.00

_____________________________________________________________________________________

Code:

#include <stdio.h>

// Function to print Pascal's triangle


void print_pascals_triangle(int n) {
int triangle[n][n];

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


// Print spaces for alignment
for (int j = 0; j < n - i - 1; j++) {
printf(" ");
}
// Generate and print row values
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1; // First and last values are 1

8
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i -
1][j];
}
printf("%d ", triangle[i][j]);
}
printf("\n");
}
}

// Main function
int main() {
int n;
printf("Enter the number of rows for Pascal's Triangle: ");
scanf("%d", &n);

print_pascals_triangle(n);

return 0;
}

Explanation:

1. triangle Array:
o A 2D array is used to store the values of Pascal's Triangle as it's calculated.
2. Logic:
o The first and last elements in each row are set to 1.
o Each intermediate value is the sum of the two values directly above it from the previous
row.
3. Alignment:
o Spaces are printed before each row to ensure the output forms an equilateral triangle.

9
Sample Run:

Input:
Enter the number of rows for Pascal's Triangle: 6

Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

This approach is straightforward, avoids factorial calculations, and directly builds Pascal's
Triangle.

______________________________________________________________________________

Code:

10
#include <stdio.h>
#include <stdlib.h>

// Function to calculate score and grade


void calculate_score(char *correct_answers, char *student_answers, int
num_questions, int *score, char *grade) {
int i;
*score = 0;

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


if (student_answers[i] == correct_answers[i]) {
*score = *score + 2; // Correct answer
} else if (student_answers[i] == 'T' || student_answers[i] ==
'F') {
*score = *score - 1; // Wrong answer
}
// No answer gets no change
}

float percentage = ((*score) * 100.0) / (2 * num_questions);

if (percentage >= 90) {


*grade = 'A';
} else if (percentage >= 80) {
*grade = 'B';
} else if (percentage >= 70) {
*grade = 'C';
} else if (percentage >= 60) {
*grade = 'D';
} else {
*grade = 'F';
}
}

// Main function

11
int main() {
int num_questions, num_students, i;

// Input number of questions and students


printf("Enter the number of questions: ");
scanf("%d", &num_questions);

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


scanf("%d", &num_students);

// Dynamically allocate memory for arrays


char *correct_answers = (char *)malloc((num_questions + 1) *
sizeof(char));
char **student_ids = (char **)malloc(num_students * sizeof(char
*));
char **student_answers = (char **)malloc(num_students *
sizeof(char *));
int *scores = (int *)malloc(num_students * sizeof(int));
char *grades = (char *)malloc(num_students * sizeof(char));

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


student_ids[i] = (char *)malloc(20 * sizeof(char)); //
Assuming max ID length is 20
student_answers[i] = (char *)malloc((num_questions + 1) *
sizeof(char));
}

// Input correct answers


printf("Enter the correct answers (e.g., TFFTFFTT): ");
scanf("%s", correct_answers);

// Input student data


for (i = 0; i < num_students; i++) {
printf("Enter student ID and answers (e.g., ABC12345
TFTFTFTT): ");

12
scanf("%s %s", student_ids[i], student_answers[i]);
}

// Calculate scores and grades


for (i = 0; i < num_students; i++) {
calculate_score(correct_answers, student_answers[i],
num_questions, &scores[i], &grades[i]);
}

// Display results
printf("\nResults:\n");
printf("ID\t\tAnswers\t\t\tScore\tGrade\n");
printf("---------------------------------------------------\n");
for (i = 0; i < num_students; i++) {
printf("%s\t%s\t%d\t%c\n", student_ids[i], student_answers[i],
scores[i], grades[i]);
}

// Free allocated memory


free(correct_answers);
for (i = 0; i < num_students; i++) {
free(student_ids[i]);
free(student_answers[i]);
}
free(student_ids);
free(student_answers);
free(scores);
free(grades);

return 0;
}

Explanation:

13
1. Dynamic Memory Allocation:
o The correct answers are stored in a dynamically allocated string (correct_answers).
o student_ids and student_answers are dynamically allocated arrays of strings, with

memory allocated for each student.


2. Input:
o Number of questions and students is taken as input.
o Correct answers and each student's data are entered.
3. Score Calculation:
o Correct answers get +2 points.
o Wrong answers get -1 point.
o Unanswered questions result in no change.
4. Grade Assignment:
o Based on the percentage calculated from the score.
5. Output:
o Displays student ID, answers, score, and grade.
6. Memory Deallocation:
o All dynamically allocated memory is freed at the end.

Sample Run:

Input:
Enter the number of questions: 5
Enter the number of students: 2
Enter the correct answers (e.g., TFFTFFTT): TFFTT
Enter student ID and answers (e.g., ABC12345 TFTFTFTT): ABC54301 TFFFT
Enter student ID and answers (e.g., ABC12345 TFTFTFTT): DEF98765 TFTTT

Output:
Results:
ID Answers Score Grade

14
---------------------------------------------------
ABC54301 TFFFT 7 C
DEF98765 TFTTT 8 B

This implementation satisfies the requirements for dynamic memory allocation and grading
based on scores.

15
Code
#include <stdio.h>
#include <stdlib.h>

#define MAX_OPERANDS 100

// Struct to store operands and operators


struct data {
float operand1;
float operand2;
char operator;
};

16
// Function to perform basic arithmetic operations
float basic(float operand1, float operand2, char op) {
switch (op) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
if (operand2 == 0) {
printf("Invalid. Any number divided by zero is
infinity.\n");
return -1; // Return an invalid result to indicate an
error
}
return operand1 / operand2;
default:
printf("Invalid operator\n");
return -1; // Return an invalid result to indicate an
error
}
}

// Function to display the equation and result


void display(const struct data equation[], int size) {
float result = equation[0].operand1;
for (int i = 0; i < size; i++) {
result = basic(result, equation[i].operand2,
equation[i].operator);
if (result == -1) {
return; // If there's an error (e.g., division by zero),
exit
}

17
}

// Print the equation in the required format


printf("You have solved the following equation:\n");
printf("%.2f ", equation[0].operand1);
for (int i = 0; i < size; i++) {
printf("%c %.2f ", equation[i].operator,
equation[i].operand2);
}
printf("= %.2f\n", result);
}

// Function to calculate the dot product of two vectors


double dot(const double A[], const double B[], int size) {
double result = 0;
for (int i = 0; i < size; i++) {
result += A[i] * B[i];
}
return result;
}

int main() {
char choice;
do {
printf("Do you want to solve an equation (press a) or a dot
product (press b)? ");
scanf(" %c", &choice); // Adding a space before %c to consume
any extra newline characters

if (choice == 'a') {
int num_operands;
printf("How many operands are there in the equation: ");
scanf("%d", &num_operands);

// Ensure the number of operands does not exceed the limit

18
if (num_operands > MAX_OPERANDS) {
printf("Too many operands. The maximum is %d.\n",
MAX_OPERANDS);
continue;
}

struct data equation[num_operands - 1]; // Array to store


operators and operands

// Input operands and operators


for (int i = 0; i < num_operands - 1; i++) {
printf("Enter operand %d: ", i + 1);
if (i == 0) {
scanf("%f", &equation[i].operand1);
}
printf("Choose operator (+, -, *, /): ");
scanf(" %c", &equation[i].operator);
printf("Enter operand %d: ", i + 2);
scanf("%f", &equation[i].operand2);
}

// Call to display function to show the result


display(equation, num_operands - 1);

printf("Do you want to solve another equation? Press y for


yes!\n");
scanf(" %c", &choice); // Asking the user if they want to
continue solving equations

} else if (choice == 'b') {


int size;
printf("Enter the size of the vectors: ");
scanf("%d", &size);

double A[size], B[size];

19
// Input vector A
for (int i = 0; i < size; i++) {
printf("Enter the value for A[%d]: ", i);
scanf("%lf", &A[i]);
}

// Input vector B
for (int i = 0; i < size; i++) {
printf("Enter the value for B[%d]: ", i);
scanf("%lf", &B[i]);
}

// Call to dot function to calculate dot product


double result = dot(A, B, size);
printf("The dot product is: %.6lf\n", result);

printf("Do you want to perform another dot product? Press


y for yes!\n");
scanf(" %c", &choice); // Asking the user if they want to
perform another dot product

} else {
printf("Invalid input\n");
break; // Exit the program if input is invalid
}

} while (choice == 'y' || choice == 'a' || choice == 'b');

return 0;
}

Explanation:

1. Struct Definition:

20
o struct data is used to store two operands and an operator. This is used to store the

equation step by step for solving.


2. Basic Function (basic):
o This function performs the basic arithmetic operations based on the provided operator
(+, -, *, /). It handles division by zero and invalid operators.
3. Display Function (display):
o This function takes the array of operations and operands, calculates the result step by
step, and displays the full equation with the result.
4. Dot Product Function (dot):
o This function computes the dot product of two vectors A and B by summing the
products of corresponding elements.
5. Main Function:
o The main function gives the user a choice to either solve an equation or calculate the
dot product.
o If the user chooses to solve an equation, the program asks for operands and operators,
stores them in an array of structs, and calculates the result.
o If the user chooses the dot product, the program asks for two vectors and calculates the
dot product.
6. Looping and User Interaction:
o The program continues to ask the user whether they want to solve another equation or
calculate another dot product until they choose to exit.

Example Output:

Input:
Do you want to solve an equation (press a) or a dot product (press b)? a
How many operands are there in the equation: 5
Enter operand 1: 3
Choose operator (+, -, *, /): +
Enter operand 2: 34.5
Choose operator (+, -, *, /): /
Enter operand 3: 2

21
Choose operator (+, -, *, /): *
Enter operand 4: 60
Choose operator (+, -, *, /): -
Enter operand 5: 22
You have solved the following equation:
3.00 + 34.50 / 2.00 * 60.00 - 22.00 = 1103.00
Do you want to solve another equation? Press y for yes!
y
How many operands are there in the equation: 3
Enter operand 1: 78
Choose operator (+, -, *, /): /
Enter operand 2: 0
Invalid. Any number divided by zero is infinity.
Do you want to solve another equation? Press y for yes!
n
Do you want to solve an equation (press a) or a dot product (press b)? b
Enter the size of the vectors: 5
Enter the value for A[0]: 1
Enter the value for B[0]: 4
Enter the value for A[1]: 2
Enter the value for B[1]: 5
Enter the value for A[2]: 5
Enter the value for B[2]: 6
Enter the value for A[3]: 2
Enter the value for B[3]: 3
Enter the value for A[4]: 1
Enter the value for B[4]: 10
The dot product is: 60.000000
Do you want to perform another dot product? Press y for yes!
n

This program should meet your requirements for both functionalities: solving an equation and
calculating the dot product.

22

You might also like