CSE1071 Remedial Jan2014 Assignment-3 Answers

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

FIRST-YEAR B.

TECH (REMEDIAL JAN 2024)


COURSE: PROBLEM SOLVING USING COMPUTERS (CSE 1071)
ASSIGNMENT #3

Submission date: 22-04-2024, 5 PM MAX.MARKS: 05

1.(a) Write a C program to compute the average of ‘n’ array elements using a pointer.
Ans:
#include<stdio.h>
int main() {
float a[20],sum=0,avg=0,*p;
int n,i;
printf("Enter number of array elements ");
scanf("%d",&n);
printf("Enter array elements\n");
for(p=a;p<a+n;p++)
scanf("%f",p);
for(p=a;p<a+n;p++) {
sum+=*p;
}
avg=sum/n;
printf("Average = %f\n",avg);
return 0;
}
1.(b) Create a structure called time with hours, minutes and seconds as its members. Write a C
program to read start and end times and print the time difference using a function timediff()
that accepts two structure variables of type time as input and computes the time difference.
Ans:
#include<stdio.h>
struct time
{
int hours,minutes,seconds;
};
struct time timediff(struct time s, struct time e)
{
struct time diff;
if(e.seconds<s.seconds) {
e.seconds+=60;
--e.minutes;
}
if(e.minutes<s.minutes) {
e.minutes+=60;
--e.hours;
}
diff.seconds=e.seconds-s.seconds;
diff.minutes=e.minutes-s.minutes;
diff.hours=e.hours-s.hours;
return(diff);
}
int main() {
struct time t1, t2, d;
printf("Enter start time in hours, minutes and seconds\n");
scanf("%d%d%d",&t1.hours,&t1.minutes,&t1.seconds);
printf("Enter end time in hours, minutes and seconds\n");
scanf("%d%d%d",&t2.hours,&t2.minutes,&t2.seconds);
d=timediff(t1, t2);
printf("Time difference is %d hours, %d minutes and %d seconds\n", d.hours, d.minutes,
d.seconds);
return 0;
}
2(a) Write a C program that reads a square matrix of size N x N and
i. Write a function DiagSumCompare() which takes a matrix as argument and displays
whether sum of primary diagonal elements is greater than secondary diagonal elements after
displaying the respective sum.
ii. Write a function BorderNonborderCompare() which takes a matrix as argument and
displays whether sum of all border elements is greater than non-border elements after
displaying the respective sum.
Call both the functions from main().
Ans:
#include<stdio.h>
void DiagSumCompare(int m[][10], int N){
int pds=0,sds=0,i,j;
for(i=0;i<N;i++) {
pds = pds + m[i][i];
sds=sds+m[i][N-i-1];
}
printf(“Primary Diagonal Sum=%d,\n Secondary Diagonal Sum=%d”,pds,sds);
if(pds > sds)
printf(“Primary Diagonal Sum is greater than Secondary Diagonal Sum”);
else if(sds>pds)
printf(“Primary Diagonal Sum is less than Secondary Diagonal Sum”);
else
printf(“Primary Diagonal Sum is equal to Secondary Diagonal Sum”);
}

void BorderNonborderCompare(int m[][10],int N)


{
int brdrs=0, nbrdrs=0;
for(i=0;i<N;i++)
{
brdrs=brdrs + m[0][i];
brdrs=brdrs+m[N-1][i];
if(i>0) {
brdrs=brdrs+m[i][0];
brdrs=brdrs+m[i][N-1];
}
}
for(i=1;i<N-1;i++)
for(j=1;j<N-1;j++)
nbrdrs=nbrdrs+m[i][j];
printf(“Border Sum=%d, Non-border Sum=%d”,brdrs,nbrdrs);
if(brdrs > nbrdrs)
printf(“Border sum is greater than non-border sum”);
else if(brdrs < nbrdrs)
printf(“Border sum is less than non-border sum”);
else
printf(“Border sum is equal to non-border sum”);
}

