passing struct array to function for inputting value - c

Need to pass a struct array to 2 functions so that the user can input the values.
This is the structure needed:
struct Sale {
double quantity;
double unit_p;
char taxable;
};
Calling the function in the main functions as:
no_sales = enter(sales, MAX_SALES);
total(sales, no_sales);
and i am inputting values by:
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
printf("Unit Price : ");
scanf("%lf", &s[i].unit_p);
printf("Taxable(y/n) : ");
scanf("%*c%c%*c", &s[i].taxable);
It compiles fine in gcc compiler. When I ran the program I can enter the values but when I try to print the values it displays all values as 0. The values are not being stored in struct array
output I am getting:
Quantity : 2
Unit Price : 1.99
Taxable(y/n) : y
Quantity Unit Price
0.000000 0.000000
The whole code:
program accepts the values and calculates total price in 2 separate functions
#include <stdio.h>
const int MAX_SALES = 10;
struct Sale {
double quantity;
double unit_p;
char taxable;
};
void total(const struct Sale *s,int n);
int enter(struct Sale *s, int M);
int main()
{
int no_sales;
struct Sale sales[MAX_SALES];
printf("Sale Records \n");
printf("=============\n");
no_sales = enter(sales, MAX_SALES);
total(sales, no_sales);
}
int enter(struct Sale *s, int M)
{
int i = 0;
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
while(s[i].quantity != 0) {
printf("Unit Price : ");
scanf("%lf", &s[i].unit_p);
printf("Taxable(y/n) : ");
scanf("%*c%c%*c", &s[i].taxable);
i++;
if(i == M) {
printf("Maximum exceeded\n");
break;
}
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
}
int j;
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[i].quantity, s[i].unit_p, s[i].taxable);
}
return i;
}
void total(const struct Sale *s,int n)
{
int i, subtot = 0, hst = 0, tot = 0;
for(i = 0; i < n; i++) {
subtot = subtot + (s[i].quantity * s[i].unit_p);
if(s[i].taxable == 'y' || s[i].taxable == 'Y') {
hst = hst + (0.13 * s[i].quantity * s[i].unit_p);
}
}
tot = subtot + hst;
printf("\n%-12s%.2lf", "Subtotal", subtot);
printf("\n%-12s%.2lf", "HST (13%)", hst);
printf("\n%-12s%.2lf\n", "Total", tot);
}

In function enter() you are using the wrong index variable i to access the struct:
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[i].quantity, s[i].unit_p, s[i].taxable);
}
which should be
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[j].quantity, s[j].unit_p, s[j].taxable);
}
Second, in function total(), your variables for calculating the totals, should be of type double
int i;
double subtot = 0, hst = 0, tot = 0;
...

Related

Can somebody help on how to return each array in function and then calling it all at main function? [c]

So here's my code:
#include <stdio.h>
double CalculateFinalScore(int assignment[], int midterm[], int finalExam[], double *scoreSum[]) {
int i = 0;
for (i = 0; i < 4; ++i) {
*scoreSum[i] = (assignment[i] * 0.2) + (midterm[i] * 0.3) + (finalExam[i] * 0.5);
}
}
int main(void) {
const int NUM_SCORES = 4; // Array size
double testScores[NUM_SCORES]; // User test scores
int i = 0;
double finalScore = 0.0;
int x[100];
int y[100];
int z[100];
double q;
// Prompt user to enter test scores
printf("Enter %d students test scores:\n", NUM_SCORES);
for (i = 0; i < NUM_SCORES; ++i) {
printf("Input student %d assignment score: ", (i+1));
scanf("%d", &(x[i]));
printf("Input student %d midterm score: ", (i+1));
scanf("%d", &(y[i]));
printf("Input student %d final exam score: ", (i+1));
scanf("%d", &(z[i]));
printf("\n");
}
printf("\n");
// Call function to calculate final score
CalculateFinalScore(x, y, z, &q);
for (i = 0; i < NUM_SCORES; ++i) {
printf("Final student test score: ");
printf("%lf\n", q);
}
return 0;
}
Basically, I want to have an output that display the final score for each student that I have inputed before. But the when my code tries to display the output its always segmentation fault. I tried to return the array before but it seems that it doesn't fix it. Can somebody help me?
Using your code (not tested)
#include <stdio.h>
#include <stdint.h>
#define NUM_SCORES 4
double CalculateFinalScore(int assignment[], int midterm[], int finalExam[], double scoreSum[], uint8_t num_scores)
{
int i = 0;
for (i = 0; i < num_scores; ++i)
{
scoreSum[i] = (assignment[i] * 0.2) + (midterm[i] * 0.3) + (finalExam[i] * 0.5);
}
}
int main(void)
{
double testScores[NUM_SCORES]; // User test scores
int i = 0;
int x[NUM_SCORES];
int y[NUM_SCORES];
int z[NUM_SCORES];
// Prompt user to enter test scores
printf("Enter %d students test scores:\n", NUM_SCORES);
for (i = 0; i < NUM_SCORES; ++i)
{
printf("Input student %d assignment score: ", (i+1));
scanf("%d", &(x[i]));
printf("Input student %d midterm score: ", (i+1));
scanf("%d", &(y[i]));
printf("Input student %d final exam score: ", (i+1));
scanf("%d", &(z[i]));
printf("\n");
}
printf("\n");
// Call function to calculate final score
CalculateFinalScore(x, y, z, testScores, NUM_SCORES);
for (i = 0; i < NUM_SCORES; ++i)
{
printf("Final student %d test score: ", )i+1));
printf("%lf\n", testScores[i]);
}
return 0;
}
You are passing a single double while your function need an array
Your function needs an array of double, not a pointer to an array of double

