Array considered to be a pointer in the arguments - c

I am trying to make a program where the user inserts the price of a certain item of his choice, then that price is stored in a list, and the user can expand that last as he wishes, but there is a problem, even though I have the exact same arguments and parameters, the array "prices" is considered to be a pointer for some reason.
#include <stdio.h>
void ask(char ques, int index, double prices[index], double price)
{
printf("Do you want to expand your list y/n: ");
scanf("%c", &ques);
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
switch (ques)
{
case 'y':
prices[index + 1] = price;
case 'n':
main();
}
}
int main()
{
int index = -1;
double prices[index];
double price;
char ques;
ask(ques, index, prices[index], price);
}
I have this error: argument of type "double" is incompatible with parameter of type "double *"C

A solution using an array on the stack to store the prices.
prices.c
#include <stdio.h>
void ask(double prices[], int *elements, int max_elements)
{
if (*elements >= max_elements) {
printf("List is already full. (%d elements)\n", *elements);
return;
}
while (*elements < max_elements) // as long as there is space left
{
double price;
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
prices[*elements] = price; // store price in array
*elements += 1; // increase number of elements
if (*elements == max_elements) {
printf("List is full. (%d elements)\n", max_elements);
break; // leave loop
}
char ques;
printf("Do you want to expand your list (y/n): ");
scanf(" %c", &ques);
if (ques == 'n') {
break; // leave loop
}
}
}
int main()
{
const int MAX_ELEMENTS = 10000; // 10000 prices should be enough for now
double prices[MAX_ELEMENTS]; // array to store 10000 prices
int elements = 0; // number of prices, currently none
ask(prices, &elements, MAX_ELEMENTS); // let user fill it
for (int i = 0; i < elements; i++) {
printf("%3d: %.2lf\n", i + 1, prices[i]); // print price number and price
}
return 0; // return 0 to indicate no error
}
Let's see how it works so far:
$ gcc -Wall prices.c
$ ./a.out
What do you want the price of the next item to be: 1.11
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 2.22
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 101
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 1000000.99
Do you want to expand your list (y/n): n
1: 1.11
2: 2.22
3: 101.00
4: 1000000.99
$
Test it online: https://onlinegdb.com/x1jVUU6GT

Related

Beginner in C: Can't properly printf first and last element in double array?

