Integer variable changing value in C when it's not supposed to - c

I have no idea what's going on here. A project I am working on is the 2048 game. I am programming it in c. The thing is, I initially declared the score as 0 and have not implemented the scoring system yet but randomly it changes to 4? (I have it printed out)
Here's part of my code:
for(;;){
printf("Score: %d",user_score);
rand_i=rand()%(board_size+1);
rand_j=rand()%(board_size+1);
while(M[rand_i][rand_j]!=0){
rand_i=rand()%(board_size+1);
rand_j=rand()%(board_size+1);
}
rand_num= rand()%2*2+2;
M[rand_i][rand_j]=(rand_num);
for(i=0;i<board_size;i++){
printf("\n");
for(j=0;j<board_size;j++){
if (M[i][j]==0){
printf("[ ]");
}
else printf("[%4d]",M[i][j]);
}
}
printf("\n(w=up, a=left, s=down, d=right, q=quit) > ");
scanf("%c%c",&user_input);
//system("clear");
switch(user_input){
case 'w':
for(j=0;j<board_size;j++){
for(i=0;i<board_size;i++){
if(M[i][j]!=0 && i!=0){
for(k=i;k>0;k--){
if(M[k-1][j]==0){
M[k-1][j]=M[k][j];
M[k][j]=0;

I think you are writing beyond array M.
rand_i=rand()%(board_size+1);
rand_j=rand()%(board_size+1);
If M is declared as int M[board_size][board_size], than rand_i and rand_j could be one too large.
Hope this helps.

Related

Re-execute program based on user input in C

Hi i'm trying to learn programming in C on my own and have managed to make a verry, verry simple program that calculates the surface of a circle based on user input.
However the program runs only one time and then closes it.
This was initially the intention because it is only for learning but i want to expand on this program to increase my skills/knowledge and hope someone can point me in the right direction.
What i want to do now is instead of terminating the program after running it once; i would like to offer the user a choise to either stop the program or to continue it and to calculate a new circle.
I understand that it has to be done with an if else statment with the getchar function but i have some issues wrapping my mind around it on how to put it in a program flow. I hope someone can give me some directions on how to tackle this problem or can point me to some documentation that explains this properly.
Currently i have this:
int main(void){
float diameter;
double straal;
double oppervlakte;
char ch;
printf("Type de diameter van de cirkel:\t");
scanf("%g", &diameter);
printf("\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
printf("De straal =\t%g \n\n", straal );
printf("De oppervlakte =\t%f \n\n" , oppervlakte);
printf("Druk enter om af te sluiten.");
scanf("%c",&ch);
getchar();
return 0;
}
and im trying to accomplish something like this(below) but i can't get it to work properly (i get the warning that the label "diameter" is not defined while trying to compile it.)
#include <stdio.h>
#define PI 3.14
int main(void){
float diameter;
double straal;
double oppervlakte;
char ch;
printf("Type de diameter van de cirkel:\t");
scanf("%g", &diameter);
printf("\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
printf("De straal =\t%g \n\n", straal );
printf("De oppervlakte =\t%f \n\n" , oppervlakte);
printf("Druk 'd' om door te gaan of druk enter om af te sluiten.");
if(getchar() == 'd')
{
goto diameter; /* tried to use main(void) here but that also doesnt work */
}
else{
scanf("%c",&ch);
getchar();
}
return 0;
}
i do understand that goto is not the best practise to use but in this case it seemed the easyest way to solve this issue. (and the program is not that complex ofc). However if im wrong in this please let me also know.
Option 1: (likely the best choice): use a do..while loop. Place a do { above your primary code block, and add a } while (<repeat condition>); at the end. The program will run through the code once, check the repeat condition (which will be "did the user enter yes"), and if so repeat, otherwise not.
Option 2: recursively call main(). You said you "tried that", but I'm not sure if you tried it by attempting to use a goto or not. Just use the line main() to call the function again. Note that if you do this too many times you can end up with a stack overflow, because the computer keeps track of each call. It takes a lot to have it be a problem, but with enough repeats it can happen.
You can do something like:
while(true) //this is an endless loop
{
//display a menu like
1. calc area
2. [anything else if you want to add in future]
.
.
.
0. exit
//take user input (e.g 1 for calculating the area)
switch(user input)
{
case 1:
//code to calculate area
break;
case 2:
//code for anything else
break
case 0:
exit(0); //this will terminate the program
}
}
If you follow this pattern, you can add more options to your program in future. You just need to add a case in your switch statement and include that operation in your menu. You can search for menu driven c program to get more details. Try reading about while loop and switch... case statements.
I actually managed to make work in both ways.
Thanks for the tips and suggestions.

I need a function that ask the user to enter a pin and after 3 wrong attempts, they program terminates

I have to write an ATM program for a class, and i cant figure out how to make a function that will ask the user for a pin and if the pin is entered incorrectly three times the program will display an exit message then terminate.... this is what i have some far. I think my issue is i don't know the correct syntax to handle my issue.
I know i will need a for loop but not sure how exactly to construct it.
void validate_acc(){
int user_acc_try;
printf("Please enter your account number: ");
scanf("%d", &user_acc_try);
if(user_acc_try != account_number){
printf("You entered the wrong account number");
}
else{
printf("");
}
}
void validate_pin(){
int user_pin_try;
printf("Please enter your pin number: ");
scanf("%d", &user_pin_try);
if(user_pin_try != pin){
printf("You entered the wrong pin number.");
}
else{
printf("");
}
}
void validate(){
validate_acc();
validate_pin();
}
Secondly, since i can only post every 90 minutes might as well ask another question, I do not know how to make a function go back to the beginning of my program like for example say after an deposit, what is the logic i would need to use to have a function go back to the beginning of my main function. I know of goto labels, that didnt seem to work when i put it in front of my main function like so...
MAIN:
int main()
i would put goto main; in another function and i would get a.... Main is not defined error. I have read a few different questions on here about labels but cant find anything that helps, if someone could guide me in the right direction, you would be giving me a great deal of relief.
thank you in advance.
It's a good idea to write out a flow chart for things like this if you can't figure out how to do it in code.
Please do not use labels/goto in C. It's a nasty habit and it's not needed.
You know how to use if statements to make a decision; think about how you would use a while loop to try to make the same decision over and over again until something changes. For instance, in pseudo-code (because I don't want to do your work for you)
user_has_not_entered_correct_pin = true
retries_left = 3
while retries_left > 0 and user_has_not_entered_correct_pin:
get pin
if pin_is_not_correct(pin) retries = retries - 1
else user_has_not_entered_correct_pin = false
end while
I am limited on time right now, so I will just post a quick help. I would suggest start researching loops in C. Since this is for a class, the book you are using should have information in it about for loops and while loops, but if not, a simple Google search can help a lot.
With a quick search on Google, this site seemed like a decent site for basic information on loops:
Loops in C
It has links and examples of using a for loop, a while loop, a do...while loop and nested loops which should help you solve your problem.
Edited to add:
In your post you mentioned that you think the problem is that you don't know the syntax that you need. It is for that reason that I pointed you to a location that can help you with the syntax that you need to solve your problem rather than show you directly how to solve the problem. I hope that this helps you not only with this question, but going forward in your class as well.
Keep a count variable like I have did below and check the number of attempts:
I don't see a need for goto here. The same logic can be used for checking pin also.
int i=0;
while(1)
{
if(i>2)
{
printf("Maximum attempts reached\n");
break;
}
printf("Enter the acc_num\n");
scanf("%d", &user_acc_try);
if(acc_num == saved_acc_num)
{
// Do your stuff
}
i++;
}
Return value from validate_pin() int validate_pin(){... return 0; .... return 1;} and test it in the main() or your validate().
int i=0;
int result=0;
while ( (result==0)&&(i<3) ){
result=validate_pin();
i++;
}
Dont use goto, learn to use loops.

Why is the modulus operand not working on inputted variables in my C code?

I'm not new to C or anything, I was just doing a couple of exercises when...
for (i=0;i<no_1;i++)
{
if (no_1%i==0)
{
number_1=i;
}
This program is meant to display the highest common factor of two inputted numbers. The problem is, my code keeps stopping after the user inputs the second number, and I get this option to send an error report to Microsoft (I'm using Windows XP)
I've stripped all my code and realized that it was the modulus operator that was causing my program to stop, but I honestly don't see why. I tried using the modulus operator in a program by itself where I test if 10%2==0. That worked fine. So by deduction,my problem must be because the numbers I'm using are variables inputted by the user. But then why would it still not work? Am I missing some golden rule or something?
The problem is in the following:
for (i=0;i<no_1;i++)
Start the counter from 1:
for (i=1;i<no_1;i++)
You are currently causing a divide-by-zero error.
Change your code to:
int main()
{
int no_1,no_2,number_1=0,number_2=0,i,j;
printf("Enter a number: ");
scanf("%d",&no_1);
printf("\nEnter another number: ");
scanf("%d",&no_2);
for (i=1;i<no_1;i++)
{
if (no_1%i==0)
{
number_1=i;
}
}
for ( j=1;j<no_2;j++)
{
if (no_2%j==0)
{
number_2=j;
}
}
if (number_1==number_2)
printf("The HCF is %d",number_1);
else
printf("The HCF is 1");
return 0;
}
It's happening because you've start your counter from 0, it causes the division by zero error. Start the counter from 1 for both of your loop.

In C, How can I evaluate a local variable thats in one function, in a different function?

Ok so I'm creating this text adventure game. To be all unique and different, I decided to add an influence system where your responses to other characters can affect their responses to you as well their combat effectiveness.
I have a fair amount of experience in C++ and I just started my second semester-long course in C. So far, I have tried using global variables, structs, static variables, and using functions inside of other functions. I also tried using pointers but I kept getting errors every time so I stopped. This is a snippet of code that tries to use the influence system(Sorry for the stars, wouldn't want to give away any story plots):
#include <stdlib.h>
#include <stdio.h>
static int positive_Influence; int negative_Influence; int overall_Influence;
void printpInI(int positive_Influence, int negative_Influence);//positive and negative influence
int choice_6()
{
int choice = 0;
int positive_Influence, negative_Influence, overall_Influence;
positive_Influence = 0;
negative_Influence = 0;
overall_Influence = 0;
printf("What do you do?\n");
printf("\t1. You: ****\n");
printf("\t2. You: ****\n");
printf("\t3. You: ****\n");
do
{
scanf_s("%i", &choice);
switch (choice)
{
case 1:
{
printf("\t****?\n");
system("pause");
negative_Influence += 10;
printf("You lose influence and are now at %i with ****.\n", positive_Influence-negative_Influence);
break;
}
case 2:
{
printf("\t****");
system("pause");
positive_Influence += 10;
printf("You gain influence and are now at %i influence with ****.\n", positive_Influence-negative_Influence);
break;
}
case 3:
{
printf("**** smiles at this.\n");
system("pause");
positive_Influence += 10;
printf("You gain influence and are now at %i influence with ****.\n", positive_Influence-negative_Influence);
break;
}
}
}while(choice != 1 && choice != 2 && choice != 3);
overall_Influence = positive_Influence-negative_Influence;
printf("%i\n", overall_Influence);
}
void story_7()
{
printf("Your overall influence is %i\n", overall_Influence);
}
int main()
{
choice_6();
story_7();
system("pause");
}
You have declared overall_influence as a global but also as a local in choice_6. The local declaration takes precedence; just remove that and you should be OK. Same thing about the variables positive_influence and negative_influence.
Can you tell me which type of errors you got? Also you already declared global variables for calculating influence so why you again declared it locally in choice_6 function and that is the error case in you program so local variables have more precedence then global one within function in which they declared. So remove declaration from function choice_6.
I actually was just being really dumb because I forgot hows pointers worked (dam ampersans!) anyway thank you all for replying I really really do appreciate it. I am also working on a combat system that can use multiple enemies so keep watching my profile because I'll probably have moar questions later. If you would like to beta test, my email is mikemanahan15#gmail.com if you would like to play what I have so far. Of course, here is the finished code (for choice_6 and story_7) enjoy:
#include <stdlib.h>
#include <stdio.h>
int choice_6(int *influence)
{
int choice = 0;
printf("What do you do?\n");
printf("\t1. You: No. I know absolutely nothing about you. You could be a monster\n");
printf("\ttoo for all I know! Normal people don't turn into frogs!\n");
printf("\t2. You: Your right we should keep moving. You can tell me when your\n");
printf("\tready.\n");
printf("\t3. You: Okay where do you think should we go then?\n");
do
{
scanf_s("%i", &choice);
switch (choice)
{
case 1:
{
printf("\tBrie flashes a pained look on her face and you immediately regret saying that.\n");
printf("\tBrie: You really think I'm a monster?\n");
system("pause");
*influence -= 10;
printf("You lose influence and are now at %i with Brie.\n", *influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Your right we should keep moving.\n");
break;
}
case 2:
{
printf("\tBrie: Thank you. I'd rather not discuss this my life story in a dark\n");
printf("\tdungeon.\n");
system("pause");
*influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", *influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: I'd have to agree with you there. Let's see what is up these stairs.\n");
choice = 2;
break;
}
case 3:
{
printf("Brie smiles at this.\n");
printf("\tBrie: Well the only way out seems to be these stairs so let's go up.\n");
system("pause");
*influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", *influence);
system("pause");
printf("Influence affects characters reactions towards you, their effectiveness in combat, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Sounds good to me I am quite frankly done with dungeons about now.\n");
break;
}
default:
{
printf("Type the number for the choice you want to do\n");
system("pause");
break;
}
}
}while(choice != 1 && choice != 2 && choice != 3);
}
int story_7(int influence)
{
if (influence > 0)
{
printf("Brie laughs at this and slowly leans you off her to have both of you crouch.");
system("pause");
}
else
{
printf("Brie: Ugh just get off of me!\n");
printf("Brie pushes you off her violently and you manage to stay crouched.");
system("pause");
}
}
int main()
{
int influence = 0;
// ...
choice_6(&influence);
story_7(influence);
// ...
}
You should remove the local variables and use scope resolution operator to use your global variables
This would solve your question.
Also you can use these variables in any function you want later.

How to pass a local variable to another function?

So I am doing a text adventure game. It has Hundreds of lines of story, a fully functioning combat system, and I am now trying to create an influence system. Basically it is supposed to work like this: Certain responses/actions will increase or decrease your influence over different characters. I want to use the influence variable in choice_6() and story_7(). How do I do that? Please do not send me any links. I've gone through many many other answers and they haven't made sense to me so if your going to copy and paste, at least explain it a different way than other answers. Thank you.
int choice_6()
{
int influence = 0;
int choice = 0;
printf("What do you do?\n");
printf("\t1. You: No. I know absolutely nothing about you. You could be a monster\n");
printf("\ttoo for all I know! Normal people don't turn into frogs!\n");
printf("\t2. You: Your right we should keep moving. You can tell me when your\n");
printf("\tready.\n");
printf("\t3. You: Okay where do you think should we go then?\n");
do
{
scanf_s("%i", &choice);
switch (choice)
{
case 1:
{
printf("\tBrie flashes a pained look on her face and you immediately regret saying that.\n");
printf("\tBrie: You really think I'm a monster?\n");
system("pause");
influence -= 10;
printf("You lose influence and are now at %i with Brie.\n", influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Your right we should keep moving.\n");
break;
}
case 2:
{
printf("\tBrie: Thank you. I'd rather not discuss this my life story in a dark\n");
printf("\tdungeon.\n");
system("pause");
influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", influence);
system("pause");
printf("Influence affects characters reactions towards you, their combat effectiveness, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: I'd have to agree with you there. Let's see what is up these stairs.\n");
choice = 2;
break;
}
case 3:
{
printf("Brie smiles at this.\n");
printf("\tBrie: Well the only way out seems to be these stairs so let's go up.\n");
system("pause");
influence += 10;
printf("You gain influence and are now at %i influence with Brie.\n", influence);
system("pause");
printf("Influence affects characters reactions towards you, their effectiveness in combat, and even their allegiances in rare cases.\n");
printf("However, depending on the situation, low influence is not always a bad thing...\n");
system("pause");
printf("\tYou: Sounds good to me I am quite frankly done with dungeons about now.\n");
break;
}
default:
{
printf("Type the number for the choice you want to do\n");
system("pause");
break;
}
}
}while(choice != 1 && choice != 2 && choice != 3);
}
int story_7()
{
printf("\ninfluence is %i\n", influence);
printf("You lead the way walking upstairs\n");
system("pause");
printf("You turn the corner while crouched to find a room full of gremlins and goblins.\n");
system("pause");
printf("You grab Brie's hand and roll to the left behind some crates before they see you.\n");
system("pause");
printf("Even though you realize you will probably not make it out of this situation\n");
printf("alive, you can't help but feel lucky with Brie being so tightly pressed against you on the floor.\n");
system("pause");
printf("After a long period of silence to confirm nobody has seen you both enter,\n");
printf("Brie looks up at you and rolls her eyes.\n");
system("pause");
printf("*whispers*\tBrie: At least buy me dinner first jeez.\n");
system("pause");
printf("*whispers*\tYou: I'd love to but we should probably kill these uglies first.\n");
system("pause");
if (influence > 0)
{
printf("Brie laughs at this and slowly leans you off her to have both of you crouch.");
system("pause");
}
else
{
printf("Brie: Ugh just get off of me!\n");
printf("Brie pushes you off her violently and you manage to stay crouched.");
system("pause");
}
}
int main()
{
int play = 0;
int influence = 0;
intro_1();
story_1();
choice_1();
story_2();
choice_2();
story_3();
choice_3();
story_4();
choice_4();
story_5();
choice_5();
intro_2();
combat_1();
story_6();
choice_6();
story_7();
choice_7();
system("pause");
}
You can pass a pointer to the influence variable, if you want to modify it from within a function. Like this:
int choice_6(int *influence)
{
// ...
*influence -= 10;
// use *influence wherever you would have had used influence before
// ...
}
int story_7(int influence)
{
// ...
if (influence > 0) ...
// ...
}
int main()
{
int influence = 0;
// ...
choice_6(&influence);
story_7(influence);
// ...
}
This is passing a pointer to choice_6() because you need to modify influence from within that function. This is passing the value to story_7() because you do not need to modify the influence value there.
You should create game object(s) that stores the state of the game, in this case, influence and other event flags.
You will then need to either set this game object as a global, or pass it around by pointer/reference to every functions that may need to check or modify the game state.
struct MyGame {
int influence;
int has_cheese;
};
void choice_6(struct MyGame * game) {
...
game->influence += 10;
...
}
int main(...) {
struct MyGame game;
game->influence = 0;
game->has_cheese = FALSE; // or 0
...
choice_6(&game);
....
}
You need to pass the influence variable by reference. This means the function(s) you give the reference to can change the value of the variable itself (not just a copy of the variable).
Do this by prepending the parameter with a * in the function signatures, and passing with a & prepended:
int choice_6(int *influence)
{
....
int main()
{
int play = 0;
int influence = 0;
choice_6(&influence);
....

Resources