struct and values entered in C - c

I have a program that does not work. The problem for example is:
You input 2 for students, then enter mark 5 for the first student and then 10 for second student.
The output sum in the fun() function should return 15 . But instead, it returns 20.
This is my code so far:
struct mark{
int x;
};
int main(){
int n;
printf("Enter the number of student: ");
scanf("%d",&n);
struct mark *marks= malloc(n * sizeof(struct mark)); ;
for (int i = 0; i < n; i++ ){
printf("Enter mark: ");
scanf("%d",&(*marks).x);
}
fun(marks,n);
free(marks);
return 0;
}
void fun(struct mark *marks, int n){
int sum =0,i;
for (i = 0; i < n; i++ ){
sum= sum+(*marks).x;
}
printf("Sum: %d \n",sum);
}

scanf("%d",&(*marks).x);
Means you are reading into the first mark in marks.
You already have a for loop and a counter variable for reading into it, so use it. change
sum= sum+(*marks).x;
to
sum= sum+marks[i].x;
which is also equivalent to
sum = sum+(*marks+i).x;
Do the same for
scanf("%d",&(*marks).x);
change it to
scanf("%d",&marks[i].x);
again,
marks[i].x is equivalent to (*marks+i).x
The point is that you want to access the second mark in marks in your second iteration of your for loop. Also, don't forget to free() your marks when your program is done.

change :
scanf("%d",&marks[i].x);
and:
sum= sum+marks[i].x;

Inside main in this piece of code:
for (int i = 0; i < n; i++ ){
printf("Enter mark: ");
scanf("%d",&(*marks).x);
}
You are always assigning mark to 1st array element.
Inside fun in this piece of code:
for (i = 0; i < n; i++ ){
sum= sum+(*marks).x;
}
you are not iterating over the marks array, but instead always reading 1st array value.

Related

C Programming How to get results of an mathematical operation stored in a different array?

I am trying to subtract a given number from an array and then store the results in a completely different array. Is it possible to write the code without using pointers?
I am trying to write the code with using for loop and or do/while loop.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int num[100];
int i ;
int size;
int sub;
int diff[100];
printf("Enter the size of the array: ");
scanf("%d", &size);
for(i=0;i<size; i++){
printf("Enter the element %d :", i+1);
scanf("%d", &num[i]);
}
printf(" Enter the number to substract: \n");
scanf("%d", &sub);
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}
for (y=0; y<size; y++)
{
printf("%d", diff[y]);
}
}
After I scan the results, I tried different ways to initialize and store the values in the second array but haven't been successful. What mistake am I making here?
y = num[i] - sub;
This is fine, as it's the result of subtraction for a given source array element.
scanf("%d", &diff[y]);
This doesn't make sense, as it's attempting to read input from the user. Not only that, it's using the result of the subtraction as the index of the destination array.
Just assign the result of the subtraction to the corresponding destination array member:
diff[i] = num[i] - sub;
In your question, you try to scan the value to another array, but the correct form is to assign the value in the new array position.
For example, in your first for loop use the i variable as the position and assign num[i] - sub on diff[i]:
for (i = 0; i < size; i++)
{
diff[i] = num[i] - sub;
}
instead of:
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}

Find the mistake in the code ā€” we have to print the sum of elements of the array of any size

