CP Week9
CP Week9
Program:
#include <stdio.h>
#include <stdlib.h>
int main( )
{
int i,n; // Size of the array
int *arr; // Pointer to the array
int sum = 0; // Variable to store the sum
// Step 1: Input the size of the array
printf("Enter the size of the array: ");
scanf("%d", &n);
// Step 2: Dynamically allocate memory for the array
arr = (int *)malloc(n * sizeof(int));
// Step 3: Check if memory allocation is successful
if (arr == NULL)
{
printf("Memory allocation failed\n");
return 1; // Exit the program with an error code
}
// Step 4: Input elements of the array from the user
printf("Enter %d elements:\n", n);
for ( i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
// Step 5: Calculate the sum of the array elements
for ( i = 0; i < n; i++)
{
sum += arr[i];
}
// Step 6: Display the sum
printf("Sum of the array elements: %d\n", sum);
// Step 7: Free the dynamically allocated memory
free(arr);
// Step 8: Exit the program successfully
return 0;
}
Result:
Enter the size of the array: 5
Enter 5 elements:
10
20
30
40
50
Sum of the array elements: 150
ii) Write a C program to find the total, average of n students using structures
Aim: To write a C program to find the total, average of n students using structures
Algorithm:
Step1: Input the number of students (n) from the user.
Step 2: Declare a structure to represent a student with fields for name and marks.
Step 3: Declare an array of structures to store information about each student.
Step 4: For each student, input their name and marks from the user.
Step 5: Calculate the total marks by summing up the marks of all students.
Step 6: Calculate the average marks by dividing the total marks by the number of students (n).
Step7: Display the total and average marks.
Step 8: Exit the program.
Program:
#include <stdio.h>
// Define a structure to represent a student
struct Student
{
char name[50];
int marks;
};
int main( )
{
Int i, n;
// Step 1: Input the number of students
printf("Enter the number of students: ");
scanf("%d", &n);
// Step 2: Declare a structure to represent a student
// Step 3: Declare an array of structures to store information about each student
struct Student students[n];
// Step 4: Input details for each student
for ( i = 0; i < n; i++)
{
printf("Enter the name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter the marks of student %d: ", i + 1);
scanf("%d", &students[i].marks);
}
// Step 5: Calculate total marks
int total = 0;
for ( i = 0; i < n; i++)
{
total + = students[i].marks;
}
// Step 6: Calculate average marks
float average = (float)total / n;
// Step 7: Display total and average marks
printf("Total marks: %d\n", total);
printf("Average marks: %.2f\n", average);
// Step 8: Exit the program
return 0;
}
Result:
Enter the number of students: 3
Enter the name of student 1: Alice
Enter the marks of student 1: 85
Enter the name of student 2: Bob
Enter the marks of student 2: 90
Enter the name of student 3: Charlie
Enter the marks of student 3: 78