Copying elements of array to a new one - C - c

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];

Related

How can I call my array in one function to another function and display specific data from that array?

#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]);
}
}
}

How can I delete a user inputed element/data from an Array in Structure? [duplicate]

How to delete an element from the array of type structure? Let's say if I register an item and then want to delete it how can I do that? The delete function is at the end of the code. I want to delete the item by giving the varunummer (id number). Any one know how to do it?
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define WORDLENGTH 30
#define MAX 5
struct varor {
int varunummer;
char namn[WORDLENGTH];
int lagersaldo;
};
int readLine(char s[], int length);
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods);
void registerVaror(struct varor reg[], int *nrOfGoods);
void getPrint(const struct varor reg[], int nrOfGoods);
void avregristreraVaror(struct varor reg[], int nrOfGoods);
int main(void) {
struct varor vRegister[WORDLENGTH];
int nrOfGoods = 0;
int run = 1;
while (run) {
char choice;
printf("\n\t\tMeny - Lager Program\n\n\
(1) Register\n\b\b\b\b\
(2) Print\n\
(3) Delete\n\
(4) Quit\n");
scanf(" %c%*c", &choice);
if (choice=='1')
registerVaror(vRegister, &nrOfGoods);
if (choice=='2')
getPrint(vRegister, nrOfGoods);
if (choice=='3')
avregristreraVaror(vRegister, nrOfGoods);
else if (choice=='4')
run = 0;
}
return 0;
}
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods) {
int i;
for (i = 0; i < nrOfGoods; i++)
if(reg[i].varunummer == varunummer)
return i;
return -1;
}
int readLine(char s[], int length) {
int ch, i=0;
while (isspace(ch=getchar()));
while (ch != '\n' && ch != EOF) {
if (i < length)
s[i++] = ch;
ch = getchar();
}
s[i] = '\0';
return i;
}
void registerVaror(struct varor reg[], int *nrOfGoods) {
char namn[WORDLENGTH], tmp[WORDLENGTH];
int varunummer, lagersaldo;
if (*nrOfGoods == MAX) {
printf("\nError! Finns inte plats kvar!\n");
return;
}
printf("Ange varunummer: ");
scanf("%d", &varunummer);
if (ifVarunummerExist(varunummer, reg, *nrOfGoods) >= 0) {
printf("\nVarunummer finns redan!\n");
return;
}
reg[*nrOfGoods].varunummer = varunummer;
printf("Ange namn: ");
readLine(reg[*nrOfGoods].namn, WORDLENGTH);
printf("Ange lagersaldo :");
scanf("%d", &reg[*nrOfGoods].lagersaldo);
//reg[*nrOfGoods]=createVara(varunummer,namn,lagersaldo);
(*nrOfGoods)++;
}
void getPrint(const struct varor reg[], int nrOfGoods) {
int i;
printf("\nVarunummer \t Namn \t\t\t Lagersaldo\n");
for (i = 0; i < nrOfGoods; i++) {
printf(" %d \t\t %s \t\t\t %d\n",reg[i].varunummer,reg[i].namn,reg[i].lagersaldo);
}
}
void avregristreraVaror(struct varor reg[], int nrOfGoods) {
int run = 1;
while (run) {
char choice;
printf("\n (1) Delete \n (2) Exit");
scanf(" %c", &choice);
//DELETE IF CHOICE 1---------
if (choice == '1') {
int i, varunummer;
printf("Ange varunummer: ");
scanf("%d", &varunummer);
for (i = varunummer + 1; i < MAX; i++) {
reg[i - 1] = reg[i];
}
reg[i] = 0;
}
}
//QUIT TO MY MENU CHOICE 2--------
if (choice == '2')
run = 0;
}
You can try iterating through the array in a for loop UNTIL your varunummer is matched with the struct's property. Something along these lines (let's say you are searching for the member with varunummer = varunummerToLookFor), this shift all the elements in the array from the point onwards of your deletion by 1, hence, producing an array with the same sequence as before but with your wanted element removed. Hope that helps!
for(int i = 0, i < varorArraySize, i++){
if(varunummerToLookFor == varorArray[i].varunummer){
for (i = pos; i < varorArraySize - 1; i++)
{
varorArray[i] = varorArray[i + 1];
}
}
}

Unable to read structures properly from binary