I'm trying to display a Wish List on the command line. The user enters the cost of the item, the level of priority (1-3), and whether or not it has financing options (y/n). The inputted values are put in multiple arrays. After the user enters all their values, they're displayed in a table at the end.
Everything in my code works fine except when I try to printf the user inputed cost values (double itemCosts[numOfItems];) in the table. The first and last element don't print properly, even when I input the same price (6225.88) for all of them. The last element is just 0.000000. See included pic of table output.
I tried debugging the issue by separating the cost-related loops and compiling/running them as another file and the costs display correctly...so I'm thinking the bug is somewhere else, but I can't find it.
#define MAX_ITEMS 10
#include <stdio.h>
int main()
{
const double MIN_INCOME = 500, MAX_INCOME = 400000;
int numOfItems;
double netIncome, itemTotal;
double itemCosts[numOfItems];
int itemPriors[numOfItems];
char itemFinOps[numOfItems];
printf("+--------------------------+\n");
printf("+ Wish List Forecaster |\n");
printf("+--------------------------+\n\n");
// Prompt for net monthly income
do
{
printf("Enter your monthly NET income: $");
scanf("%lf", &netIncome);
if (netIncome < MIN_INCOME)
{
printf("ERROR: You must have a consistent monthly income of at least $500.00\n\n");
}
else if (netIncome > MAX_INCOME)
{
printf("ERROR: Liar! I'll believe you if you enter a value no more than $400000.00\n\n");
}
} while (!(netIncome >= MIN_INCOME && netIncome <= MAX_INCOME));
printf("\n");
// Prompt for # of wish list items
do
{
printf("How many wish list items do you want to forecast?: ");
scanf("%d", &numOfItems);
if (!(numOfItems > 0 && numOfItems <= MAX_ITEMS))
{
printf("ERROR: List is restricted to between 1 and 10 items.\n\n");
}
printf("\n");
} while (!(numOfItems > 0 && numOfItems <= MAX_ITEMS));
// Store wish list item details
for (int i = 0; i < numOfItems; i++)
{
printf("Item-%d Details:\n", i + 1);
do //////////////// ******** PROMPT COST ********** //////////
{
printf("Item cost: $");
scanf("%lf", &itemCosts[i]);
if (!(itemCosts[i] >= (double)100))
{
printf(" ERROR: Cost must be at least $100.00\n");
}
} while (!(itemCosts[i] >= (double)100));
do // prompt priority
{
printf("How important is it to you? [1=must have, 2=important, 3=want]: ");
scanf("%d", &itemPriors[i]);
if (!(itemPriors[i] >= 1 && itemPriors[i] <= 3))
{
printf(" ERROR: Value must be between 1 and 3\n");
}
} while (!(itemPriors[i] >= 1 && itemPriors[i] <= 3));
do // prompt finance options
{
printf("Does this item have financing options? [y/n]: ");
scanf(" %c", &itemFinOps[i]);
if (!(itemFinOps[i] == 'y' || itemFinOps[i] == 'n'))
{
printf(" ERROR: Must be a lowercase 'y' or 'n'\n");
}
} while (!(itemFinOps[i] == 'y' || itemFinOps[i] == 'n'));
printf("\n");
}
///////// display summary of item details in TABLE //////////
printf("Item Priority Financed Cost\n");
printf("---- -------- -------- -----------\n");
for (int j = 0; j < numOfItems; j++)
{
printf(" %d %d %c %lf\n", j + 1, itemPriors[j], itemFinOps[j], itemCosts[j]);
itemTotal += itemCosts[j];
}
return 0;
}
int numOfItems;
double netIncome, itemTotal;
double itemCosts[numOfItems];
int itemPriors[numOfItems];
char itemFinOps[numOfItems];
It is undefined behaviour as your numOfItems is not inilized. In C table will not grow or shrink to the size when you change this variable
Change to:
double itemCosts[MAX_ITEMS];
int itemPriors[MAX_ITEM];
char itemFinOps[MAX_ITEM];
Always check the result of scanf. Exmaple:
if(scanf("%lf", &netIncome) != 1){ /* handle error*/}
As Vlad from Moscow and 0___________ said, you cannot define an array using a not initialised variable for the number of its elements. You can define the variables as
double *itemCosts;
int *itemPriors;
char *itemFinOps;
and after the variable numOfItems is given a value, you dynamically allocate memory as follows:
itemCosts = (double*) malloc(numOfItems * sizeof(double));
itemPriors = (int*) malloc(numOfItems * sizeof(int));
itemFinOps = (char*) malloc(numOfItems * sizeof(char));
or
itemCosts = (double*) calloc(numOfItems, sizeof(double));
itemPriors = (int*) calloc(numOfItems, sizeof(int));
itemFinOps = (char*) calloc(numOfItems, sizeof(char));
calloc initialises all elements of array to 0
At the end you must free the allocated memory:
free(itemCosts);
free(itemPriors);
free(itemFinOps);

Why does my program keep printing garbage values?