Sort by using Structure's arrays

So I want to sort the list so that i can give them their position according to their grades but it's not working.
It is Showing error like : incompatible types when assigning to type char from type struct info.
p.s : I am trying to do this sorting using Structures.
#include <stdio.h>
#define SIZE 3
struct info {
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE];
int i, j;
char temp;
int avg;
for (i = 0; i < SIZE; i++) {
printf("Enter your name : ");
scanf("%s", list[i].name);
printf("Enter your number : ");
scanf("%d", & list[i].number);
printf("Enter your grade : ");
scanf("%lf", & list[i].grade);
}
for (i = 0; i < SIZE; i++) {
printf("Name : %s Student Number : %d Grade : %f", list[i].name,
list[i].number, list[i].grade);
printf("\n");
}
for (i = 0; i < SIZE; i++) {
for (j = i + 1; j < SIZE; j++) {
if (list[j].grade > list[i].grade) {
temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
for (i = 0; i < SIZE; i++) {
printf("%d st Position : Name : %s Student Number : %d Grade : %f ",i,
list[i].name, list[i].number, list[i].grade);
printf("\n");
}
avg = 0;
for (i = 0; i < SIZE; i++)
avg += list[i].grade;
avg = avg / 3;
printf("Average is %d", avg);
getch();
return 0;
}
errors are in the following code:
for(i=0;i<SIZE;i++) {
for(j=i+1;j<SIZE;j++) {
if(list[j].grade>list[i].grade) {
temp=list[j];
list[j]=list[i];
list[i]=temp;
}
}
}
You assign a type char with name temp and try to assign a struct to it. Instead create a struct temp and then sort your array of structs.
#include <stdio.h>
#define SIZE 3
struct info { // use typedef struct info instead
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE]; // allows you to write info list[size]
int i, j; // do not initialize loop variables outside of their loops unless you need to(makes it easier to read the loop statements/spot mistakes)
char temp; // you need to use a type info, not char e.g. info temp
I can not compile it myself at the moment, so please let us know in the comments if you have any further questions.

How do i get this C code to work?

My knowledge is limited so bear with me but I am experimenting with creating functions and this is what I got so far but it doesn't. All advice is appreciated! Try to create a function that collects input from the user
#include<stdio.h>
int GetIntFromUser(int grades[5]);
int GetIntFromUser(int grades[5])
{
int counter = 0;
int incre = 1;
while(counter < 4)
{
printf("Please enter GPA %d: ",incre);
scanf("%d",&grades[counter]);
incre++;
counter++;
}
}
int main()
{
int sum = 0;
int grades[5];
int counter = 0;
printf(GetIntFromUser());
while(counter < 4)
{
sum = sum + grades[counter];
counter++;
}
float gpa = (float)sum/counter;
printf("The average GPA is %.2f\n",gpa);
return 0;
}
Try this:
#include<stdio.h>
void GetIntFromUser(int grades[5]); //void since you do not return anything
void GetIntFromUser(int grades[5])
{
int counter = 0;
int incre = 1;
while(counter < 4)
{
printf("Please enter GPA %d: ",incre);
scanf("%d",&grades[counter]);
incre++;
counter++;
}
}
int main()
{
int sum = 0;
int grades[5];
int counter = 0;
GetIntFromUser(grades); // Correct function call
while(counter < 4)
{
sum = sum + grades[counter];
counter++;
}
float gpa = (float)sum/counter;
printf("The average GPA is %.2f\n",gpa);
return 0;
}
You also have an array of 5 elements but you only use 4.

Complex numbers using struct

I want to write a program that reads an array of complex numbers until 0+0j is entered and calculates the absolute value of these numbers and gives the maximum value.
i create a struct which includes im and re.
i take numbers from user and check it whether it is equal to 0+0j
i send the inputs array to absc function
in absc function i created a new array which is equal to sqrt(re^2+im^2) and i send this new array to another function find_max
in find_max i find the max value of absolute array.
Then i print the max value.
However, i fail and i don't understand where should correct.
#include<stdio.h>
#include<math.h>
#define SIZE 5
struct stComplex
{
int re, im;
};
typedef struct stComplex Complex;
float absc(float[]);
float find_max(float[]);
int main()
{
Complex inputs[SIZE]; //Array for inputs
int i;
float max;
for(i = 0; i < SIZE; i++
printf("Enter real part of complex number: ");
scanf("%d", &inputs[i].re);
printf("Enter imaginary part of complex number: ");
scanf("%d", &inputs[i].im);
if(inputs[i].re != 0 and inputs[i].im != 0)
{
continue;
}
else
{
return 1;
}
}
max = absc(Complex inputs[SIZE]); //Sending the real and imaginary parts to calculate absolute value
printf("The biggest absolute value is %f", max);
return 0;
}
float absc(Complex x[SIZE])
{
int i;
float absolute[SIZE], max;
for(i = 0; i < SIZE; i++)
{
absolute[i] = sqrt(pow(inputs[i].re, 2) + pow(inputs[i].im, 2));
}
max = find_max(absolute[SIZE]);
return max;
}
float find_max( float array[SIZE] )
{
int i, max;
max = array[0];
for( i = 1; i < SIZE; i++ )
{
if( max < array[ i ] )
max = array[ i ];
}
return max;
}
#include<stdio.h>
#include<math.h>
#define SIZE 5
struct stComplex
{
int re, im;
};
typedef struct stComplex Complex;
float absc(Complex inputs[]);
float find_max(float[]);
int main()
{
Complex inputs[SIZE]; //Array for inputs
int i;
float max;
for(i = 0; i < SIZE; i++)
{
printf("Enter real part of complex number: ");
scanf("%d", &inputs[i].re);
printf("Enter imaginary part of complex number: ");
scanf("%d", &inputs[i].im);
if(inputs[i].re != 0 && inputs[i].im != 0)
{
continue;
}
else
{
return 1;
}
}
max = absc(inputs); //Sending the real and imaginary parts to calculate absolute value
printf("The biggest absolute value is %f", max);
return 0;
}
float absc(Complex inputs[SIZE])
{
int i;
float absolute[SIZE], max;
for(i = 0; i < SIZE; i++)
{
absolute[i] = sqrt(pow(inputs[i].re, 2) + pow(inputs[i].im, 2));
}
max = find_max(absolute);
return max;
}
float find_max( float array[SIZE] )
{
int i, max;
max = array[0];
for( i = 1; i < SIZE; i++ )
{
if( max < array[ i ] )
max = array[ i ];
}
return max;
}

Typing a letter into a number array

I have this simple project where I'm supposed to create 4 arrays and enter employee's data into, the arrays are: The employee's ID, their salary, the salary cuts, and the net salary. I am also supposed to print the average salary, the ID # of the employee with the highest salary, and the ID # of the employee with the lowest cut.
The code works fine, except if I enter a letter, then it just executes the whole program in a weird way (no formatting, random numbers).
Why is that? The letter gets converted to an integer, right? What causes it to stop working properly?
Also, would you mind looking at the coding style I used and telling me if there's a way I can improve it?
#include <stdio.h>
#define SIZE 100
int main(void){
int n; /*Number of employees*/
float average; /*Average of the employee's salary*/
int max; /*Highest salary*/
int min; /*Minimum cut*/
int i;
int employee_number = 1;; /*The number (index +1) of the employee*/
float sum = 0; /*The sum of the employee's salary*/
int num_highest; /*The number of the employee with the highest
salary*/
int num_lowest; /*The number of the employee with the lowest cut*/
int id_number[SIZE]; /*Array to hold employee's IDs in*/
float salary[SIZE]; /*Array for employee's salaries*/
float cuts[SIZE]; /*Array for salary cuts*/
float net_salary[SIZE]; /*Net salary after cuts*/
printf("Enter the number of employees\t");
scanf("%i", &n);
for(i = 0; i < n; i++){
printf("Enter the ID of employee #%i\t", employee_number);
scanf("%i", &id_number[i]);
printf("Enter the salary of employee #%i\t", employee_number);
scanf("%f", &salary[i]);
printf("Enter the salary cut of employee #%i\t", employee_number);
scanf("%f", &cuts[i]);
employee_number++;
}
for(i = 0; i < n; i++){
net_salary[i] = salary[i] - (salary[i] * cuts[i] * 1/100);
}
for(i = 0; i < n; i++){
sum += net_salary[i];
}
average = sum/(float)n;
printf("The average salary is %.2f\n", average);
max = net_salary[0];
min = cuts[0];
for(i = 0; i < n; i++){
if(net_salary[i] > max){
max = net_salary[i];
num_highest = i;
}
if(cuts[i] <= min){
min = cuts[i];
num_lowest = i;
}
}
printf("Employee with ID # %i has the highest salary which is %i\n", id_number[num_highest], max);
printf("Employee with ID # %i has the lowest cut of %i and a base salary of %.2f", id_number[num_lowest], min, salary[num_lowest]);
}
You should check the value returned by every call to function scanf.
If this value is smaller than the number of input arguments that the function is supposed to obtain from the user, then it has failed and you should call it again.
In terms of coding style, you can use a struct to store information about each employee, and create an employees[] array of structs that way. This helps in organizing your code better, and avoids having to use 4 separate arrays to store information about the employees.
The struct can look like this:
typedef struct {
int id_number;
float salary;
float cuts;
float net_salary;
} employee_t;
And then you can create an array of structs like this:
employee_t employees[n]; /* n is number of employees */
It is also good to check the return of scanf().
So instead of doing simply:
scanf("%i", &n);
Be extra careful and change this to:
if (scanf("%i", &n) != 1) {
/*exit program if true */
}
I wrote some code to demonstrate these points:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id_number;
float salary;
float cuts;
float net_salary;
} employee_t;
void get_number_employees(int *n);
void get_user_input(employee_t employees[], int n, float *average);
void print_results(employee_t employees[], int n, float average);
int highest_salary(employee_t employees[], int n);
int lowest_cut(employee_t employees[], int n);
int
main(void) {
int n;
float average;
get_number_employees(&n);
employee_t employees[n];
get_user_input(employees, n, &average);
print_results(employees, n, average);;
return 0;
}
void
get_number_employees(int *n) {
printf("Enter number of employees: ");
if (scanf("%d", n) != 1) {
printf("Invalid number.\n");
exit(EXIT_FAILURE);
}
}
void
print_results(employee_t employees[], int n, float average) {
int high_sal, low_cut;
high_sal = highest_salary(employees, n);
low_cut = lowest_cut(employees, n);
printf("The average salary is %f\n", average);
printf("Employee with ID # %d has the highest salary which is %f\n",
employees[high_sal].id_number, employees[high_sal].net_salary);
printf("Employee with ID # %d has the lowest cut of %f and a base salary of %f\n",
employees[low_cut].id_number, employees[low_cut].cuts, employees[low_cut].salary);
}
void
get_user_input(employee_t employees[], int n, float *average) {
int i, employee_number = 1, sum = 0;
for (i = 0; i < n; i++) {
printf("Enter the ID of employee #%d: ", employee_number);
if (scanf("%d", &(employees[i].id_number)) != 1) {
printf("Invalid number.\n");
exit(EXIT_FAILURE);
}
printf("Enter the salary of employee #%d: ", employee_number);
if (scanf("%f", &(employees[i].salary)) != 1) {
printf("Invalid salary.\n");
exit(EXIT_FAILURE);
}
printf("Enter the salary cut of employee #%d: ", employee_number);
if (scanf("%f", &(employees[i].cuts)) != 1) {
printf("Invalid cuts.\n");
exit(EXIT_FAILURE);
}
employees[i].net_salary = employees[i].salary - (employees[i].salary * employees[i].cuts * 1/100);
sum += employees[i].net_salary;
employee_number++;
}
*average = (1.0f * sum)/n;
}
int
highest_salary(employee_t employees[], int n) {
float max;
int i, idx;
max = employees[0].net_salary;
for (i = 1; i < n; i++) {
if (employees[i].net_salary > max) {
max = employees[i].net_salary;
idx = i;
}
}
return idx;
}
int
lowest_cut(employee_t employees[], int n) {
float min;
int i, idx;
min = employees[0].cuts;
for (i = 1; i < n; i++) {
if (employees[i].cuts < min) {
min = employees[i].cuts;
idx = i;
}
}
return idx;
}
Letters are char or char* when taken as input for many C and C++ functions. char can generally be output to the console as an ASCII encoded digit or as an integer value.
char can be cast into int very easily in C because it's actually considered a numeric value. For example, A becomes 41, and B becomes 42.

Resources