Am I properly passing parameters and passing by reference? - c

I am getting no output for the grosspay and taxespaid functions for this programming assignment I am writing to keep track of employee payroll. I am just wondering if I am properly passing parameters and passing by reference, which is the method we are supposed to use. My class doesn't meet often and the book sucks so I would appreciate any advice.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
void userinput(char name[][20], int hoursworked[], float rate[]);
void calculatepay(float rate[], int hoursworked[]);
float tax(float grosspay[]);
float totalpay(float grosspay[], float taxespaid[]);
void print(char name[][20], float rate[], int hoursworked[], float grosspay[], float sum, float taxespaid[]);
int main(){
int hoursworked[]={};
float rate[]={};
char name[][20]={};
float grosspay[]={};
float taxespaid[]={};
float sum;
userinput(name, hoursworked, rate);
calculatepay(rate, hoursworked);
sum = tax(grosspay);
totalpay(grosspay, taxespaid);
print(name, rate, hoursworked, grosspay, sum, taxespaid);
return (0);
}
void userinput(char name[][20], int hoursworked[], float rate[]){
for(int i=0; i<SIZE; i++){
printf("Enter name: ");
scanf("%s", &name[i] , 20);
if(name[i][0] == '-' && name[i][1] == '1'){
break;
}
printf("Enter hours worked: ");
scanf("%d", &hoursworked[i]);
if(hoursworked[i] == -1){
break;
}
printf("Enter hourly rate: ");
scanf("%f", &rate[i]);
if(rate[i] == -1){
break;
}
puts("\n");
}
}
void calculatepay(float rate[], int hoursworked[]){
float grosspay[]={};
for(int i=0; i<SIZE; ++i){
if(hoursworked[i]<=40){
grosspay[i] = rate[i] * hoursworked[i];
}
else{
grosspay[i] = (40*rate[i])+((hoursworked[i] - 40)*1.5*rate[i]);
}
}
}
float tax(float grosspay[]){
float taxespaid[]={};
for(int i=0; i<SIZE; ++i){
taxespaid[i] = grosspay[i]*0.2;
return taxespaid[i];
}
return 0;
}
float totalpay(float grosspay[], float taxespaid[]){
float sum = 0.0;
for (int i=0; i<SIZE; i++)
{
sum=sum+(grosspay[i] - taxespaid[i]);
}
return sum;
}
void print(char name[][20], float rate[], int hoursworked[], float grosspay[], float sum, float taxespaid[]){
for(int i=0; i<SIZE; i++){
printf("Pay to: %s\n", name[i] , 20);
if(name[i][0] == '-' && name[i][1] == '1'){
break;
}
printf("Hours worked: %d\n", hoursworked[i]);
if(hoursworked[i] == -1){
break;
}
printf("Hourly rate: %.2f\n", rate[i]);
if(rate[i] == -1){
break;
}
if(hoursworked[i]<=40){
printf("Gross Pay: %.2f\n", grosspay[i]);
}
else
{
printf("Gross Pay: %.2f\n", grosspay[i]);
printf("Base Pay: %.2f\n", rate[i]*40);
printf("Overtime Pay: %.2f\n", grosspay[i] - (rate[i]*40));
}
printf("Taxes paid: %.2f\n", taxespaid[i]);
printf("Net pay: %.2f\n\n", grosspay[i] - taxespaid[i]);
}
printf("Total paid to all employees: %.2f\n", sum);
}

I hate to be the bearer of bad news, but there is no pass-by-reference in C. The only method of parameter passing that C defines is pass-by-value, in 6.5.2.2p4:
In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.
Perhaps you intended to ask about C++, in which case... No, you're not using pass-by-reference.
Otherwise, if you intended to ask how C mimics pass-by-reference, it is by using pointers (that is, the parameters have pointer types and pointer values).
In void userinput(char name[][20], int hoursworked[], float rate[]);, for example, name, hoursworked and rate are all pointer types. The values that are passed will be pointer values. The pointer values point into the objects that are to be modified, so the same outcome is possible (that is, the changes that are made to the array are still visible once the function returns).
In case you're curious as to why this doesn't technically qualify as pass-by-reference, it's because the unary *pointer or array[subscript] (or pointer[subscript] operators are required to change the value pointed to, where-as when pass-by-reference is used you should merely be able to assign a value without those like: array = value;. It makes more sense if you look at it as a test in writing a swap function:
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
If you try calling this function, you will notice that it hasn't successfully swapped its arguments. If you were to use pass-by-value, those three lines would have swapped its arguments. For example, in C++:
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
This will swap the arguments. All I had to change was the function signature; I didn't have to change the way the function is used or the code in the function itself... That is pass-by-reference.