int main(){
int m[10][10],i,j,N;
printf(“Enter the number of rows in square matrix”);
scanf(“%d”,&N);
for(i=0;i<N;i++)
for(j=0;j<N;j++)
scanf(“%d”,&m[i][j]);

DiagSumCompare(m,N);
BorderNonborderCompare(m,N);
return 0;
}
2(b) List out the Rules to pass a 2D- array to a function and Write a c program to add all the
even elements of an array using the function Add().
Ans:
Rules to pass a 2D- array to a function
• The function must be called by passing only the array name.
• In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.
• The size of the second dimension must be specified.
• The prototype declaration should be similar to the function header.
Program:
int AddE( int a[ ], int n)
{
int sum=0,i;
for(i=0;i<n;i++)
{
if((a[i]%2) == 0)
sum+=a[i];
}
return (sum);
}
int main()
{
int n, a[20], x, y, i;
printf("Enter the limit \n");
scanf("%d", &n);
printf("Enter the values: \n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
printf("The sum of even array elements is =%d ", AddE(a,n));
return 0;
}
3(a) Define recursive function. Write a C program to find the sum of digits of a number using
recursion.
Ans:
A recursive function is a function that invokes/calls itself directly or indirectly.
int sumDigits(int num)
{
static int sum=0;
if(num>0)
{
sum+=(num%10); //add digit into sum
sumDigits(num/10);
}
else
{
return sum;
}
}
#include<stdio.h>
#include<math>
int main()
{
int number,sum;
printf(“Enter a positive integer number: ");
scanf(“%d”,&number);
sum=sumDigits(number);
printf("Sum of all digits: %d”,sum);

return 0;
}
3(b). Develop a C program to read a matrix of order M X M and Display the same in matrix
form in the main function. Write a function isSaddle which takes the matrix read, and its
dimensions as parameters, finds and displays the saddle points (numbers) in the matrix. [A
saddle point (number) is one which is minimum in its row and largest in its column. Write
another function SumofDigits, which takes an integer as parameter, calculates and returns the
sum of the digits of the integer. Invoke SumofDigits from isSaddle function with saddle point(s)
as parameter(s). Display the sum of the digits of the saddle number(s).
Ans:
#include<stdio.h>
void isSaddle(int a[30][30],int m);
int SumofDigits(int n);
void main() {
int a[30][30],i,j;
int s[5],sum=0,carry=0,r=5-1;
int m;
printf("enter the number of rows cols\n");
scanf("%d",&m);
printf("enter the elements in a matrix\n");
for(i=0;i<m;i++) {
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);
}
printf("the entered matrix is\n");
for(i=0;i<m;i++) {
for(j=0;j<m;j++) {
printf("%d\t",a[i][j]);}
printf("\n");
}
isSaddle(a,m);
}
void isSaddle(int a[30][30],int m) {
int min[30],max[30],mi,mx;
int i,j,sd,k=0,r=0;
printf("inside saddle");
for(i=0;i<m;i++) {
mi=a[k++][0];
mx=a[0][r++];
for(j=0;j<m;j++) {
if(a[i][j]<mi) {
mi=a[i][j];
}
if(a[j][i]>mx) {
mx=a[j][i];
}
}
min[i]=mi;
max[i]=mx;
}
for(i=0;i<m;i++)
printf("%d %d \n",min[i],max[i]);
for(i=0;i<m;i++) {
for(j=0;j<m;j++) {
if(min[i]==max[j]) {
printf("the saddle point is %d and found at %d row and %d col\n",min[i],i,j);
sd=SumofDigits(min[i]);
printf("the sum of the digits of saddle point is %d",sd);
}
}
}
}
int SumofDigits(int n) {
int sum=0,rem;
printf("inside sd");
while(n!=0) {
rem=n%10;
sum=sum+rem;
n=n/10;
}
return sum;
}
4(a). Write a C program to read and display the 1D integer array. Use recursive function named
“Sort” to sort integer array elements in ascending order. Pass 1D array as argument to the
function. Demonstrate with neat diagram the function call and return for taking suitable input.
Ans:
#include <stdio.h>
// Function to display the elements of the array
void displayArray(int arr[], int size) {
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Recursive function to sort the array in ascending order
void sort(int arr[], int size) {
if (size <= 1) {
return; // Base case: Already sorted if the array has 1 or 0 elements
}
// Find the maximum element and its index in the unsorted part of the array
int maxIndex = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
// Swap the maximum element with the last element in the unsorted part
int temp = arr[maxIndex];
arr[maxIndex] = arr[size - 1];
arr[size - 1] = temp;
// Recursive call to sort the remaining unsorted part of the array
sort(arr, size - 1);
}
int main() {
int n;
// Read the size of the array
printf("Enter the size of the array: ");
scanf("%d", &n);
// Read the elements of the array
int arr[n];
printf("Enter %d integer elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the original array
displayArray(arr, n);
// Call the sort function to sort the array
sort(arr, n);
// Display the sorted array
printf("Sorted array in ascending order:\n");
displayArray(arr, n);
return 0;
}
Function Call and Return Diagram:
Main Function
|
|__ sort(arr, n)
|
|__ sort(arr, n-1)
|
|__ sort(arr, n-2)
.
|
|__ sort(arr, 1)
|
|__ Base Case (size <= 1)
||
| |__ Return to the previous level
|
|__ Swap and Return to the previous level
.
.
|
|__ Display Sorted Array
|
|__ Display Original Array
4(b). Write a C program to read and display a 2D integer array. Write a function Statistics() that
accepts 2D array as argument to the function. The function Statistics() will find sum and
average of all elements of an array and return sum and average using pointers.
Ans:
#include <stdio.h>
// Function to calculate sum and average of all elements in a 2D array
void Statistics(int rows, int cols, int arr[rows][cols], int *sum, float *average) {
*sum = 0;
*average = 0.0;
// Calculate sum
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
*sum += arr[i][j];
}
}
// Calculate average
*average = (float)(*sum) / (rows * cols);
}
// Function to display the 2D array
void displayArray(int rows, int cols, int arr[rows][cols]) {
printf("Array elements:\n");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("%d\t", arr[i][j]);
}
printf("\n");
}
}
int main() {
int rows, cols;
// Input the number of rows and columns
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare a 2D array with the specified number of rows and columns
int arr[rows][cols];
// Input elements of the 2D array
printf("Enter %d x %d array elements:\n", rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
scanf("%d", &arr[i][j]);
}
}
// Display the original array
displayArray(rows, cols, arr);
// Calculate and display statistics using the Statistics function
int sum;
float average;
Statistics(rows, cols, arr, &sum, &average);
printf("\nStatistics:\n");
printf("Sum of all elements: %d\n", sum);
printf("Average of all elements: %.2f\n", average);
return 0;
}
5(a). Describe the following with the help of an example.
i) Any two methods for initializing the structure members.
ii) Structure within structure.
Ans:
i) Method 1: Member-wise Initialization:
In this method, you initialize each member of the structure individually.
#include <stdio.h>
// Define a structure
struct Point {
int x;
int y;
};
int main() {
// Declare a structure variable
struct Point p1;
// Initialize members individually
p1.x = 5;
p1.y = 10;
// Print the values
printf("Point coordinates: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Method 2: Initializing at Declaration: You can also initialize structure members at the time of
declaration.
#include <stdio.h>
// Define a structure
struct Point {
int x;
int y;
};
int main() {
// Declare and initialize structure at the same time
struct Point p1 = {5, 10};
// Print the values
printf("Point coordinates: (%d, %d)\n", p1.x, p1.y);
return 0;
}
ii) You can nest structures within other structures to create more complex data structures.
#include <stdio.h>
// Define a structure for a date
struct Date {
int day;
int month;
int year;
};
// Define a structure for a person
struct Person {
char name[50];
int age;
struct Date birthdate; // Structure within structure
};
int main() {
// Declare and initialize a person with birthdate
struct Person person1 = {"John Doe", 25, {1, 1, 1998}};
// Print the person's information
printf("Person: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Birthdate: %d/%d/%d\n", person1.birthdate.day, person1.birthdate.month,
person1.birthdate.year);
return 0;
}
In this example, the Person structure contains a member birthdate, which is of type Date,
representing the birthdate of the person. This illustrates the concept of a structure within a
structure.
5(b). Develop a Sales Report Generation System in C using an array of structures. The program
should allow users to input sales data for N salespersons, including their name, sales amount
for three different products, and generate a report displaying total sales and commission for
each salesperson, assuming commission is 5% of total sales.
Ans:
#include <stdio.h>
// Define a structure for salesperson
struct Salesperson {
char name[50];
float sales[3]; // Sales for three different products
float totalSales;
float commission;
};
// Function to calculate commission (assuming 5%)
float calculateCommission(float totalSales) {
return 0.05 * totalSales;
}
int main() {
int N; // Number of salespersons
printf("Enter the number of salespersons: ");
scanf("%d", &N);
// Declare an array of structures to store salesperson data
struct Salesperson salespersons[N];
// Input sales data for each salesperson
for (int i = 0; i < N; ++i) {
printf("\nEnter details for Salesperson #%d:\n", i + 1);
printf("Name: ");
scanf("%s", salespersons[i].name);
// Input sales for three different products
for (int j = 0; j < 3; ++j) {
printf("Enter sales for Product %d: ", j + 1);
scanf("%f", &salespersons[i].sales[j]);
salespersons[i].totalSales += salespersons[i].sales[j];
}
// Calculate commission
salespersons[i].commission = calculateCommission(salespersons[i].totalSales);
}
// Display the sales report
printf("\nSales Report:\n");
printf("%s %s %s %s %s\n", "Name", "Product 1", "Product 2", "Product 3", "Total Sales");
for (int i = 0; i < N; ++i) {
printf("%s %f %f %f %f\n",
salespersons[i].name,
salespersons[i].sales[0],
salespersons[i].sales[1],
salespersons[i].sales[2],
salespersons[i].totalSales);
}
printf("\nCommission Report:\n");
printf("%s %s\n", "Name", "Commission");
for (int i = 0; i < N; ++i) {
printf("%s %f\n", salespersons[i].name, salespersons[i].commission);
}
return 0;
}

You might also like