remembering the value of a counter - c

#include <stdio.h>
int main()
{
int input, counter,value;
int ABC[3];
counter = 0;
scanf("%d", &input);
switch (input)
{
case 1:
if (counter >=4)
{
printf("Error\n");
}
scanf("%d", &value);
ABC[counter]= value;
printf("ABC[%d] is %d \n", counter, ABC[counter]);
counter++;
main();
break;
case 2: //do anything
main();
break;
default:
printf("a is anything\n");
break;
}
return 0;
}
I want to put in array ABC every time i choose case 1 a value, until array ABC is full. My problem is, that i can only enter in this programm values into ABC[0] . Is there any way, to remember the value of counter, so it's not always 0? Maybe using if-statement? But how to formulate an if-statement in this programm, which is only once in the beginning true?
But ABC should also be allowed to have empty space

After "counter++" you are re-calling your "main" function, that reinitializes your counter to 0. You should use a loop:
int counter = 0;
do
{
// Your scanf goes here
switch(scanf_result)
{
// Add your case labels here
default: // Incorrect input? Let's start again!
continue;
};
counter++;
}
while(counter < 3);

i think that declaring counter outside the main function, would make it global scope.
in this way everytime you call main(); you reset the value to 0.
so write int counter = 0 before the main declaration, at row number 2.

Related

How to copy a multidimensional array to another without knowing the exact amount of rows in C?

So my program is basically built to get game scores, and track w/l/t, etc. What I am needed to do is to arrange the scores in ascending order based off of the opponent's scores.
So to do that I decided to bubble sort, but when I do that and print it, the first pair [0][0], and [0][1] come out with big negative numbers, which is what I'm guessing is their reference then after that the rest print correctly. I've googled around and couldn't find anything about this so I was wanting to copy the original array into a copy and try sorting with that one.
#include <stdio.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS //doesn't work
#define FLUSH myFlush()
#define GAMES 50
void titleDisplay(int);
void menuOptions();
void gameResults(int *counter, int team[][2], int); // records games from user input
void showRecord(int counter, int team[][2]); // shows current record
void displayResultFromGamesWon(int counter, int team[][2]);
void displayAllResults(int counter, int team[][2]); // shows all results ordered by opp score.
char getChoice();
void myFlush();
int main() {
//const int GAMES = 50; - program doesn't read this as a const when used to create arr.
const int MAX_GAMES = 50;
int userTeam[GAMES][2]; // array column 0 is user score, column 1 is opp score
int gameCounter = 0;
char userChoice;
do {
system("clear");
titleDisplay(1);
menuOptions();
userChoice = getChoice();
switch (userChoice) {
case 'a': case 'A':
gameResults(&gameCounter, userTeam, MAX_GAMES);
break;
case 'b': case 'B':
showRecord(gameCounter, userTeam);
break;
case 'c': case 'C':
displayResultFromGamesWon(gameCounter, userTeam);
break;
case 'd': case 'D':
displayAllResults(gameCounter, userTeam);
break;
case 'e': case 'E':
printf("Bye bye.\n");
system("pause");
break;
default:
printf("Invalid selection, choose again!\n");
system("pause");
break;
}//end switch
} while (userChoice != 'e' && userChoice != 'E');
return 0;
}
Here's where I sort and print:
//function definition
void displayAllResults(int counter, int team[][2]) {
int i;
int temp, temp2 = 0;
system("clear");
if (counter == 0) {
printf("\n\n\tYou haven't played any games yet.\n\n\n");
}
else {
titleDisplay(4);
printf("\t (Arranged by Opponent score low to high)\n\n");
printf("\tUser Score\t\t\tOpponent Score\n");
printf("\t----------\t\t\t--------------\n");
//begin bubble sorting
for (int x = 0; x < counter; x++) {
for (int y = x + 1; y < counter; y++) {
if (team[x][0] > team[y][0]) {
temp = team[x][1];
temp2 = team[x][0];
team[x][0] = team[y][0];
team[x][1] = team[y][1];
team[y][0] = temp2;
team[y][1] = temp;
}//end if
}
}//end bubble sort
for (i = 0; i < counter; i++) {
printf("\t%-8i\t\t\t%-11i\n", team[i][0], team[i][1]);
}//end for
}//end else
system("pause");
}//end function
I've tried declaring a variable of 'int sortedArray = team[counter][2];' in the displayAllResults function but that gave memory problems, and failed when I tried to access that variable. I tried memcpy, but either I didn't implement correctly or that doesn't work either.
Is it even possible to copy a 2D array like this to another one?
There are two ways to copy an array to another:
1-Using sizeof(array) and dividing it to size of one element of the array, in this case it is a pointer.
2- The best way is, to have a variable which will show you the length of the array.
I think you made an implementational mistake. I couldn't understand what you are doing. What is 5 for?
In any case, do have a variable for the length of the array.