When I declared the variables before main() and initialised the arrays with SIZE then it worked fine :)
#define SIZE 5
void userinput(char name[][20], int hoursworked[], float rate[]);
void calculatepay(float rate[], int hoursworked[]);
float tax(float grosspay[]);
float totalpay(float grosspay[], float taxespaid[]);
void print(char name[][20], float rate[], int hoursworked[], float grosspay[], float sum, float taxespaid[]);
int hoursworked[SIZE];
float rate[SIZE];
char name[SIZE][20];
float grosspay[SIZE];
float taxespaid[SIZE];
float sum;
int main(){
userinput(name, hoursworked, rate);
calculatepay(rate, hoursworked);
sum = tax(grosspay);
totalpay(grosspay, taxespaid);
print(name, rate, hoursworked, grosspay, sum, taxespaid);
return (0);
}
void userinput(char name[][20], int hoursworked[], float rate[]){
int i;
for(i=0; i<SIZE; i++){
printf("Enter name: ");
scanf("%s", &name[i] , 20);
if(name[i][0] == '-' && name[i][1] == '1'){
break;
}
printf("Enter hours worked: ");
scanf("%d", &hoursworked[i]);
if(hoursworked[i] == -1){
break;
}
printf("Enter hourly rate: ");
scanf("%f", &rate[i]);
if(rate[i] == -1){
break;
}
puts("\n");
}
}
void calculatepay(float rate[], int hoursworked[]){
float grosspay[SIZE];
int i;
for(i=0; i<SIZE; ++i){
if(hoursworked[i]<=40){
grosspay[i] = rate[i] * hoursworked[i];
}
else{
grosspay[i] = (40*rate[i])+((hoursworked[i] - 40)*1.5*rate[i]);
}
}
}
float tax(float grosspay[]){
int i;
float taxespaid[SIZE];
for(i=0; i<SIZE; ++i){
taxespaid[i] = grosspay[i]*0.2;
return taxespaid[i];
}
return 0;
}
float totalpay(float grosspay[], float taxespaid[]){
float sum = 0.0;
int i;
for (i=0; i<SIZE; i++)
{
sum=sum+(grosspay[i] - taxespaid[i]);
}
return sum;
}
void print(char name[][20], float rate[], int hoursworked[], float grosspay[], float sum, float taxespaid[]){
int i;
for(i=0; i<SIZE; i++){
printf("Pay to: %s\n", name[i] , 20);
if(name[i][0] == '-' && name[i][1] == '1'){
break;
}
printf("Hours worked: %d\n", hoursworked[i]);
if(hoursworked[i] == -1){
break;
}
printf("Hourly rate: %.2f\n", rate[i]);
if(rate[i] == -1){
break;
}
if(hoursworked[i]<=40){
printf("Gross Pay: %.2f\n", grosspay[i]);
}
else
{
printf("Gross Pay: %.2f\n", grosspay[i]);
printf("Base Pay: %.2f\n", rate[i]*40);
printf("Overtime Pay: %.2f\n", grosspay[i] - (rate[i]*40));
}
printf("Taxes paid: %.2f\n", taxespaid[i]);
printf("Net pay: %.2f\n\n", grosspay[i] - taxespaid[i]);
}
printf("Total paid to all employees: %.2f\n", sum);
}

Related

I get the message: Cannot convert 'float' to 'float*' in assignment and i have some logical mistakes