So my program creates an 2d-dynamic array of structures, reads these structures from a binary file, changes the information in the structures and writes them in the same file. The problem is, that it does not read the information from the file properly. For example, I expect the info from ptr[0][0].Flat_IDto be 101. But on the console it prints a random number, say10948144, and this jeopardizes my entire program. I tried to change the way it reads, but to no effect.
Here is my main():
#include "Header.h"
int main()
{
while(1)
{
printf("Hello world!\n");
unsigned int floors=0, flats_per_floor=0;
S_Apartament Flats;
char FileName[50];
printf("0. Exit program.\n");
printf("1. Enter a file name.\n");
printf("Please, choose a command.\n");
unsigned short choice;
scanf("%hu", &choice);
if(choice == 0)
{
break;
}
else
{
printf("Enter file name in the following format 'Name.bin' :");
scanf("%s", FileName);
}
S_Apartament **ptr = memalloc(floors, flats_per_floor, Flats, FileName);
printf("%u",ptr[0][0].Flat_ID);
while(1)
{
choice = menu();
if(choice==0)
{
break;
}
switch(choice)
{
case 1:
enterNewResidents(ptr, floors, flats_per_floor);
break;
case 2:
calculateTax(ptr, floors, flats_per_floor);
break;
case 3:
Elevator(ptr, floors, flats_per_floor);
break;
case 4:
emptyApartment(ptr, floors, flats_per_floor);
break;
default:
printf("Invalid command\n");
break;
}
writeInfo(ptr,floors,flats_per_floor, FileName);
free(ptr);
}
}
printf("Program exited successfully. Have a nice day");
return 0;
}
My header file:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
unsigned int Flat_ID;
unsigned short count_Rooms;
unsigned short count_Adults;
unsigned short count_Children;
char Family_Surname[20];
char Date[10];
float rent;
}S_Apartament;
unsigned short menu();
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50]);
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50]);
#endif // HEADER_H_INCLUDED
And my source file:
#include "Header.h"
unsigned short menu()
{
unsigned short choice=0;
printf("Welcome, to the smart House manager program! Here is a list of the available commands.\n");
printf("1. Enter new residents.\n");
printf("2. Calculate month tax.\n");
printf("3. Set elevator\n");
printf("4. Empty an apartment\n");
printf("0. Exit the program\n");
printf("Please choose a command:\n");
scanf("%hu",&choice);
return choice;
}
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50])
{
FILE *f;
f = fopen(FileName,"rb");
if(f==NULL)
{
printf("Error opening file, or no such file.");
fclose(f);
exit(1);
}
fread(&floors,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
fclose(f);
S_Apartament **arr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);
for (int i = 0; i < floors; i++)
{
arr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);
printf("Here");
}
for(int i = 0; i < floors; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
fread(&Apartment,sizeof(S_Apartament),1,f);
arr[i][j]=Apartment;
}
}
fclose(f);
return arr;
}
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short a = 0, b = 0;
printf("Enter the floor, where you wish to accommodate the new residents.\n");
scanf("%hu", &a);
printf("Good, now the flat.\n");
scanf("%hu", &b);
if((a > floors) || (b > flats_per_floor))
{
printf("Invalid coordinates.");
}
if(ptr[a-1][b-1].count_Adults==0)
{
printf("The apartment is free to use. Enter the following data:\n");
printf("Enter the number of adults\n");
scanf("%hu", &(ptr[a-1][b-1].count_Adults));
printf("Enter the number of children\n");
scanf("%hu", &(ptr[a-1][b-1].count_Children));
printf("Enter the name of the Family\n");
scanf("%s", ptr[a-1][b-1].Family_Surname);
printf("Date of entry:\n");
scanf("%s", ptr[a-1][b-1].Date);
printf("Enter the rent\n");
scanf("%f", &(ptr[a-1][b-1].rent));
}
else
{
printf("The apartment is occupied. Please, choose another one.\n");
}
}
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
int Tax = 0;
for(int i=0; i<floors; i++)
{
for(int j=0; i<flats_per_floor; j++)
{
if( (i==0) || (i==1) )
{
Tax = Tax + (3*ptr[i][j].count_Adults) + (1*ptr[i][j].count_Children);
}
else
{
Tax = Tax + (5*ptr[i][j].count_Adults) + (3*ptr[i][j].count_Children);
}
}
}
printf("Tax is: %d \n", Tax);
}
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short Elevator_location = 1;
unsigned number_of_residents = 0;
unsigned max_amount = 0;
for(int i = 1; i < floors - 1; i++)
{
for(int j = 0; j<flats_per_floor; j++)
{
number_of_residents = number_of_residents + ptr[i][j].count_Adults + ptr[i][j].count_Children + ptr[i-1][j].count_Adults + ptr[i-1][j].count_Children + ptr[i+1][j].count_Adults + ptr[i+1][j].count_Children;
}
if(number_of_residents >= max_amount)
{
max_amount = number_of_residents;
number_of_residents = 0;
Elevator_location = i + 1;
}
else
{
number_of_residents = 0;
}
}
printf("The elevator's default floor is to be set to ");
if(Elevator_location == 2)
{
printf("%hu nd floor.\n", Elevator_location);
}
else if(Elevator_location == 3)
{
printf("%hu rd floor.\n", Elevator_location);
}
else
{
printf("%hu th floor.\n", Elevator_location);
}
}
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short Entered_number = 0;
int i = 0, j = 0;
printf("Enter the number of the apartment you wish to empty:\n");
scanf("%hu", &Entered_number);
for(i=0; i<floors; i++)
{
for(j=0; j<flats_per_floor; j++)
{
if(Entered_number == ptr[i][j].Flat_ID)
{
ptr[i][j].count_Adults = 0;
ptr[i][j].count_Children = 0;
ptr[i][j].Family_Surname[0] = '\0';
ptr[i][j].rent = 0.00;
printf("Apartment is empty");
break;
}
}
if(Entered_number == ptr[i][j].Flat_ID)
{
printf("TEST");
break;
}
else if(i == (floors - 1))
{
printf("No such apartment");
}
}
}
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50])
{
FILE *fp;
fp = fopen(FileName,"wb");
if(fp==NULL)
{
printf("Error opening file");
fclose(fp);
exit(2);
}
fwrite(&floors,sizeof(unsigned),1,fp);
fwrite(&flats_per_floor,sizeof(unsigned),1,fp);
for(int i = 0; i < floors; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
fwrite(&ptr[i][j],sizeof(S_Apartament),1,fp);
}
}
fclose(fp);
}
I can think of no other way to fix this. Any help would be appretiated. Sorry for the huge amount of code.
In your memalloc and these lines you close the file
fread(&floors,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
fclose(f);
but later in your loop you try to read from it, and a few lines after this you close it again
for(int j = 0; j < flats_per_floor; j++)
{
fread(&Apartment,sizeof(S_Apartament),1,f);
arr[i][j]=Apartment;
}
Try removing the first fclose call.

Im trying to put return at the end of the code but they keep messing me up with while before return

Like i want to put the "return 0" at the right place, everything in the code is working normal.
complie the code and they keep saying about "while before return", i tried to put outside of the code and inside
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
int menu(){
printf("Menu:\n");
printf("1- Add a value\n");
printf("2- Search a value\n");
printf("3- Print out the array\n");
printf("4- Print out values in a range\n");
printf("5- Print out the array in ascending order\n");
printf("6- Quit?\n");
printf("Enter your operation: ");
int choice;
scanf("%d", &choice);
return choice;
}
int isFul (int*a, int n){
return n==MAXN;
}
int isEmpty (int*a, int n){
return n==0;
}
void add(int value, int*a, int*pn){
a[*pn] = value;
(*pn)++;
}
int search(int x, int *a, int n){
int i;
for (i=0; i<n; i++) if (a[i]==x) return i;
return -1;
}
void printvalueinrange (int*a, int n){
int i, min, max;
printf("\nEnter min value: ");scanf("%d", &min);
printf("\nEnter max value: ");scanf("%d", &max);
for(i=0; i<sizeof(a); i++)
if(a[i]>=min&&a[i]<=max) printf("%d", a[i]);
}
void printarray(int*a, int n){
int i;
for (i=0;i<n;i++) printf("%d", a[i]);
}
void printAsc(int*a, int n){
int** adds =(int**)calloc(n, sizeof(int*));
int i,j;
for(i=0; i<n; i++) adds[i]= &a[i];
int* t;
for (i=0;i<n-1; i++)
for(j=n-1; j>i; j--)
if (*adds[j]< *adds[j-i]){
t=adds[j];
adds[j]=adds[j-1];
adds[j-1]=t;
}
for (i=0;i<n; i++) printf("%d ", *adds[i]);
free(adds);
}
int main(){
int a[MAXN];
int n=0;
int value;
int choice;
do
{ choice= menu();
switch(choice){
case 1:{
if (isFull(a,n)) printf("\n Sorry! The array is full.\n");
else
{ printf ("Input an added value:");
scanf("%d", &value);
add(value, a, &n);
printf("Added!\n");
}
break;
}
case 2:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{ printf ("Input the searched value:");
scanf("%d", &value);
int pos = search(value, a, n);
if (pos<0) printf("Not found!\n");
else printf("Postion is found: %d\n", pos);
} break;
}
case 3:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{
printarray(a,n);
} break;
}
case 4:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{
printvalueinrange(a,n);
} break;
}
case 5:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{
printAsc(a,n);
} break;
}
default: printf ("Goodbye!");
break;
}
while (choice>0 && choice<7);
getchar();
}
return 0;
}
I just adding some word to fit with the requirement :"D
And if u find out any kind of error or mistake that in my code, just points out for me to improve them xd
In this part of main
}
while (choice>0 && choice<7);
getchar();
}
return 0;
}
the while construction occupies a wrong place.
There should be
}
} while (choice>0 && choice<7);
getchar();
return 0;
}
Also in this statement
if (isFull(a,n)) printf("\n Sorry! The array is full.\n");
^^^^^^
there is a typo. There should be
if (isFul(a,n)) printf("\n Sorry! The array is full.\n");

how to transfer globals to functions and how to calculate the input of arrays?

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;
}

Resources