For some reason when i input my time , description and index and click quit to print the array that i have populated with values and strings, i get a bunch of garbage values printed instead of what i inputed, not sure what im doing wrong. any advice?
For some reason when i input my time , description and index and click quit to print the array that i have populated with values and strings, i get a bunch of garbage values printed instead of what i inputed, not sure what im doing wrong. any advice?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
struct event //data type called event which holds time and description for events
{
int hour; //holds the hour digit between 0-23
int minute; //holds the minute digit between 0-59
char description[41];
//holds the description for the reason of the alarm
};
typedef struct event Event; //allows coder to only have to use "Event" instead of "struct event"
int InputRange(int min, int max);
Event* InputEvent(Event *newEvent);
int AddEventAtIndex(Event list[], Event e, int i);
//int InsertionSortEvent(Event list[], int *p_size, Event e);
//void DisplayEvent(Event e);
//void DisplayEventList(Event list[], int size);
//int DeleteEvent(Event list[], int i, int *p_size);
int main (void)
{
Event EventList[MAX];
Event e;
int i=0;
int eventListSize = 0;
int choice;
do
{
printf("__= Scheduler v1.0 =__\n");
printf("1. Schedule an event.\n");
printf("2. Delete an event.\n");
printf("3. Display schedule.\n");
printf("4. Save schedule.\n");
printf("5. Load schedule.\n");
printf("6. Exit\n");
switch(choice = InputRange(1, 6))
{
case 1: InputEvent( EventList );
i = AddEventAtIndex(EventList, e, i);
break;
/* case 2: pHead = deleteStudent(pHead);
break;
case 3: printf("Press 1 to search by ID or 2 to search by name: \n");
scanf("%d", &search);
if (search == 1){
searchStudentID(pHead);
}
else if (search == 2){
searchStudentlName(pHead);
}
else{
printf("Invalid selection");
}
break;
case 4: displayStudentInfo(pHead);
break;
case 5: saveStudentInfo(pHead);
break;
case 6: end(pHead);
break;*/
default: printf("Exiting Program\n\n");
}
}
while ( choice != 6 );
printf("Index #[]\tTime\tDescription");
for ( int j = 1; j < 6; j++)
{
printf("\n[%d]\n\t%d:%d \t %s", j, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
}
int InputRange(int min, int max)
{
int timenumber;
printf("Please enter a number between %d - %d\n", min, max);
scanf("%d", &timenumber);
printf("\n");
if (timenumber < min || timenumber > max)
{
printf("Invalid Entry\n");
InputRange(min, max);
}
return timenumber;
}
Event* InputEvent(Event *newEvent)
{
if (newEvent != NULL) // quality assurance:
// make sure the pointer is valid
{
printf("Enter the event time:\n");
newEvent->hour = InputRange(0, 23);
newEvent->minute = InputRange(0, 59);
printf("Enter the event description:\n");
fgetc(stdin);
fgets(newEvent->description, 41, stdin);
printf("\n");
}
return newEvent;
}
int AddEventAtIndex(Event list[], Event e, int i)
{
--i;
printf("Where in the array would you like to store this event\n");
i = InputRange(1, 5);
list[i].hour = e.hour;
list[i].minute = e.minute;
strcpy(list[i].description, e.description);
return i;
}
Why does my program keep printing garbage values?
You use non initialized data, in main you have :
Event e;
...
i = AddEventAtIndex(EventList, e, i);
where e is not initialized but used in AddEventAtIndex :
int AddEventAtIndex(Event list[], Event e, int i)
{
...
list[i].hour = e.hour;
list[i].minute = e.minute;
strcpy(list[i].description, e.description);
the behavior of strcpy with an non initialized value is undefined and can have a dramatic consequences.
Probably the call InputEvent( EventList ); must be replaced by InputEvent(&e);
In
for ( int j = 1 ; j < 6 ; j++)
{
printf("\n[%d]\n\t%d:%d \t %s", j, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
You access out of EventList when j is 5 and 6, do for instance :
for ( int j = 0 ; j < MAX ; j++)
{
printf("[%d]\t%d:%d \t %s\n", j+1, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
But you also write entries never set printing 'garbage values', more the fact to print a string non initialized has undefined effect. A way to separate entries set and not set is to initialize all the hours by 24 and to test that value in the loop to write or not the entry.
I also changed the format because the newline after the index is not compatible with printf("Index #[]\tTime\tDescription"); and it is better to put the other newline after all rather than before to flush the output line, so also change printf("Index #[]\tTime\tDescription"); by puts("Index #[]\tTime\tDescription");
MAX is not a very good name because it is more a SUP, or just rename it by SIZE
In main you do not use eventListSize
In AddEventAtIndex
--i must be done after i = InputRange(1, 5); or just do i = InputRange(1, 5) - 1; else when i values 5 list[i] is out of list so you write out of list with an undefined behavior.
So finally the parameter i is useless, remove it.
The return index is also not used in main, you use it to assign i and do not used the value of i after. AddEventAtIndex do not need to return a value.
In InputRange
You do not check the result of scanf so the value of timenumber is undefined if a non valid integer was enter and if you do not purge the input so all the next scanf to get a number will not success
Also if the value is not in the range you just call InputRange(min, max); without returning its value so you finally return the invalid value, put all in a for(;;) for instance to only return when the value is correct.
You use fgets in InputEvent, to mix it with scanf to read number is a source of problem, replace the scanf by the use of fgets then a sscanf on the read line
In InputEvent
When you do fgetc(stdin); you probably hope to bypass a newline but if the user enter characters after the number in InputRange (supposing a number was enter) fgets will read the first of them and fgets will not get the expected description. The solution is to do fgets then sscanf in InputRange as I said above allowing you to remove that fgetc
A proposal taking into account my remarks :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
struct event //data type called event which holds time and description for events
{
int hour; //holds the hour digit between 0-23
int minute; //holds the minute digit between 0-59
char description[41]; //holds the description for the reason of the alarm
};
typedef struct event Event; //allows coder to only have to use "Event" instead of "struct event"
int InputRange(int min, int max);
Event* InputEvent(Event *newEvent);
void AddEventAtIndex(Event list[], Event e);
//int InsertionSortEvent(Event list[], int *p_size, Event e);
//void DisplayEvent(Event e);
//void DisplayEventList(Event list[], int size);
//int DeleteEvent(Event list[], int i, int *p_size);
int main (void)
{
Event EventList[MAX];
Event e;
int choice;
/* mark uset entries */
for (int i = 0; i != MAX; ++i)
EventList[i].hour = 24;
do
{
printf("__= Scheduler v1.0 =__\n");
printf("1. Schedule an event.\n");
printf("2. Delete an event.\n");
printf("3. Display schedule.\n");
printf("4. Save schedule.\n");
printf("5. Load schedule.\n");
printf("6. Exit\n");
switch(choice = InputRange(1, 6))
{
case 1:
InputEvent( &e );
AddEventAtIndex(EventList, e);
break;
/*case 2: pHead = deleteStudent(pHead);
break;
case 3: printf("Press 1 to search by ID or 2 to search by name: \n");
scanf("%d", &search);
if (search == 1){
searchStudentID(pHead);
}
else if (search == 2){
searchStudentlName(pHead);
}
else{
printf("Invalid selection");
}
break;
case 4: displayStudentInfo(pHead);
break;
case 5: saveStudentInfo(pHead);
break;
case 6: end(pHead);
break;*/
default: printf("Exiting Program\n\n");
}
}
while ( choice != 6 );
puts("Index #[]\tTime\tDescription");
for ( int j = 0 ; j < MAX ; j++)
{
if (EventList[j].hour != 24)
printf("\t[%d]\t%d:%d \t %s\n", j+1, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
}
int InputRange(int min, int max)
{
char line[32];
int timenumber;
for (;;) {
printf("Please enter a number between %d - %d\n", min, max);
if (fgets(line, sizeof(line), stdin) == NULL)
/* EOF */
exit(-1);
if ((sscanf(line, "%d", &timenumber) == 1) &&
(timenumber >= min) &&
(timenumber <= max))
return timenumber;
printf("Invalid Entry\n");
}
}
Event* InputEvent(Event *newEvent)
{
if (newEvent != NULL) // quality assurance:
// make sure the pointer is valid
{
printf("Enter the event time:\n");
newEvent->hour = InputRange(0, 23);
newEvent->minute = InputRange(0, 59);
printf("Enter the event description:\n");
fgets(newEvent->description, sizeof(newEvent->description), stdin);
printf("\n");
}
return newEvent;
}
void AddEventAtIndex(Event list[], Event e)
{
printf("Where in the array would you like to store this event\n");
int i = InputRange(1, 5) - 1;
list[i].hour = e.hour;
list[i].minute = e.minute;
strcpy(list[i].description, e.description);
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall c.c
pi#raspberrypi:/tmp $ ./a.out
__= Scheduler v1.0 =__
1. Schedule an event.
2. Delete an event.
3. Display schedule.
4. Save schedule.
5. Load schedule.
6. Exit
Please enter a number between 1 - 6
1
Enter the event time:
Please enter a number between 0 - 23
2
Please enter a number between 0 - 59
22
Enter the event description:
descr1
Where in the array would you like to store this event
Please enter a number between 1 - 5
1
__= Scheduler v1.0 =__
1. Schedule an event.
2. Delete an event.
3. Display schedule.
4. Save schedule.
5. Load schedule.
6. Exit
Please enter a number between 1 - 6
1
Enter the event time:
Please enter a number between 0 - 23
3
Please enter a number between 0 - 59
33
Enter the event description:
descr2
Where in the array would you like to store this event
Please enter a number between 1 - 5
4
__= Scheduler v1.0 =__
1. Schedule an event.
2. Delete an event.
3. Display schedule.
4. Save schedule.
5. Load schedule.
6. Exit
Please enter a number between 1 - 6
12
Invalid Entry
Please enter a number between 1 - 6
6
Exiting Program
Index #[] Time Description
[1] 2:22 descr1
[4] 3:33 descr2
note the empty line in the final print, this is because the newline is part of the description, it must be remove is present in InputEvent

Structure C: Storing values in an array

Can anyone advise why values are not getting stored in struct array?
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
This is what I tried:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int menu(void);
struct item
{
int i_SKU;
int i_QUANTITY;
int i_PRICE;
};
int main()
{
int i,j = 0;;
int n;
int input;
//struct item item1[10] = { {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0} };
struct item item1[]={0};
struct item buff[]={0};
//printf("size of %d", sizeof(item1)/sizeof(item1[0]));
printf("Welcome to the Inventory\n");
printf("===================\n");
B: printf("Please select from the following:\n");
A: menu();
scanf("%d", &input);
switch (input)
{
case 1:
printf("Inventory\n");
printf("=========================================\n");
printf("ku Price Quant\n");
for (i = 0; i < sizeof(buff)/sizeof(buff[0]); i++)
{
printf("%d %d %d\n", buff[i].i_SKU, buff[i].i_PRICE, buff[i].i_QUANTITY);
}
printf("=========================================\n");
goto B;
case 2:
//n = sizeof(item1)/sizeof(item1[0]) + 1;
//for (i=n; i < ; i++)
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
printf("Quantity:");
buff[j].i_QUANTITY=scanf("%d", &item1[j].i_QUANTITY);
printf("Price:");
buff[j].i_PRICE=scanf("%d", &item1[j].i_PRICE);
printf("The item added.\n");
j=j+1;
goto B;
case 0:
printf("bye!");
exit(1);
default:
printf("Invalid input, try again:\n");
goto A;
}
return 0;
}
int menu(void)
{
printf("1) Display.\n");
printf("2) Add to inventory.\n");
printf("0) Leave.\n");
printf("Select:");
return 0;
}
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
scanf doesn't return the value it reads, it returns the number of characters it reads.
So these lines:
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
buff[j].i_SKU=scanf("%d", &item1[j].i_QUANTITY);
buff[j].i_SKU=scanf("%d", &item1[j].i_PRICE);
don't do what you want. They put the integer into item1[j].i_X, but assign buff[j].i_X to the number of characters read.
Also, I'm guessing you intended the left hand side of those three equations to differ, not all refer to i_SKU.
Another possible problem: your buffers don't have a length specified, so they will probably just have storage for one element.
EDIT:
I'm not sure what purpose the items1 array serves in your code, but if you want the value in both arrays, you can try the following:
int sku;
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &sku);
item1[j].i_SKU = sku;
buff[j].i_SKU = sku;
// etc.

my program fails when I build and succeeds when I rebuild?

Whenever I build my program using visual studio 2015, it says it fails, but when I rebuild immediately after, it says it succeeded. Another question is how do i store multiple inputs for SKU, price and price and then properly output it.
#include <stdio.h>
#define MAX_ITEMS 10
struct Item
{
int sku_[10];
int quantity_[10];
float price_[10];
};
int main(void)
{
int size = 0;
int input =1;
int i;
int j;
struct Item items[10];
printf("Welcome to the Shop\n");
printf("===================\n");
printf("Please select from the following options\n");
while (size <= MAX_ITEMS && input != 0)
{
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n);
printf("Select:");
scanf_s("%d", &input);
while (input < 0 || input >2 && input != 0)
{
printf("Invalid input, try again: Please select from the following);
printf("1)Display the inventory.\n2)Add to the inventory.\n0) Exit.\n");
printf("Select:");
scanf_s("%d", &input);
}
if (input == 1)
{
printf("Inventory\n");
printf("====================\n");
printf("Sku Price Quantity\n");
printf("%d", items[size].sku_);
}
else if (input == 2)
{
printf("Please input a SKU number:");
if (size >= MAX_ITEMS)
{
printf("The inventory is full");
}
else if (size < MAX_ITEMS)
{
scanf_s("%d", &items[size].sku_);
printf("Quantity:");
scanf("%d", &items[size].quantity_);
printf("Price:");
scanf("%f", &items[size].price_);
printf("The item is successfully added to the inventory.\n");
size += 1;
}
}
else if (input == 0)
{
printf("Good bye");
}
}
}
Here are errors detected in the source code:
1- As WhozCraig suggests, two printf() calls are bad terminated.
Instead of:
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n);
...
printf("Invalid input, try again: Please select from the following);
Add a text terminator:
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n");
...
printf("Invalid input, try again: Please select from the following");
2- When entering items[size].sku_, or .quantity_, or .price_, use a pointer to a value instead of a pointer to a array of value. The struct Item is malformed.
Just modify the struct Item:
struct Item
{
int sku_; // unexpected use [10];
int quantity_; // unexpected use [10];
float price_; // unexpected use [10];
};
3- When printing the inventory, use a loop and not the last index. And format all attributes of each items[i] to align with the header.
printf("Sku Price Quantity\n");
for(i=0;i<size;i++) {
printf("%6d %8d %6.2f\n", items[i].sku_,items[i].quantity_,items[i].price_);
}

2 questions on typedef struct and averages on grades. Am I doing it correctly In C?

I need help on two questions, Its not homework but its to study for an exam. I need to have these questions because i was allowed 1 full page of notes for the exam. If you could help me these two simple questions for me that would be great. Here are the questions:
"Write a function called getGrades. The function that repeatedly prompts the user for positive integers until the user enters a negative value to stop. The function should return the average of these grades and the highest grade."
"Write a function called Get_Info that takes a pointer to a student structure, (that has three fields: char array called name, an int id, and a double gpa) as its only argument. The function prompts the user for the required information to fill the structure and stores it in the appropriate fields."
What I have so far, Let me know if they are correct and if i need to add anything.
1.
double getGrades() {
double average;
double i;
For(i=1 ; i<i; i++)
{
printf("Enter Grade1:\n");
scanf("%lf", &i);
}
if (i<0)
{
(double) average == (grade1 + grade2 + grade3) / 3;
return average;
}
}
2.
typedef struct {
int id;
double gpa;
char name[SIZE];
} student;
void Get_Info(student list[], int num) {
int i;
for(i=0; i<num; i++) {
printf("\nName:%s", list[i].name);
printf("\nGPA:%lf", list[i].gpa);
printf("\nID: %d\n", list[i].id);
}
}
On #1: The requirement is that the function accept ints. You are scanning for doubles.
The requirement is "The function should return the average of these grades and the highest grade." You only return one double, when two different outputs are called for.
Your for loop is written as "For" (C is case-sensitive), and is based on the test i<i. When will i ever be less than itself??
Here's my version of it.
double getGrades(int* max)
{
int sum = 0;
int input;
int i = 0;
*max = 0;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
while (input > 0) {
if (*max < input) {
*max = input;
}
sum = sum + input;
i++;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
}
return i? ((double)sum / i) : 0;
}
Your #2 is much better than your #1, but still has some errors:
The requirement is that the function takes a pointer to a student struct, NOT an array.
It should then print a series of Prompts, and get a series of answers (just as you did in #1).
This is a sequence of printf/scanf.
And when using scanf, you typically pass the ADDRESS of the variable, using &.
(strings are a exception, however)
Here is my version:
typedef struct {
char name[SIZE];
int id;
double gpa;
} student;
void Get_Info(student* ps) {
printf("Enter Name\n");
scanf("%s", ps->name);
printf("Enter ID:\n");
scanf("%d", &ps->id);
printf("Enter GPA\n");
scanf("%lf", &ps->gpa);
}
Try this. It should seem intuitive enough:
double getGrades() {
double average;
double grade;
double total = 0;
int count = 0;
while (1) {
printf("Enter grade: ");
scanf("%d", &grade);
if (grade < 0) {
if (count == 0) {
average = 0;
break;
}
average = total/count;
break;
}
count++;
total += grade;
}
return average;
}

Resources