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.
Related
I have a problem with my code, it doesn't print the result I expect. This code allows the user to enter as many numbers as he wishes and then print the most repeated one
Here it is:
#include <stdio.h>
void reading_numbers(int array[]){
int i = 0;
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
}
void most_present_number(int array[], int Max){
int i = 0;
reading_numbers(array);
int current_number = array[i];
int current_number_count = 0;
int most_present_one = 0;
int most_present_one_counter = 0;
while (i < Max) {
if (array[i] == current_number) {
current_number_count++;
i++;
} else {
if (current_number_count > most_present_one_counter){
most_present_one = current_number;
most_present_one_counter = current_number_count;
}
current_number_count = 1;
}
}
printf("This is the most present number %d it is repeated %d times\n", most_present_one,
most_present_one_counter);
}
int main() {
int Max = 0;
int array[Max];
most_present_number(array, Max);
return 0;
}
The problem for me is when I call the function, but I don't know how to fix it
I should have written as a premise but I'm a bit new to C so probably there are some things in this code that don't make sense
I make a procedure to find the result ,int main() must have the size of array (mistake logic),because the procedure take the parameters of the main function (int main ())
Here is my code:
#include<stdio.h>
void most_present_number(int Max,int T[Max])
{
int i = 0;
while (i < Max)
{
printf("Insert the numbers :");
scanf("%d", &T[i]);
i++;
}
int k=0,cpt1=0,cpt=0;
for(int i=0;i<Max;i++)
{
cpt=0;
for(int j=i+1;j<Max;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>=cpt1)
{
cpt1=cpt;
k=T[i];
}
}
printf("This is the most present number %d it is repeated %d times\n",k,cpt1+1);
}
int main()
{
int Max = 0;
do
{
printf("How much long the array will be?\n");
scanf("%d", &Max);
}while(Max<1);
int T[Max];
most_present_number(Max,T);
}
the following proposed code:
cleanly compiles
performs the desired functionality
only includes header files those contents are actually used
and now the proposed code:
#include <stdio.h>
void reading_numbers( int Max, int array[ Max ][2])
{
for( int i = 0; i < Max; i++ )
{
printf("Insert the numbers\n");
scanf("%d", &array[i][0]);
array[i][1] = 0;
}
}
void most_present_number( int Max, int array[ Max ][2] )
{
for( int i=0; i < Max; i++ )
{
for( int j=i; j<Max; j++ )
{
if ( array[i][0] == array[j][0] )
{
array[i][1]++;
}
}
}
int most_present_one = array[0][0];
int most_present_one_counter = array[0][1];
for( int i=1; i<Max; i++ )
{
if( most_present_one_counter < array[i][1] )
{
most_present_one = array[i][0];
most_present_one_counter = array[i][1];
}
}
printf("This is the most present number %d it is repeated %d times\n",
most_present_one,
most_present_one_counter);
}
int main( void )
{
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
int array[Max][2]; // uses variable length array feature of C
reading_numbers( Max, array );
most_present_number( Max, array );
return 0;
}
a typical run of the code:
How much long the array will be?
4
Insert the numbers
1
Insert the numbers
2
Insert the numbers
3
Insert the numbers
2
This is the most present number 2 it is repeated 2 times
I have created a program that takes in input "n" numbers that the user chooses and then prints the most repeated one, but I have a problem with passing the values between the functions so it gives me 0 as a result. How can I solve it?
void most_present_number(int array[]);
int read_numbers(int array[]);
int main() {
int array[400];
most_present_number(array);
return 0;
}
void most_present_number(int array[]){
read_numbers(array);
int i = 0;
int Max = 0;
int Current_number = vettore[0];
int Current_number_counter = 0;
int most_present_number = 0;
int most_present_number_counter = 0;
while (i < Max) {
if (array[i] == Current_number) {
Current_number_counter++;
i++;
} else {
if (Current_number_counter > most_present_number_counter){
most_present_number = Current_number;
most_present_number_counter = Current_number_counter;
}
Current_number = array[i];
Current_number_counter = 1;
i++;
}
}
printf("The most present number is %d which is repeated %d times\n", most_present_number,
most_present_number_counter);
}
int read_numbers(int array[]){
int Max = 0;
int i = 0;
printf("Insert the array lenght\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
return Max;
}
You have Max = 0 in most_present_number(), so the while loop stops immediately.
read_numbers() returns Max, so you can use this to initialize Max in most_present_number().
void most_present_number(int array[], int Max);
int read_numbers(int array[]);
int main() {
int array[400];
int size;
most_present_number(array);
return 0;
}
void most_present_number(int array[]){
int Max = read_numbers(array);
int i;
int Current_number = array[0];
int Current_number_counter = 0;
int most_present_number = 0;
int most_present_number_counter = 0;
for (i = 0; i < Max; i++) {
if (array[i] == Current_number) {
Current_number_counter++;
} else {
if (Current_number_counter > most_present_number_counter){
most_present_number = Current_number;
most_present_number_counter = Current_number_counter;
}
Current_number = array[i];
Current_number_counter = 1;
}
}
printf("The most present number is %d which is repeated %d times\n", most_present_number,
most_present_number_counter);
}
int read_numbers(int array[]){
int Max = 0;
int i = 0;
printf("Insert the array lenght\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
return Max;
}
Note also that your algorithm assumes that all the equal numbers will be together in the array. If they can be mixed up, you need a very different design. You need another array where you keep the counts of each number. Then at the end you find the entry in this array with the highest count.
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;
}
Earlier I posted a question about the coin vending machine problem (the minimum number of coins required). Turns out the issue was a typo in a for loop, so now the program works. The original question was this:
As the programmer of a vending machine controller your are required to compute the minimum number of coins that make up the required change to give back to customers. An efficient solution to this problem takes a dynamic programming approach, starting off computing the number of coins required for a 1 cent change, then for 2 cents, then for 3 cents, until reaching the required change and each time making use of the prior computed number of coins. Write a program containing the function ComputeChange(), that takes a list of valid coins and the required change. This program should repeatedly ask for the required change from the console and call ComputeChange() accordingly. It should also make use of “caching”, where any previously computed intermediate values are retained for subsequent look-up.
The issue is that the code makes use of recursion, so it takes quite a long time to evaluate large values. Making use of caching should improve the issue, but I have no idea how to go about it. The code can be found below.
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
return 1+min(possible_mins, n);
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
With your existing code:
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
void initChange ();
int change [MAX]; //used for memoization
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
initChange ();
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
void initChange () {
int i =0;
for (i = 0; i < MAX; i++) {
change[i] = INT_MAX;
}
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
if (change[v] == INT_MAX) {
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
change[v] = 1 + min(possible_mins, n); // memoization
}
return change[v];//you return the memoized value
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
I already posted a solution using loops in your previous question. I will post it again here:
So the below is the code snippet for your problem using memoization and dynamic programming. The complexity is O(Val*numTypesofCoins).
In the end, change[val] will give you the min number of coins for val.
int main (void) {
int change [MAX];
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(a)/sizeof(int);
int val; //whatever user enters to get the num of coins required.
printf("Enter a value in euro cents: ");
scanf("%d", &val);
for (i=0; i <= val; i++) {
change[i] = INT_MAX;
}
for (i=0; i < n; i++) { // change for the currency coins should be 1.
change[cur[i]] = 1;
}
for (i=1; i <= val; i++) {
int min = INT_MAX;
int coins = 0;
if (change[i] != INT_MAX) { // Already got in 2nd loop
continue;
}
for (j=0; j < n; j++) {
if (cur[j] > i) { // coin value greater than i, so break.
break;
}
coins = 1 + change[i - cur[j]];
if (coins < min) {
min = coins;
}
}
change[i] = min;
}
}
I know this is a very novice question but I am having trouble with my if and for() loops in this program. I tried to designate where the issues are, but basically in main() it asks if the user wants to dismiss an employee and then that employee ID. Then in the dismissWorker function, it's supposed to scan the array of worker ID's, find the ID that matches the employee to be fired (badID), and then change that array. In my dismissWorker function I have it printing "HI" just to see if I called it correctly in main (and it does), but it doesn't run through the for() loop. I'm sure it's something simple that I'm doing wrong, but what is it exactly? Also, I don't know what I should have it return to at the end of dismissWorker, so some suggestions would be helpful.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_ROSTER 10 //roster of employees
typedef struct workerT_struct {
char name[81]; //employee name
char title[81]; //employee title
int empID; //unique ID for employee
int empStatus; //
int year100_salary; //before-tax salary, in cents
int year100_401k; //annual contribution to retirement, in cents
double taxRate; //fraction used to determine payroll taxes
int month100_paycheck; //monthly paycheck, in cents
} workerT;
typedef struct companyT_struct {
char dbaName[81]; //company name
int EmpActiveTot; //number of active employees
int EmpOnLeaveTot; //number of employees on unpaid leave
int year100_salaryTot; //total annual before-tax salaries, in cents
int year100_401kTot;
double year100_taxTot; //total annual payroll tax, in cents
int month100_paycheckTot; //total of all monthly paychecks for employees
} companyT;
void initWorkerArray(workerT list[], int siz);
void prntWorker(workerT list[], int siz, int indx);
void payWorker (workerT list[], int siz, int indx);
int dismissWorker (workerT list[], int siz, int badID);
void initCo(companyT hubCo[], workerT roll [], int sizRoll);
void doCoBooks(companyT hubCo[], workerT roll[], int sizRoll);
void printCoBooks(companyT hubCo[]);
int main()
{
workerT roster[MAX_ROSTER];
initWorkerArray(roster, MAX_ROSTER);
payWorker(roster, MAX_ROSTER, 0);
companyT myCo[1];
initCo(myCo, roster, 0);
doCoBooks(myCo, roster, MAX_ROSTER);
printCoBooks(myCo);
printf("Would you like to dismiss an existing employee? (yes/no)\n\n");
//FIXME FIXME FIXME
char defaultAnswer[4] = "yes";
char answer[4];
int badID = 0;
scanf(" %s", answer);
while (strcmp(answer,defaultAnswer) == 0) {
printf("Please give the employee ID:\n");
scanf(" %d", &badID);
printf("The employee ID you chose was %d.\n", badID);
dismissWorker(roster, MAX_ROSTER, 10); //FIXME
printf("Do you want to dismiss another employee?\n\n");
scanf(" %s", answer);
}
printf("Goodbye!");
return 0;
}
void initWorkerArray(workerT list[], int siz) {
int i = 0;
for (i = 0; i < 4; ++i) {
strcpy(list[0].name, "Buggy, Orson");
strcpy(list[0].title, "Director/President");
list[0].empID = 1;
list[0].empStatus = 1;
list[0].year100_salary = 12015000;
list[0].year100_401k = 950000;
list[0].month100_paycheck = 0;
list[0].taxRate = 0.45;
strcpy(list[1].name, "Czechs, Imelda");
strcpy(list[1].title, "Chief Financial Officer");
list[1].empID = 2;
list[1].empStatus = 1;
list[1].year100_salary = 8020000;
list[1].year100_401k = 960000;
list[1].month100_paycheck = 0;
list[1].taxRate = 0.39;
strcpy(list[2].name, "Hold, Levon");
strcpy(list[2].title, "Customer Service");
list[2].empID = 6;
list[2].empStatus = -1;
list[2].year100_salary = 8575000;
list[2].year100_401k = 1133000;
list[2].month100_paycheck = 0;
list[2].taxRate = 0.39;
strcpy(list[3].name, "Andropov, Picov");
strcpy(list[3].title, "Shipping Coordinator");
list[3].empID = 7;
list[3].empStatus = 1;
list[3].year100_salary = 4450000;
list[3].year100_401k = 375000;
list[3].month100_paycheck = 0;
list[3].taxRate = 0.31;
}
for (i = 4; i < siz; ++i) {
strcpy(list[i].name, "none");
strcpy(list[i].title, "none");
list[i].empID = -1;
list[i].empStatus = -1;
list[i].year100_salary = 0;
list[i].year100_401k = 0;
list[i].month100_paycheck = 0;
list[i].taxRate = 0.0;
}
return;
}
void prntWorker(workerT list[], int siz, int indx) {
int i = 0;
for (i = 0; i < siz; ++i) {
printf("%s, ", list[i].name);
printf("%s, ", list[i].title);
printf("%d, ", list[i].empID);
printf("%d, ", list[i].empStatus);
printf("%d, ", list[i].year100_salary);
printf("%d, ", list[i].year100_401k);
printf("%lf, ", list[i].taxRate);
printf("%d ", list[i].month100_paycheck);
printf("\n\n");
}
return;
}
void payWorker(workerT list[], int siz, int indx) {
int i;
for (i = 0; i < siz; ++i) {
list[i].month100_paycheck = (list[i].year100_salary / 12);
}
prntWorker(list, MAX_ROSTER,0);
return;
}
//FIXME FIXME FIXME
int dismissWorker (workerT list[], int siz, int badID) {
int i;
printf("HI");
for (i = 0; i < siz; ++i) { //FIXME
if (list[i].empID == badID) {
printf("HIHIHI");
list[i].empStatus = -1;
list[i].month100_paycheck = 0;
list[i].year100_salary = 0;
return 1;
}
else {
printf("\nWARNING! empID not found! Cannot dismiss "
"a non-employee!\n\n");
return 1;
}
}
return siz;
}
void initCo(companyT hubCo[], workerT roll [], int sizRoll) {
initWorkerArray(roll, sizRoll);
strcpy(hubCo[0].dbaName, "Dewey, Cheatham, and Howe, Consultants");
hubCo[0].EmpActiveTot = 3;
hubCo[0].EmpOnLeaveTot = 0;
hubCo[0].year100_salaryTot = 0;
hubCo[0].year100_401kTot = 0;
hubCo[0].year100_taxTot = 0.0;
hubCo[0].month100_paycheckTot = 0;
}
void doCoBooks(companyT hubCo[], workerT roll[], int sizRoll) {
int i = 0;
for (i = 0; i < sizRoll; ++i) {
if (roll[i].empStatus == 1) {
payWorker(roll, MAX_ROSTER, i);
hubCo[0].year100_salaryTot += roll[i].year100_salary;
hubCo[0].year100_401kTot += roll[i].year100_401k;
hubCo[0].year100_taxTot += roll[i].taxRate;
hubCo[0].month100_paycheckTot += roll[i].month100_paycheck;
}
}
}
void printCoBooks(companyT hubCo[]) {
printf("Name: %s\n", hubCo[0].dbaName);
printf("Active: %d\n", hubCo[0].EmpActiveTot);
printf("Leave: %d\n", hubCo[0].EmpOnLeaveTot);
printf("Salary: %d\n", hubCo[0].year100_salaryTot);
printf("401k: %d\n", hubCo[0].year100_401kTot);
printf("Monthly: %d\n", hubCo[0].month100_paycheckTot);
printf("Tax: %lf\n", hubCo[0].year100_taxTot);
printf("\n\n");
}
In your function initWorkerArray(workerT list[], int siz) you initiate four workerT objects with empID values 1, 2, 6, 7.
Now, in the main function, you call dismissWorker with dismissWorker(roster, MAX_ROSTER, 10)
In the for loop:
for (i = 0; i < siz; ++i) { //FIXME
if (list[i].empID == badID) {
printf("HIHIHI");
list[i].empStatus = -1;
list[i].month100_paycheck = 0;
list[i].year100_salary = 0;
return 1;
}
}
As far as I can see, the code does run through the for loop, but it can't find the badID and exits. You should print a warning or an error message to catch errors, such as these.
Try dismissWorker(roster, MAX_ROSTER, 7) to test it. It should work, and use error / warning messages to catch unforeseen circumstances in the code, such as empID's that don't exist in this case. Commonly known as Defensive Programming
You'll be able to see the error in your logic clearly if you use proper indentation in your code.
int dismissWorker (workerT list[], int siz, int badID) {
int i;
printf("HI");
for (i = 0; i < siz; ++i) {
if (list[i].empID == badID) {
printf("HIHIHI");
list[i].empStatus = -1;
list[i].month100_paycheck = 0;
list[i].year100_salary = 0;
return 1;
}
else {
printf("\nWARNING! empID not found! Cannot dismiss "
"a non-employee!\n\n");
return 1;
}
}
return siz;
}
As you can see, if the ID of the first employee doesn't match the given badID, the function will return with the warning. You need to use:
// Return 1 for success and 0 for failure, maybe.
int dismissWorker (workerT list[], int siz, int badID) {
int i;
printf("HI");
for (i = 0; i < siz; ++i) {
if (list[i].empID == badID) {
printf("HIHIHI");
list[i].empStatus = -1;
list[i].month100_paycheck = 0;
list[i].year100_salary = 0;
return 1;
}
}
printf("\nWARNING! empID not found! Cannot dismiss "
"a non-employee!\n\n");
return 0;
}