The elements of the array have to be taken as input from the user. Here I am using an array of size 10. I am getting the sum as 0 if I initialized it with sum = 0; while declaring, and if I didn't, I am getting a garbage value.
Here is the code:
#include <stdio.h>
int main(void)
{
int barray[10], i=0, sum=0;
for(i=0;i<10;i++ ){
printf("Enter the value for barray[%d] element of the array : ",i);
scanf("%d", &barray[i]);
}
while(i >=0 && i<10)
{
sum += barray[i];
i++;
}
printf("The sum of the elements of the array is %d", sum);
}
The problem with your code is that i is not a variable declared in the scope of the for loop but in the scope of main, so when the for loop is done i=10 and then the contents of the while loop are skipped as the condition for i to be greater than 0 and less than 10 are never met.
To fix this you should set i to zero after the for loop
scanf("%d", &barray[i]);
}
i = 0; // add this
while(i >=0 && i<10)
{
or change the while loop to a for loop like the first one. Though I would recommend as good practice and for cleaner code to declare the iterator variable inside the context of the for loop unless you need to access it outside of it, like so.
int main(void)
{
int barray[10], sum=0;
for (int i = 0; i < 10; i++) {
printf("Enter the value for barray[%d] element of the array : ", i);
scanf("%d", &barray[i]);
}
for (int i = 0; i < 10; i++) {
sum += barray[i];
}
printf("The sum of the elements of the array is %d", sum);
}

Passing struct array to function and calculating average in C?

Beginner here, I've been trying this for hours and can't get it to work, searched online too and couldn't find an answer.
I'm trying to write a program where you input people by putting their age and height then calculate the average of each, and the average ratio of age to height. Whenever I pass the struct to my getAverage function, it returns the address (I think) instead of the averages.
#include <stdio.h>
#include <stdlib.h>
typedef struct person
{
int age;
double height;
} Person;
double getAv (Person people[50], int max)
{
int i;
double total, retval;
total = 0;
for (i=0; i<=max; i++)
{
total = total + people[i].age;
}
retval = total / max;
return retval;
}
int main (void)
{
Person people[50];
int i;
while (i++, people[i].age>=0)
{
printf ("Person #%d\n", i);
printf ("enter an age: ");
scanf ("%d", &people[i].age);
if (people[i].age<0)
break;
printf ("enter a height: ");
scanf ("%lf", &people[i].height);
printf ("\n");
}
double averageAge;
averageAge = getAv (&people[50], i);
printf ("%.1lf\n", averageAge);
}
Haven't implemented average height or ratio yet, just trying to get average of ages to work for now. When I try taking the & out of averageAge = getAv(&people[50], I); I get a compile error that tells me it needs the &. Any help would be appreciated.
There are serveral issues in you code, the first one:
Person people[50];
int i;
while (i++, people[i].age>=0)
You are using i uninitialized, thus, incrementing a variable containing garbage (or 0 as intended, but it is impossible to guarantee)
To avoid such problems in the future enable warnings on your compiler, the compiler would have told you something like:
ā€˜iā€™ is used uninitialized in this function [-Wuninitialized]
So switch to
Person people[50] = {0};
int i = 0;
It seems (based on the pre-increment operator ++i) that you want to use arrays with base 1, there is nothing wrong with that, but in your average function you are starting from 0, so use a for:
for (i = 0; ; i++)
{
...
if (people[i].age <= 0) break;
...
}
Another issue:
double averageAge;
averageAge = getAv (&people[50], i);
In this way you are passing only element 50 which is not part of your array (remember arrays are base 0 in C), to pass the entire array:
averageAge = getAv (people, i);
or
averageAge = getAv (&people[0], i);
The last one:
for (i=0; i<=max; i++)
You are including the element discarded when you was checking for age > 0, switch to:
for (i=0; i<max; i++)
A minor issue:
Iif the user enters 0 for the first element of people you end up dividing by 0
double averageAge;
averageAge = getAv (&people[50], i);
printf ("%.1lf\n", averageAge);
should be
if (i > 0)
{
double averageAge;
averageAge = getAv (people, i);
printf ("%.1f\n", averageAge); // No need to use lf (long double)
}
If you do it this way, you need to receive in your function (Person& people[], int n)
Where n is the length of the array.
We use the '&' to not do copies of the array and also you are passing only the element with index 50 in the function, simply do only (people, n)
there are mistakes in this code ,first you should initialize int i to int i=0 in mian function.
how are using this condition while (i++, people[i].age>=0) when you haven't scanned any input it's like using an uninitialized variable. you need a do-while like this
do
{
printf("Person #%d\n", i);
printf("enter an age: ");
scanf("%d", &people[i].age);
if (people[i].age < 0)
break;
printf("enter a height: ");
scanf("%lf", &people[i].height);
printf("\n");
i++;
} while (people[i-1].age >= 0);
also you are sending wrong arguments to your getAv function you should use averageAge = getAv (people, i);.
and in your function you have to remove = in this loop for (i=0; i<=max; i++) .this should be for (i=0; i<max; i++) ,otherwise the negative entered age will also be add to total and will affect the average.

Reading a series of integers to an array?

I'm new to arrays , i want to know if it is possible to fill the array using a for-loop with the scanf function , i made a first attempt but the program isn't working ( it is supposed to fill the array then print all the elements of it )
#include<stdio.h>
void main(){
int n,i;
int table[10];
for(i=1;i<=10;i++){
scanf("%d",table[i]);
}
for(i=1;i<=n;i++){
printf("\n%d",table[i]);
}
getchar();
getchar();
return ;
}
When you declare an array of size N, the elements are indexed from 0 to N - 1. From there, you need to pass the address of your variable to scanf, not the variable itself. Since you are using an array, this becomes very simple.
for (int i = 0; i < 10; ++i)
scanf("%d", table + i);
You should use
scanf("%d", &table[i]);
Additionally the loop should start with 0, because indexes in C start from 0..N-1.
for(i = 0; i < 10; i++)
scanf("%d", &table[i]);
In C, array indexing starts from 0.
Change for loop to
for(i = 0; i < 10; i++) {...}
and
scanf("%d",table[i]);
to
scanf("%d", &table[i]);
^& operator before the variable table[i]

Calendar in c with sum of last row

I'm trying to make a one-month calendar that prints the sum of the last row of days.
The output of this is correct for the calendar, but the sum keeps printing out that it's 0. For an input of 3=day_of_week and 30=days_in_month, the sum should be 26+27+28+29+30 = 140
Thanks.
int main() {
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i=0; i<3*day_of_week; i++)
printf(" ");
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}
I don't understand why you are doing ++day_of_week,
something like this should work better:
int main()
{
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i = 0; i < 3 * day_of_week; i++)
printf(" ");
for (i = 1; i <= days_in_month; i++)
{
printf("%3d", i);
array[i] = i;
if (i % 7 == 0)
printf("\n");
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}
You have
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
but day_of_week does not remain constant in your program and changes before with this statement:
day_of_week++;
Use a second variable to increment and do not modify day_of_week after scanf.
One problem is here:
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
You are allowing day_of_week to go out of range. Your code expects that value to be no more than 7. This loop will result in that variable being set to the value the user entered plus (days_in_month - 1). In your final for loop, the statement 7 - day_of_week will likely be negative, which will throw the rest of your code off.
You are sort of checking for overflow when you test the variable modulo 7 and print a newline. When you do that, set day_of_week = 0 as well.
Also, calculate (days_in_month-(7-day_of_week)) and store it in a temporary variable as soon as you get the input from the user. Since you're manipulating these variables inside your code, your final for loop probably isn't using the values that you think it's using. Alternatively, don't modify the variables that you use for user input and create other variables to use as temporaries.

Resources