I have a problem with the compiler and I must have some logical mistakes (C language)
I want to have one void function that gives me the maximum price, the minimum price and the average of a table with maximum 100 prices. And if the user gives price=-1 I want the program to end!
Here is my code:
#include <stdio.h>
void function(float pin[],int j,float *min,float *max,float *mo,int cnt);
int main()
{
int i=0,count=0;
float prc[100],mo;
for(i=0;i<=99;i++)
{
printf("Enter price:");
scanf("%f",&prc[i]);
if(prc[i]==-1)
{
break;
}
count++;
}
int min=prc[0];
int max=prc[0];
void function(float prc,int i,float *min,float *max,float *mo,int count);
printf("Minimum price is:%f Maximum price is:%f and Mo is:%f",min,max,mo);
return 0;
}
void function(float pin[],int j,float *min,float *max,float *mo,int cnt)
{
float sum;
for(j=0;j<=cnt;j++)
{
if(pin[j]<*min)
{
min=pin[j];
}
if(pin[j]>*max)
{
*max=pin[j];
}
sum=+pin[j];
}
*mo=sum/j;
}
Looks like you have lots of little mistakes (missing dereference, using a variable out of scope, wrong operator, etc.):
#include <stdio.h>
void function(float pin[], float *min, float *max, float *mo, int cnt);
int main()
{
int i=0, count=0;
float prc[100], mo;
for (i=0; i<=99; i++)
{
printf("Enter price:");
scanf("%f", &prc[i]);
if (prc[i] == -1)
{
break;
}
count++;
}
float min=prc[0];
float max=prc[0];
function(&prc[0], &min, &max, &mo, count);
printf("Minimum price is:%f Maximum price is:%f and Mo is:%f", min, max, mo);
return 0;
}
void function(float pin[], float *min, float *max, float *mo, int cnt)
{
float sum = 0.0f;
for (int j=0; j < cnt; j++)
{
if (pin[j] < *min)
{
*min = pin[j];
}
if (pin[j] > *max)
{
*max = pin[j];
}
sum += pin[j];
}
*mo = sum / cnt;
}
There are a few mistakes in the function :
I have modified the code and looks to be fine except the function argument mo , decide whether to declare it as a float pointer or a float
Look at the declaration inside main, u are calling a function but the syntax is for declaration.
used mo as argument but mo is defined as float variable whereas the function accepts a pointer as per the declaration and there are a few warning related to the types
Declared ints but printing them using format specifiers for float %f
include
void function(float pin[],int j,float *min,float *max,float *mo,int cnt);
int main()
{
int i=0,count=0;
float prc[100],mo;
for(i=0;i<=99;i++)
{
printf("Enter price:");
scanf("%f",&prc[i]);
if(prc[i]==-1)
{
break;
}
count++;
}
int min=prc[0];
int max=prc[0];
function(prc,i,min,max,mo,count);
printf("Minimum price is:%f Maximum price is:%f and Mo is:%f",min,max,mo);
return 0;
}
void function(float pin[],int j,float *min,float *max,float *mo,int cnt)
{
float sum;
for(j=0;j<=cnt;j++)
{
if(pin[j]<*min)
{
*min=pin[j];
}
if(pin[j]>*max)
{
*max=pin[j];
}
sum=+pin[j];
}
*mo=sum/j;
}
wrong use of pointer and type,use
float min=prc[0];
float max=prc[0];
function(prc,i,&min,&max,&mo,count);
You declare as:
void function(float pin[],int j,float *min,float *max,float *mo,int cnt);
So you must deliver a float-pointer but not a float number.

Vector dot product calculation wrong sum