C Loop until the condition is met problem

I want to write a loop that runs until the user enters a number greater than 10, but I have to do something wrong because it creates an infinite loop.
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
for(int i=0;a<10;i++){
printf("Enter value>10");
i++;
printf("%d",&a);
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
You mix an index that does not make sense. Also you print the memory address of variable instead of its value, not sure it is what you wanted?
Code partially corrected (because I don't know what is your ultimate goal):
#include <stdio.h>
int main()
{
int a;
do {
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
printf("\na: %d\n",a);
} while (a <= 10);
printf("Result:%d\n",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
ps: \n is line return and added do while which is what you want when you want to execute a loop at least once.
Have a look at your for-loop: you let i start at zero, you continue until a is not smaller than ten anymore, but it's not the value of a you need to check, it's the one of i.
In top of that, you are doing a i++ within your for-loop, while this is already covered in the definition of the for-loop.
I think this is the code that you are looking for: See comments
#include <stdio.h>
int main()
{
int a, ok = 0, end_of_input = 0;
do {
printf("Please input an integer value (min. 10): ");
fflush(stdout); // So the user can see the above line!
switch(scanf("%d",&a)) {
case EOF: // End of input - Give up!
end_of_input = 1;
break;
case 1: // Got a number - Check it!
if (a < 10)
{
ok = 1;
} else {
printf("%d - Not appropriate input. Please try again.\n\n",a);
}
break;
default: // Summat else - "eat" the input to the next line
scanf("%*[^\n]\n"); // "eats" the rest of the line in the buffer w/o assignment
break;
}
} while (end_of_input == 0 || ok == 0);
if (ok) { // User entered a valid number
printf("Got a that is smaller than ten %d\n", d);
} else { // We have ran out of input
printf("See you want to leave us :-(\n");
}
return 0;
}
I am not sure what you are trying to achieve but one problem that I found in your logic is you prompting user for input outside the loop. So whenever you enter number less than 10 it always goes in infinite iteration.
Try following code, with scanf inside loop
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
int i=0;
for(;a<10;){
printf("Enter value>10");
scanf("%d",&a);
printf("%d",a);
i++;
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}

Deleting an element from an array of structures

I am tasked to create an inventory management program where a user can add an item, edit an item, or delete an item. I am almost done with the code, I am just having a problem in deleting an item, particularly deleting an element from an array of structures.
I already looked for similar problems and tried the solutions suggested. The method I tried in my code was deleting an element in an array by shifting the elements next to it down by 1. The program runs and hypothetically the code should work but every time I run the program and enter the "delete an item" option, the program stops (it doesn't just exit, it says "the program stopped working" meaning I broke a rule or something). I am thinking I might be exceeding the array size or something but I can't point what exactly the problem is. Is it forbidden to shift the elements in an array of structure, or is it just my code? Please help.
This is the code for my structure.
struct details {
char name[30];
double price;
int code;
int qty;
};
details item[SIZE];
This is the main function:
int main (){
int choice; //gets the choice of user from the menu
bool condition = 1; //loops the menu
int count=0; //counts the number of items in the inventory
do{
printheader(); //prints the title of the program
printmenu(); //prints the menu (list of commands)
scanf("%d", &choice);
switch(choice){
case 1: system("cls");
AddItem(count); //function in adding record
count++; //increments every time a new item is added
system("PAUSE");
system("cls");
break;
case 2: system("cls");
EditItem(count); //function in editing a record
system("PAUSE");
system("cls");
break;
case 3: system("cls");
count = DeleteItem(count); //function in deleting a record
system("PAUSE");
system("cls");
break;
case 4: system("cls");
//ViewItem(); //function in viewing a record
system("PAUSE");
system("cls");
break;
case 5: system("cls");
DisplayInventory(count); //function in displaying inventory
system("PAUSE");
system("cls");
break;
case 6: system("cls");
SaveFile(count); //function in saving the records to a file
system("PAUSE");
system("cls");
break;
case 7: system("cls");
count = LoadFile(); //function in loading the records from a saved file
system("PAUSE");
system("cls");
break;
case 8: printf("\nThank you!");
exit(0); //ends the program
break;
default: printf("\nInvalid Input!\n");
getch();
system("cls");
}
}while(condition = 1);
return 0;
}
This is the DeleteItem() function. It accepts n which is the number of items/records.
int DeleteItem (int n){
printheader();
int i=0, code, pos;
bool cont = true;
printf("\nEnter the code of the item you want to delete: ");
scanf("%d", code);
do{
if(code==item[i].code){
for (pos=i; pos<(n-1); pos++){
// item[pos].name = item[pos+1].name; //this basically deletes the i'th element and shifts the remaining ones
item[pos].price = item[pos+1].price;
item[pos].code = item[pos+1].code;
item[pos].qty = item[pos+1].qty;
}
printf("\nItem deleted!");
cont = false; //loop ends once the input of the user matches the data in the inventory
}
if(i==n){
printf("\nCode not found!\n\n");
cont = false; //loop ends when there are no matches
}
i++;
}while(cont);
}
When the delete an item option is entered in the program, the program asks the user for the code of the item. The program then scans the array of structures for an an element (item[i].code) that matches the code. Ideally, the program should delete the element and shift the other elements if the code matches. However, what happens is the program crashes and stops. I need help to spot where the problem is. Thank you very much!
EDIT
DeleteItem function:
int DeleteItem (int n){
printheader();
int i=0, code, pos;
//bool cont = true;
printf("\nEnter the code of the item you want to delete: ");
scanf("%d", code);
while(i<n){
if(code==item[i].code){
for (pos=i; pos<(n-1); pos++){
item[pos] = item[pos+1];
}
printf("\nItem deleted!");
break;; //loop ends once the input of the user matches the data in the inventory
}
i++;
if(i==(n-1)){
printf("\nCode not found!\n\n");
break;; //loop ends when there are no matches
}
}
return (n-1);
}
I'm a total newbie with C so I'm really sorry if you see some problematic codes. I'm working on it.
One problem is that your check for i == n is done after you have indexed the array using i. To fix that you should increment i before the check. Like:
i++; // Increment first
if(i==n){ // then check
printf("\nCode not found!\n\n");
cont = false; //loop ends when there are no matches
}
Another problem is that you don't handle the case where n is zero. In general I think that a while(i < n) { ... }; is a better approach than a do { ...} while(...);.
Also notice this code (currently commented out) is wrong:
// item[pos].name = item[pos+1].name;
You can't copy a string using assignment (i.e. =). You'll need to use strcpy
Also I can't see any update of count when an item is deleted. I guess that's bug... I would assume that count has to be decremented.
Finally, I don't see the function returning any value. That's also a bug since you define the function to return an int.
A note...
Using a flag like cont to terminate the while loop will work fine and is therefore not a bug. However, you don't really need a flag. You could do using either a break like:
do{
...
...
if(i==n){
printf("\nCode not found!\n\n");
break; //loop ends when there are no matches
}
i++;
}while(1);
or simply do a return as the function has nothing more to do.
EDIT
OP has posted a second revision of the code. This edit address that second revision.
One problem with the second revision is that the code always return n-1. That is done even when the "code" wasn't found. That's a bug.
The if(i==(n-1)){ is also wrong as it means item number n-i will never be tested.
Try something like this instead:
int DeleteItem (int n){
printheader();
int i=0, code, pos;
printf("\nEnter the code of the item you want to delete: ");
scanf("%d", code);
while(i<n){
if(code==item[i].code){
for (pos=i; pos<(n-1); pos++){
item[pos] = item[pos+1];
}
printf("\nItem deleted!");
return n-1; // End the function and return n-1 as an item was deleted
}
i++;
}
printf("\nCode not found!\n\n");
return n; // End the function and return n as no item was deleted
}
BTW: You should always check the value returned by scanf

Trying to get a REPEAT UNTIL (DO...WHILE) loop working in C

So I am writing this code for simple shape determining program, and I was trying to loop it, the condition, for the loop to end is when the value of the variable x is equal to 0 (all of teh variables are angels), since an angle cannot be 0, I think it is only logical to have the loop loop until the value entered is 0. However, the code does not seem to stop iterating even after the condition is met. the code is below:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x=0;
int y=0;
int A=0;
do {
printf("What is the value of x?");
scanf("%d", &x);
printf("What is the value of y?");
scanf("%d", &y);
printf("What is the value of A?");
scanf("%d", &A);
if ((A==90)&&(x==y))
{
printf("Square\n");
}
else if ((A==90)&&(x!=y))
{
printf("Rectangle\n");
}
else if ((A==60)||(A==120))
{
printf("Hexagonal\n");
}
else if ((A!=60)||(A!=120)&&(x==y))
{
printf("Rhombic\n");
}
else if ((A!=60)||(A!=120)&&(x!=y))
{
printf("Parallelogram\n");
}
else
{
printf("The values you have entered are not supported by the program,
try again!");
}
}while(x!=0);
printf("Thanks for using the program!");
system("pause");
return 0;
}
I cannot really see what the problem with the condition for the while loop is, please help!
The easiest way may be:
scanf("%d", &x);
if (!x) break; // break the loop, not asking anything else

error in if condition even i enter code correctly in c programming

#include <stdio.h>
#include <process.h>
int main()
{
int check;
int enter[7];
int i,j;
printf("enter any 7 number to be stored");
for(i = 0; i < 7; i++)
scanf("%d" ,&enter[i]);
printf("\nenter any number to check:");
scanf("%d" ,&check);
for (i = 0; i < 7; i++)
{
if (enter[i]=check)
{
printf("your entry is valid");
exit(0);
}
else if(enter[6]!=check)
{
printf("your entry is not valid");
exit(0);
}
else
continue;
}
return 0;
}
this executes without error but dont work correctly .. always prints out the input is valid.... even i enter the number which is not in array :(
This is assignment, not equality:
if (enter[i]=check)
Change to:
if (enter[i] == check)
Additionally, always check the result of input operations:
if (1 != scanf("%d" ,&enter[i]))
{
/* Handle invalid value. */
}
to ensure subsequent code is operating on variables that have been assigned values.
This line
if (enter[i]=check)
does not do what you expect. You probably meant
if (enter[i]==check)
The assignment is valid C, but instead of checking for equality, it sets enter[i] equal check, and then checks the value of check for being zero. If it is non-zero, the condition succeeds, regardless of the initial value of enter[i]. If the check is zero, then the condition fails, - again, regardless of the initial value of enter[i]. This is a very common mistake; many compilers issue warnings to alert you to the situation.
= is the assignment operator, not equality at all. Doing:
if (enter[i]=check)
enter[i] will take the value check, and then it will check whether enter[i] is nonzero.
if (enter[i] == check)
enter[i]==check)// 2 for compare
proper usage of = is assignment operator whilst == is testing the equality
#include<stdio.h>
#include<process.h>
int main()
{
int check;
int enter[7];
int i,j;
printf("enter any 7 number to be stored");
for(i=0;i<7;i++)
{
scanf("%d" ,&enter[i]);
}
printf("\nenter any number to check:");
scanf("%d" ,&check);
for (i=0;i<7;i++)
{
// printf("\nvalue of i is %d\n" ,i);
if (check==enter[i])
{
printf("your entry is valid");
exit(0);
}
else if(enter[i]!=check && i==6)
{
printf("your entry is not valid");
exit(0);
}
else
continue;
}
return 0;
}
now i got it all right . thanks :)

Resources