#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char model[50], mark[50], color[50];
int cylinderCap;
} car;
void read(car *cr, int *nr) {
printf("Insert mark: ");
(*nr)++;
fflush(stdin);
gets((cr + *nr)->mark);
printf("Insert model: ");
gets((cr + *nr)->model);
printf("Insert color: ");
gets((cr + *nr)->color);
printf("Insert the cylinder capacity: ");
scanf("%d", &((cr + *nr)->cylinderCap));
}
void display(car *cr, int nr) {
printf("\n%-10s \t%-10s \t%-10s %d", (cr + nr)->mark, (cr + nr)->model,
(cr + nr)->color, cr[nr].cylinderCap);
}
void search_model(car *cr, int *nr, char mod[50]) {
int i;
for(i = 0; i <= (*nr); i++)
if(strcmp((cr + i)->model, mod) == 0)
display(cr, i);
}
void search_cc(car *cr, int *nr, int cc) {
int i;
for(i = 0; i <= (*nr); i++)
if((cr + i)->cylinderCap >= cc)
display(cr, i);
}
void clear(car *cr, int *nr, char mod[50]) {
int k = 0,i,j;
for(i = 0; i <= (*nr); i++)
if(strcmp((cr + i)->model, mod) == 0)
{
k++;
for(j = i; j <= (*nr - k); j++)
*(cr + j) = cr[j + 1];
}
*nr = *nr - k;
}
void main() {
car cr[50];
int opt, n = -1, i, cc = 1900;
char mod[50];
do{
system("CLS");
printf("1.Add a car\n");
printf("2.Display cars\n");
printf("3.Search a car after its model\n");
printf("4.Display all the cars with cc > 1900\n");
printf("5.Remove a car after its model\n");
printf("6.Exit\n");
printf("7.Display the biggest cyclinder capacity of all the cars\n");
printf("Insert option: ");
scanf("%d", &opt);
switch(opt) {
case 1:
read(&cr[0], &n);
break;
case 2:
printf("\n%-10s \t%-10s \t%-10s %s", "mark", "Model", "color", "Capacity");
for(i = 0; i <= n; i++)
display(cr, i);
break;
case 3:
printf("Insert model: ");
scanf("%s", mod);
printf("\n%-10s \t%-10s \t%-10s %s", "mark", "Model", "color", "Capacity");
search_model(&cr[0], &n, mod);
break;
case 4:
printf("\n%-10s \t%-10s \t%-10s %s", "mark", "Model", "color", "Capacity");
search_cc(&cr[0], &n, cc);
break;
case 5:
printf("Insert the model you wish to delete: ");
scanf("%s", mod);
clear(&cr[0], &n, mod);
break;
case 6:
break;
case 7:
break;
default: printf("Error! Please try another option!\n");
break;
}
getch();
}while(opt != 6);
getch();
}
This will display:
1.Add a car
2.Display cars
3.Search a car after its model
4.Display all the cars with cc > 1900
5.Remove a car after its model
6.Exit
7.Display the biggest cylinder capacity of all the cars
Insert option:
I don't have any idea how to do the last one, I don't even know how to begin!
I tried something like this, but with no success:
void maximum(car *cr, int *nr, int max) {
int i;
for(i = 0; i <- (*nr); i++)
if(((cr + i)->car) >=max))
max = (cr + i)->car;
display(max);
}
But it doesn't really work, so any help would be appreciated!
Your maximum function doesn't make any sense. You're trying to use an object type as an item for a struct, using superfluous pointer arithmetic and other things that were already discussed in the comments in your post.
void maximum(car *cr, int nr)
{
int i, max = 0;
for(i = 1; i <= nr - 1; i++)
{
if(cr[i].cilinderCap >= cr[max].cilinderCap)
{
max = i;
}
}
display(cr, max);
}
Note: try to understand my code before copying it to your file.
This is the most intuitive approach one can get. Note I'm using the "cylinder capacity" variable to actually check, uhm, the maximum cylinder capacity.
Also note that if you start your cars at index 0, you should search up to n - 1, and not n. The referenced parameter for nr is also redundant, as you don't even try to modify it.
So, you just call:
maximum(cr, n);
Another thing is that you should check for errors in the function, as in its current state, it might crash if there are no elements in the list.
There are some other "ethically incorrect stuff" in your code that are irrelevant to the question, but I recommend reading some articles on Google about struct lists.
Related
I have received a code from a friend of mine which was giving garbage outputs and hence I tried to run it on my PC too. The same problem is happening with me and I don't know how to fix it.
Here is the code to accept and display a few information of bank customers from the user and display it.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef struct Customer {
char name[20];
int date;
int month;
int year;
int amount;
int type_of_account;
} cus;
void display(int n);
void data_entry_of_customers(int n);
int main() {
int i, n, choices;
printf("\n Enter the number of customer you want to enter their data : ");
scanf("%d", &n);
do {
printf("\n Enter your choice :");
scanf("%d", &choices);
switch (choices) {
case 1:
data_entry_of_customers(n);
break;
case 2:
display(n);
break;
case 3:
exit(0);
break;
default:
{
printf("\n Invalid Choice");
}
}
i++;
} while (choices != 3);
getch();
return 0;
}
void data_entry_of_customers(int n) {
cus c[n];
int i;
for (i = 0; i < n; i++) {
printf("\n Enter the name of the customer%d : ", i + 1);
scanf("%s", c[i].name);
printf("\n Enter the date when the account was opened by customer : ");
scanf("%d", &c[i].date);
printf("\n Enter the month when the account was opened by customer : ");
scanf("%d", &c[i].month);
printf("\n Enter the year when the account was opened by customer : ");
scanf("%d", &c[i].year);
printf("\n Enter the amount disposited by the customer : ");
scanf("%d", &c[i].amount);
}
}
void display(int n) {
cus c[n];
int i;
for (i = 0; i < n; i++) {
printf("\n The name of the customer%d is %s", i + 1, c[i].name);
printf("\n The date-month-year when the account was opened by customer%d is %d-%d-%d", i + 1, c[i].date, c[i].month, c[i].year);
printf("\n The amount when the account was opened by customer%d is %d", i + 1, c[i].amount);
printf("\n");
}
}
I tried to look for errors in my code initially but it looked good to me hence I proceeded with an online compiler and now I am clueless on how should I fix the IDE's problem
The c array is defined as a local variable in both the display and the data_entry_of_customers functions. The values entered are lost when the function returns and the contents of c in the display function are indeterminate producing undefined behavior (garbage output).
The program may seem to behave as expected if, by chance, the position and contents of the c array in both functions happens to be the same.
You should more the definition of the array to the main function and pass it to data_entry_of_customers() and display().
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Customer {
char name[20];
int date;
int month;
int year;
int amount;
int type_of_account;
} cus;
void display(int n, cus c[n]);
void data_entry_of_customers(int n, cus c[n]);
int main() {
int n, choices;
printf("\n Enter the number of customers : ");
if (scanf("%d", &n) != 1)
return 1;
cus cus_array[n];
for (;;) {
printf("\n Enter your choice :");
if (scanf("%d", &choices) != 1)
break;
switch (choices) {
case 1:
data_entry_of_customers(n, cus_array);
break;
case 2:
display(n, cus_array);
break;
case 3:
return 0;
default:
printf("\n Invalid Choice\n");
break;
}
}
return 0;
}
void data_entry_of_customers(int n, cus c[n]) {
for (int i = 0; i < n; i++) {
printf("\n Enter the name of the customer%d : ", i + 1);
scanf("%19s", c[i].name);
printf("\n Enter the date when the account was opened by customer : ");
scanf("%d", &c[i].date);
printf("\n Enter the month when the account was opened by customer : ");
scanf("%d", &c[i].month);
printf("\n Enter the year when the account was opened by customer : ");
scanf("%d", &c[i].year);
printf("\n Enter the amount deposited by the customer : ");
scanf("%d", &c[i].amount);
}
}
void display(int n, cus c[n]) {
for (int i = 0; i < n; i++) {
printf("\n The name of the customer%d is %s", i + 1, c[i].name);
printf("\n The date-month-year when the account was opened by customer%d is %d-%d-%d", i + 1, c[i].date, c[i].month, c[i].year);
printf("\n The amount when the account was opened by customer%d is %d", i + 1, c[i].amount);
printf("\n");
}
}
Note these remarks:
void display(int n, cus c[n]); defines a function that receives an int and a pointer to an array of cus structures. The prototype is equivalent to: void display(int n, cus c[]); and void display(int n, cus *c);... A possible improvement is to specify that the cus structures are not modified by the display function, thus change the prototype to void display(int n, const cus *c);
the return value of scanf should be tested to detect and handle invalid input. Writing separate functions to read a string and an integer would help make the code more reliable and readable.
Here is an alternate approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Customer {
char name[20];
int date;
int month;
int year;
int amount;
int type_of_account;
} cus;
char *enter_string(const char *prompt, char *dest, size_t size);
int enter_int(const char *prompt, int min, int max);
void display(int n, const cus *c);
void data_entry_of_customers(int n, cus *c);
int main() {
int n = enter_int("Enter the number of customers", 1, 1000);
cus cus_array[n];
for (;;) {
switch (enter_int("Enter your choice", 1, 3)) {
case 1:
data_entry_of_customers(n, cus_array);
break;
case 2:
display(n, cus_array);
break;
case 3:
return 0;
}
}
}
char *enter_string(const char *prompt, char *dest, size_t size) {
int c;
size_t i = 0;
printf("%s: ", prompt);
fflush(stdout);
while ((c = getchar()) != EOF && c != '\n') {
if (i + 1 < size) {
dest[i++] = (char)c;
}
}
printf("\n");
if (i == 0 && c == EOF) {
printf("unexpected end of file\n");
exit(1);
}
if (i < size)
dest[i] = '\0';
return dest;
}
int enter_int(const char *prompt, int min, int max) {
int c, res, value;
for (;;) {
printf("%s: ", prompt);
fflush(stdout);
res = scanf("%d", &value);
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("\n");
if (res == 1) {
if (value >= min && value <= max)
return value;
printf("invalid value, must be between %d and %d\n", min, max);
} else {
if (c == EOF) {
printf("unexpected end of file\n");
exit(1);
}
printf("invalid input, enter a number between %d and %d\n", min, max);
}
}
}
void data_entry_of_customers(int n, cus *c) {
char prompt[80];
for (int i = 0; i < n; i++) {
snprintf(prompt, sizeof prompt, "Enter the name of the customer%d", i + 1);
enter_string(prompt, c[i].name, sizeof(c[i].name));
c[i].date = enter_int("Enter the date when the account was opened by customer",
1, 31);
c[i].month = enter_int("Enter the month when the account was opened by customer",
1, 12);
c[i].year = enter_int("Enter the year when the account was opened by customer",
1900, 2100);
c[i].amount = enter_int("Enter the amount disposited by the customer",
0, 1000000000);
}
}
void display(int n, const cus *c) {
for (int i = 0; i < n; i++) {
printf("The name of the customer%d is %s\n", i + 1, c[i].name);
printf("The date-month-year when the account was opened by customer%d is %d-%d-%d\n",
i + 1, c[i].date, c[i].month, c[i].year);
printf("The amount when the account was opened by customer%d is %d\n",
i + 1, c[i].amount);
printf("\n");
}
}
I have this C code and I struggle with the functions printCol(); and printRow.
When I run the code and call for these functions to print a specific column or a row, they always return the second row or column.
EDITED: I know that many functions are nonsense, but i just started to learn C, please don't be rude...
#include <stdio.h>
#include <stdlib.h>
void printRow1(int *p1, int rowSize) {
for (int i = 0; i < rowSize; i++) {
printf("%d\t", *p1);
p1 += 1;
}
}
void printCol1(int *p, int colSize) {
for (int i = 0; i < colSize; i++) {
printf("%d\n", *p);
p += 4;
}
}
void reverseRow1(int *p2) {
for (int i = 4; i > 0; i--) {
printf("%d\t", *p2);
p2-=1;
}
}
int arr[3][4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
void printMat() {
int col = 3;
int row = 4;
for (int i = 0; i < col; i ++) {
printf("\n");
for (int j = 0; j < row; j++) {
printf("%d\t", arr[i][j]);
}
}
}
void printCol() {
printf("Which column would you like to print? \t");
int choiceCol;
scanf("%d\n", &choiceCol);
char buf = fgetc(stdin);
if (choiceCol >= 1 && choiceCol <= 4) {
printCol1(&arr[0][choiceCol-1], 3);
} else {
printf("An Error occured\n");
}
}
void printRow() {
printf("Which row would you like to print? \t");
int choiceRow;
scanf("%d\n", &choiceRow);
char buf = fgetc(stdin);
if (choiceRow >= 1 && choiceRow <= 3){
printRow1(&arr[choiceRow-1][0], 4);
} else {
printf("An Error occured\n");
}
}
void reverseRow() {
printf("which row to reverse?: \t");
int reversedR = scanf("%d\n", &reversedR);
printf("%d\n", reversedR);
reverseRow1(&arr[0][reversedR]);
}
void printMenu() {
printf("\n");
printf("You can choose one of these services: \n");
printf("1. Print matrix tabular form. \n");
printf("2. Print a specific row or a number of rows in sequence \n");
printf("3. Print a specific column or a number of columns in sequence \n");
printf("4. Get the elements of a specific row reversed \n");
printf("5. find the number of prime numbers in a specific row \n");
printf("6. Quit \n");
printf("Please select one to try ");
int answer;
scanf("%d\n", &answer);
int *an = &answer;
switch (*an) {
case 1:
printMat();
printMenu();
break;
case 2:
printCol();
printMenu();
break;
case 3:
printRow();
printMenu();
break;
case 4:
reverseRow();
break;
case 5:
/* code */
break;
case 6:
printf("Bye!\n");
break;
default:
printf("please select carefully! \n");
break;
}
}
int main() {
char buf;
printMat();
printMenu();
return 0;
}
Can anyone please help me understand why this is happening? They are always printing wrong column or row.
Tricky little bug, the problem wasn't with your print functions, but with the way you are reading input. You use things like scanf("%d\n", &answer); which wants to read a %d and a \n. When you enter a number you have to follow it by an enter, which might lead you to believe you need to read the \n, but it doesn't go into the input stream. This is also why in your program you would need to enter the selection twice. The second time it leaves a number in the input stream which is wrongly read to choose the row/column. I have corrected these mistakes in the below code.
#include <stdio.h>
#include <stdlib.h>
void printRow1(int *p1, int rowSize) {
for (int i = 0; i < rowSize; i++) {
printf("%d\t", *p1);
p1 += 1;
}
}
void printCol1(int *p, int colSize) {
for (int i = 0; i < colSize; i++) {
printf("%d\n", *p);
p += 4;
}
}
void reverseRow1(int *p2) {
for (int i = 4; i > 0; i--) {
printf("%d\t", *p2);
p2-=1;
}
}
int arr[3][4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
void printMat() {
int col = 3;
int row = 4;
for (int i = 0; i < col; i ++) {
printf("\n");
for (int j = 0; j < row; j++) {
printf("%d\t", arr[i][j]);
}
}
}
void printCol() {
printf("Which column would you like to print? \t");
int choiceCol;
scanf("%d", &choiceCol);
if (choiceCol >= 1 && choiceCol <= 4) {
printCol1(&arr[0][choiceCol-1], 3);
} else {
printf("An Error occured\n");
}
}
void printRow() {
printf("Which row would you like to print? \t");
int choiceRow;
scanf("%d", &choiceRow);
if (choiceRow >= 1 && choiceRow <= 3){
printRow1(&arr[choiceRow-1][0], 4);
} else {
printf("An Error occured\n");
}
}
void reverseRow() {
printf("which row to reverse?: \t");
int reversedR = scanf("%d", &reversedR);
printf("%d\n", reversedR);
reverseRow1(&arr[0][reversedR]);
}
void printMenu() {
printf("\n");
printf("You can choose one of these services: \n");
printf("1. Print matrix tabular form. \n");
printf("2. Print a specific row or a number of rows in sequence \n");
printf("3. Print a specific column or a number of columns in sequence \n");
printf("4. Get the elements of a specific row reversed \n");
printf("5. find the number of prime numbers in a specific row \n");
printf("6. Quit \n");
printf("Please select one to try ");
int answer;
scanf("%d", &answer);
switch (answer) {
case 1:
printMat();
printMenu();
break;
case 2:
printCol();
printMenu();
break;
case 3:
printRow();
printMenu();
break;
case 4:
reverseRow();
break;
case 5:
/* code */
break;
case 6:
printf("Bye!\n");
break;
default:
printf("please select carefully! \n");
break;
}
}
int main() {
printMat();
printMenu();
return 0;
}
A few other things I noticed, your menu options for row and column are flipped, and your code assumes the size of the array in several spots (this is very bad practice). If the code should work with different sized arrays then you should be passing the size around, if not then you should use macros to define the size. There may be other issues I didn't notice, but the issue mentioned in the question is now fixed.
#include <stdio.h>
int main(void) {
int choice;
do {
choice = getUserChoice();
switch (choice) {
case 1:
gameResults();
break;
case 2:
printf("game results:\n ");
break;
case 3:
printf("selected choice is 3\n");
break;
case 4:
printf("selected choice is 4\n");
break;
case 5:
//this case is to keep the default from triggering when selecting 5.
break;
default:
printf("please select a valid number 1-5.\n");
system("pause");
}
} while (choice != 5);
}
int getUserChoice() {
int x = 0;
printf("[1]Enter game results.\n");
printf("[2]Current record (number of wins, losse, and ties)\n");
printf("[3]Display ALL results from all games won.\n");
printf("[4]Display ALL results ordered from low to high.\n");
printf("[5]Quit.\n");
scanf_s("%d", &x);
return x;
}//end getUserChoice
int gameResults() {
int gameInput[1][2];
//counter variables for loop.
int i, j;
for (i = 0; i < 1; i++) {
for (j = 0; j < 2; j++) {
printf("please enter a value for gameInput[%d][%d]: ", i, j);
scanf_s("%d", &gameInput[i][j]);
return gameInput[i][j];
}
}
}
void prinGameResults() {
gameResults();
int wins, ties, losses = 0;
if()
}
So essentially I'm working on this assignment that is asking me to create a 2D array, have the user select stuff from a menu, put in 2 values for 2 team scores (one being "your" team and the other one being the opponents) I've created the array and now I'm looking to display this array when the user calls the 2nd switch case, and display numbers of wins, ties, etc etc.. the only problem is I have no idea how to call this array into one function from another, perhaps I'm doing this the in a wrong way, is there some easier way of going about this array?
You'll want to define your array inside main so that it can be passed as an argument (alongside its dimensions) to each function.
#include <stdio.h>
#include <stdlib.h>
int getUserChoice(void);
void getGameResults(size_t n, size_t m, int res[n][m]);
void printGameResults(size_t n, size_t m, int res[n][m]);
#define ROWS 1
#define COLS 2
int main(void) {
int results[ROWS][COLS] = { 0 };
int choice;
while ((choice = getUserChoice()) != 5)
switch (choice) {
case 1:
getGameResults(ROWS, COLS, results);
break;
case 2:
printGameResults(ROWS, COLS, results);
break;
case 3:
puts("Selected (3)");
break;
case 4:
puts("Selected (4)");
break;
default:
puts("Select a valid option (1-5)");
break;
}
}
int getUserChoice(void) {
int x = 0;
puts("[1]Input results.");
puts("[2]Display results.");
puts("[3]--");
puts("[4]--");
puts("[5]Quit.");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Failed to read choice.\n");
exit(EXIT_FAILURE);
}
return x;
}
void getGameResults(size_t n, size_t m, int res[n][m]) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
printf("Enter a value for [%zu][%zu]: ", i, j);
if (scanf("%d", &res[i][j]) != 1) {
fprintf(stderr, "Failed to read result.\n");
exit(EXIT_FAILURE);
}
}
}
}
void printGameResults(size_t n, size_t m, int res[n][m]) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
printf("Value for [%zu][%zu]: %d\n", i, j, res[i][j]);
}
}
}
And for compilers that don't support variable-length arrays, you must be more rigid in your approach. There are a few ways to do this, here is one example:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 1
#define COLS 2
int getUserChoice(void);
void getGameResults(int res[ROWS][COLS]);
void printGameResults(int res[ROWS][COLS]);
int main(void) {
int results[ROWS][COLS] = { 0 };
int choice;
while ((choice = getUserChoice()) != 5)
switch (choice) {
case 1:
getGameResults(results);
break;
case 2:
printGameResults(results);
break;
case 3:
puts("Selected (3)");
break;
case 4:
puts("Selected (4)");
break;
default:
puts("Select a valid option (1-5)");
break;
}
}
int getUserChoice(void) {
int x = 0;
puts("[1]Input results.");
puts("[2]Display results.");
puts("[3]--");
puts("[4]--");
puts("[5]Quit.");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Failed to read choice.\n");
exit(EXIT_FAILURE);
}
return x;
}
void getGameResults(int res[ROWS][COLS]) {
for (size_t i = 0; i < ROWS; i++) {
for (size_t j = 0; j < COLS; j++) {
printf("Enter a value for [%zu][%zu]: ", i, j);
if (scanf("%d", &res[i][j]) != 1) {
fprintf(stderr, "Failed to read result.\n");
exit(EXIT_FAILURE);
}
}
}
}
void printGameResults(int res[ROWS][COLS]) {
for (size_t i = 0; i < ROWS; i++) {
for (size_t j = 0; j < COLS; j++) {
printf("Value for [%zu][%zu]: %d\n", i, j, res[i][j]);
}
}
}
I am suppoused not to use globals just functions. I don't know where to have int measurements[LENGTH], x, i; to work as it does. I also need a function to calculate de number of measurements(nrOfMeasurements) that user typed in in getMeasurements. for example if they typed in 4 instead f 10. This is needed for ex. to calculate the average.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <limits.h>
#define LENGTH 10
const char *IntroMsg = "\n\t Hello To TEST THE PRGRAM!\n",
*MenuMsg = "\n\t Menu \n\t v (View) \n\t e (Enter) \n\t c (Compute) \n\t r (Reset) \n\t q (Quit) \n\n";
int measurements[LENGTH],//not here
x, i;//not here
void getMeasurements(){
for(x=0; x<LENGTH; x++){
printf("Enter number #%d: ", x+1);
scanf("%d", &measurements[x]);
if(measurements[x]==0){
break;
}
}
return;
}
void getView(){
printf("\t\n");
printf("Your measurements:\n");
if(x>0){
for (i = 0; i < x; i++){
printf("\b %d ", measurements[i]);
}
}
else if(x==0){
printf(" [NO MEASUREMENTS]");
}
printf("\n");
}
void getCompute(){
int min = INT_MAX;
int max = INT_MIN;
int calculus;
float sum;
for(x=0; x<LENGTH; x++){
if (measurements[x]<min) min=measurements[x];
if (measurements[x]>max) max=measurements[x];
sum=sum+measurements[x];
calculus= measurements[x] - (sum/LENGTH);
printf("[%d]", calculus);
}
printf("\nMax number: %d", max);
printf("\nMin number: %d", min);
printf("\nAverage: %.2f", sum/LENGTH);
printf("\n\n");
}
int main(){
while(1){
char choice;
puts (MenuMsg);
scanf(" %c", &choice);
if(choice=='e')
getMeasurements();
else if(choice=='v'){
getView();
}
else if(choice=='c'){
getCompute();
}
else if(choice=='q'){
break;
}
}
return 0;
}
You can do something like this:
#include <stdio.h>
#define MAX_LENGTH 10
const char *IntroMsg = "\n\t Hello To TEST THE PROGRAM!\n";
const char *MenuMsg = "\n\t Menu \n"
"\t v (View)\n"
"\t e (Enter)\n"
"\t c (Compute)\n"
"\t r (Reset)\n"
"\t q (Quit)\n\n";
int getMeasurements(int *measurements, int length) {
int i;
for (i = 0; i < length; i++) {
printf("Enter number #%d: ", i+1);
scanf("%d", &measurements[i]);
if(measurements[i] == 0) {
break;
}
}
return i;
}
void getView(const int *measurements, int length){
int i;
printf("\t\nYour measurements:\n");
if (length == 0) {
printf(" [NO MEASUREMENTS]\n");
return;
}
for (i = 0; i < length; i++) {
printf("\b %d ", measurements[i]);
}
printf("\n");
}
void getCompute(const int *measurements, int length) {
int min, max, calculus, i;
float sum = 0;
if (length == 0) {
printf(" [NO MEASUREMENTS]\n");
return;
}
min = max = measurements[0];
for (i = 0; i < length; i++){
if (measurements[i] < min) min = measurements[i];
if (measurements[i] > max) max = measurements[i];
sum += measurements[i];
calculus = measurements[i] - (sum / length);
printf("[%d]", calculus);
}
printf("\nMax number: %d", max);
printf("\nMin number: %d", min);
printf("\nAverage: %.2f", sum / length);
printf("\n\n");
}
int main() {
int measurements[MAX_LENGTH];
int measurements_count = 0;
int run = 1;
while (run) {
char choice;
puts(MenuMsg);
scanf(" %c", &choice);
switch (choice) {
case 'e':
measurements_count = getMeasurements(measurements, MAX_LENGTH);
break;
case 'v':
getView(measurements, measurements_count);
break;
case 'c':
getCompute(measurements, measurements_count);
break;
case 'q':
run = 0;
break;
default:
printf("Wrong input\n");
break;
}
}
return 0;
}
I'm currently doing a school assignment and now I'm really stuck. The problem I have is that When I'm trying to copy the elements of the array dice to the array diceCheck the program goes in to some kind of infinite loop and I don't understand why. Help would be greatly appreciated!
Edit: It's in the bottom in the function printScores.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printMenu(void);
void throwDice(int dice[], int nrOfDice, int nrOfDieValues);
void readDieValues (int dice[], int nrOfDice);
void printDice(const int dice[], int nrOfDice);
void printScores(const int dice[], int nrOfdice, int nrOfDieValues);
int isThreeOfAKind(const int dieValues[], int nrOfDieValues);
int isSmallStraight(const int dieValues[], int nrOfDieValues);
int main(void)
{
const int nrOfDice = 5;
const int nrOfDieValues = 6;
int dice[4], menuChoice = 0;
printMenu();
printf("\nMake your choice: ");
while(scanf("%d", &menuChoice) != -1)
{
switch (menuChoice)
{
case 0:
printMenu();
break;
case 1:
throwDice(dice, nrOfDice, nrOfDieValues);
printf("Make your choice: ");
break;
case 2:
readDieValues(dice, nrOfDice);
printf("Make your choice: ");
break;
case 3:
printDice(dice, nrOfDice);
printf("Make your choice: ");
break;
case 4:
printScores(dice, nrOfDice, nrOfDieValues);
break;
case -1:
return 0;
break;
default:
printf("Invalid choice!\n");
break;
}
}
return 0;
}
void printMenu()
{
printf("MENU:\n");
printf("0. Display the menu\n");
printf("1. Make a random throw\n");
printf("2. Enter die values for a throw\n");
printf("3. Display the die values for the throw\n");
printf("4. Display the score for the throw\n");
printf("-1. End program\n");
}
void throwDice(int dice[], int nrOfDice, int nrOfDieValues)
{
int choice, i;
printf("Enter seed (1 gives a random seed): ");
scanf("%d", &choice);
if(choice == 1)
{
srand(time(NULL));
for (i = 0; i < nrOfDice; i++)
{
dice[i] = ( rand() % nrOfDieValues) + 1;
}
printf("\n");
}
else
{
srand(choice);
for(i = 0; i < nrOfDice; i++)
{
dice[i] = ( rand() % nrOfDieValues) + 1;
}
printf("\n");
}
}
void readDieValues(int dice[], int nrOfDice)
{
int i;
for(i = 0; i < nrOfDice; i++)
{
printf("Die %d: ", (i+1));
scanf("%d", &dice[i]);
}
}
void printDice(const int dice[], int nrOfDice)
{
int i;
printf("Your dice: ");
for(i = 0; i < nrOfDice; i++)
{
printf("%d ", dice[i]);
}
printf("\n\n");
}
int isThreeOfAKind(const int dieValues[], int nrOfDieValues)
{
}
int isSmallStraight(const int dieValues[], int nrOfDieValues)
{
}
void printScores(const int dice[], int nrOfdice, int nrOfDieValues)
{
int diceCheck[4], i;
for(i = 0; i < nrOfdice; i++)
{
diceCheck[i] = dice[i];
printf("%d ", dice[i]); //these are just for myself to check if it worked
printf("%d ", diceCheck[i]); //these are just for myself to check if it worked
}
}
You have:
const int nrOfDice = 5;
but
int dice[4];
int diceCheck[4];
Your copying idea is correct but you are going one past the end of the array.
To avoid this sort of error, initialize both from the same expression, e.g.:
int dice[4];
const int nrOfDice = sizeof dice / sizeof dice[0];
or
const int nrOfDice = 4;
int dice[nrOfDice];
and inside the PrintScores function, instead of int diceCheck[4];, do:
int diceCheck[nrOfDice];