I want to make a program that can calculate the vectors with the dot product but my sum is always 0 what did I do wrong in this code? I'm new to pointers and functions if that is important to you. I coded everything only in the main function and it worked but I want the calculation in another function because its clearer instead of writing everything in the main function. I compiled it with -Wall and -Werror and I got 0 warnings.
Would be nice if you could help me here :)
Here is the code:
#include<stdio.h>
#include<stdlib.h>
double calculation(int o, double *a, double *b, int sum) {
int i;
for(i=0;i<o;++i) {
printf("Components of first vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &a[i]);
}
for(i=0;i<o;++i) {
printf("Components of second vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &b[i]);
}
for(i=0;i<o;++i) {
sum += a[i] * b[i];
}
return(0);
}
int main() {
int o;
int sum=0;
printf("How many dimensions should the vectors have?\n");
scanf("%d", &o);
double *a = malloc(o * sizeof(double));
double *b = malloc(o * sizeof(double));
if(a==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
if(b==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
calculation(o,a,b,sum);
printf("The dot product is: %d\n", sum);
free(a);
free(b);
a=NULL;
b=NULL;
return(0);
}
In C, variables are passed by value. That means that when you change the value of sum in calculation you only change a local copy.
The idiomatic way when you only need one value is to return it:
double calculation(int o, double *a, double *b) {
double sum = 0.;
...
return sum;
}
and in main:
...
double sum = calculation(o, a, b);
...
Alternatively, if you need to return multiple values, you can pass pointers to the output variables
In double calculation(int o, double *a, double *b, int sum) the last argument is passed by value1. That is, when you call calculation(..., sum);, the variable sum is copied and then passed to the function.
Inside this function, you're modifying sum, but this only modifies the copy of the original variable that was passed. To solve this, pass a pointer or just return the sum from your function.
Actually, all arguments are passed by value. The second and the third ones just happen to be pointers.
This function
double calculation(int o, double *a, double *b, int sum) {
should change
double calculation(int o, double *a, double *b, double & sum) {
The problem with your code is that the sum is a local variable in the calculation function. So when you return back to main your variable is destructed and the sum in main is still 0.
Also if you are getting floating point values for dimensions then you must use double for sum too.
One possible solution could be like this:
#include<stdio.h>
#include<stdlib.h>
double calculation(int o, double *a, double *b) {
int i;
double sum =0.0;
for(i=0;i<o;++i) {
printf("Components of first vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &a[i]);
}
for(i=0;i<o;++i) {
printf("Components of second vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &b[i]);
}
for(i=0;i<o;++i) {
sum += a[i] * b[i];
}
return sum;
}
int main() {
int o;
double sum =0;
printf("How many dimensions should the vectors have?\n");
scanf("%d", &o);
double *a = malloc(o * sizeof(double));
double *b = malloc(o * sizeof(double));
if(a==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
if(b==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
sum = calculation(o,a,b);
printf("The dot product is: %lf\n", sum);
free(a);
free(b);
a=NULL;
b=NULL;
return(0);
}
Or you can pass the address of sum to calculation function as:
#include<stdio.h>
#include<stdlib.h>
void calculation(int o, double *a, double *b,double *sum) {
int i;
for(i=0;i<o;++i) {
printf("Components of first vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &a[i]);
}
for(i=0;i<o;++i) {
printf("Components of second vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &b[i]);
}
for(i=0;i<o;++i) {
*sum += a[i] * b[i];
}
}
int main() {
int o;
double sum=0;
printf("How many dimensions should the vectors have?\n");
scanf("%d", &o);
double *a = malloc(o * sizeof(double));
double *b = malloc(o * sizeof(double));
if(a==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
if(b==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
calculation(o,a,b,&sum);
printf("The dot product is: %lf\n", sum);
free(a);
free(b);
a=NULL;
b=NULL;
return(0);
}

calculate compound interest and display the interest for each year

void power(float P,float R,float n,float A);
void main()
{
float A,P,R,n;
clrscr();
printf("Enter principal amount:");
scanf("%f",&A);
printf("Enter rate of interest:");
scanf("%f",&R);
printf("Enter number of years:");
scanf("%f",&n);
power(A,R,P,n);
getch();
}
void power(float A,float R,float P,float n)
{
int i;
for(i=1;i<=n;i++)
{
A=1+(R*0.01);
A=A*i;
A=A*P;
printf("For year %d, C.I =%f\n",i,A);
}
}
I put
Principal = 2000
Rate of interest=3
Years=3
I am getting the value of compound interest in negative. The error is in A=A*P; The compound interest must be calculated for each year without using the power function
#include<stdio.h>
void power(float P,float R,float n,float A);
void main()
{
float A,P,R,n;
// clrscr();
printf("Enter principal amount:");
scanf("%f",&A);
printf("Enter rate of interest:");
scanf("%f",&R);
printf("Enter number of years:");
scanf("%f",&n);
power(A,R,P,n);
// getch();
}
void power(float A,float R,float P,float n)
{
int i;
float intr=0;
for(i=1;i<=n;i++)
{
intr=0;
intr=A*(R/100);
A=A+intr;
// A=A*P;
printf("For year %d, C.I =%f\n",i,intr);
}
}

C program to calculate average and min of test scores

I'm trying to write a program to find the average of students' test scores. I'd also like to find the lowest score and drop it out when I calculate the average. I then want to display all 4 quiz scores for each student as well as the lowest score and the average.
This what I have wrote:
int findMin(int student, int scores[3][4]){
int i;
int min=scores[student][0];
for(i=0 ;i<4;i++){
if(scores[student][i]<=min)
min= scores[student][i];
}
return min;
}
float getAverage(int student, int min, int scores[3][4])
{
float tot=0.0;
int i;
float average;
for(i=0 ;i<4;i++)
{
tot=tot+scores[student][i];
}
tot=tot-min;
average=tot/3.0;
return average;
}
void printTable(int scores[3][4], int min[3], float avg[3])
{
int i,j;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
}
}
}
int main(){
int scores[3][4];
printf("Enter score for first sdudent:\n");
int j=0;
for(j=0;j<4;j++){
scanf("%d",& scores[0][j]);
}
printf("Enter score for second sdudent:\n");
j=0;
for(j=0;j<4;j++){
scanf("%d",& scores[1][j]);
}
printf("Enter score for third sdudent:\n");
j=0;
for(j=0;j<4;j++){
scanf("%d",& scores[2][j]);
}
int min[3];
float avg[3];
int i=0;
for(i=0;i<3;i++) {
min[i]=findMin(i, scores);
avg[i]=getAverage(i, min[i],scores);
}
printTable(scores, min, avg);
return 0;
}
It does not output the average and the main. What am I doing wrong?
I thik you missed the printf in the printTable function

Confusion with Structures and how to store values with pointer in C

This question may be annoying, but I am trying to write code the way that I can most easily mentally process it and at this point it is without calling functions. I am rewriting my professors example code into my own, but am having a problem with what to store it into? He uses a pointer, but I just don't know how/where to declare it.
My apologies if this question is incorrectly worded. I am one of those people who just doesn't 'get it' when it comes to programming unfortunately.
My Professors:
#include <stdio.h>
#include <stdlib.h>
/* Program that computes the average salary of the employees with an age equal or greater
than x, x is passed as a parameter to the main function. Employee is a structure with two
fields: age and salary. */
struct employee {
int age;
float salary;
};
void readValues(struct employee *EMP, int n ) {
int i;
for(i=0; i<n; i++) {
printf("Employee %i\n", i+1);
printf("\tAge: ");
scanf("%i", &EMP[i].age);
printf("\tSalary: ");
scanf("%f", &EMP[i].salary);
}
}
float getAvg(struct employee *EMP, int minAge, int n ) {
int i, nE = 0;
float sum=0;
for(i=0; i<n; i++) {
if(EMP[i].age >= minAge) {
sum = sum + EMP[i].salary;
nE = nE + 1;
}
}
return sum/nE;
}
int main(int argc, char *argv[]) {
int x, n;
struct employee E[100];
if (argc<3) {
printf("Error: Some parameters missing.\n");
return -1;
}
x = atoi(argv[1]);
n = atoi(argv[2]);
readValues(E, n);
float avg = getAvg(E, x, n);
printf("Avg. Salary = %.2f\n", avg);
return 0;
}
My attempt:
#include <stdio.h>
#include <stdlib.h>
#define minage 20
struct employee{
int age;
float salary;
};
int main()
{
struct employee emp = {0};
int i, n, numb=0, sum=0, avg;
printf("How many employees do you have today?\n");
scanf("%i", n);
for(i=0; i<n; i++)
{
printf("Employee %i", i+1);
printf("Age:\n");
scanf("%i", &emp[i].age);
printf("Salary:\n");
scanf("%f", &emp[i].salary);
}
if (emp[i].age >= minage)
{
for(i=0, i<n; i++){
sum = sum + emp[i].salary
numb = numb + 1
}
}
avg = sum / numb;
printf("The average salary is %i\n", avg);
}
Refer the below Code: Comments Inline
#include <stdio.h>
#include <stdlib.h>
#define minage 20
struct employee{
int age;
float salary;
};
int main()
{
/* Use array of struct to store the employee record. */
struct employee emp[100];
int i, n, numb=0, sum=0;
float avg = 0; /* If avg is of type int then you will loose the precision when finding the average */
printf("How many employees do you have today?\n");
scanf("%i",&n); /* Use `&` when using scanf to read value into integer*/
for (i = 0; i < n; i++) {
printf("Employee %i", i+1);
printf("Age:\n");
scanf("%i", &emp[i].age);
printf("Salary:\n");
scanf("%f", &emp[i].salary);
}
/* Your professor is calculating avg salary only if age >= minage.
* But in your code your are trying to check if the last employee age is
* >= minage only after which calculating the avg salary of all employee's*/
for (i = 0; i < n; i++) {
if (emp[i].age >= minage) {
sum = sum + emp[i].salary;
numb = numb + 1;
}
}
/* Make sure to check whether numb != 0, else divide by zero exception
* when there are no employee's with age greater than 20 (minage) */
if (numb)
avg = sum / numb;
printf("The average salary is %.2f\n", avg);
/* return 0; when return type of main() is int.
* If not required then change to void main()*/
return 0;
}
Also as your professor is initializing minage from user input. In your code it is hard coded to a fixed number 20.
Try to read the minage from user as you did to get the number of employee's.

Resources