C Programming BCA Practical Slips Solution
Q1. Write a C program to accept n elements of 1D array and then display sum of
all elements of array. [15 Marks]
#include <stdio.h>
int main()
{
int arr[10];
int sum,i;
printf("\nEnter elements : \n");
for(i=0; i<10; i++)
{
printf("Enter arr[%d] : ",i);
scanf("%d",&arr[i]);
}
sum=0;
for(i=0; i<10; i++)
{
sum=sum+arr[i];
}
printf("\nSum of array is : %d" ,sum);
return 0;
}
Q2. Accept n integers in an array. Copy only the non-zero elements to another array
(allocated using dynamic memory allocation). Calculate the sum and average of
non-zero elements. [25 Marks]
#include<stdio.h>
#include<stdlib.h>
void main(){
int a[30], i,n, sum = 0;
int count=0;
int *ptr;
float avg;
printf("\n Enter the total number of elements you want to enter : ");
scanf("%d",&n);
printf("\n Enter element in aaray");
for(i = 0;i<n;i++){
scanf("%d",&a[i]); }
for(i = 0;i<n;i++){
if(a[i]!=0){
count++; }
}
ptr = (int *)malloc(count * sizeof(int));
for(i = 0;i<n;i++){
if(a[i]!=0){
*(ptr+i)=a[i];
sum=sum+*(ptr+i); }
}
avg=sum/count;
printf("sum is %d \n",sum);
printf("avg is %f\n",avg);
getch();
}
No comments:
Post a Comment