The program crashes after executing while loop - c++

The code shuts down after executing the while loop and does not execute the last 2 printf statements. I don't know whats wrong.. after the loop goes around for the chosen times the program just closes.
#include <stdio.h>
int main()
{
int numberofq;
int questionansc;
int questionansic;
int counter;
int answer;
numberofq = 0;
questionansc = 0;
questionansic = 0;
counter = 0;
answer = 0;
while(numberofq <1 || numberofq >5)
{
printf("Hello enter the amount of questions you want between 1 and 5 \n");
scanf("%d", &numberofq);
} // End While
//Program runs until the counter is less than users wanted question number.
while (counter < numberofq)
{
//Question 1
printf("Question 1. what is 2+2? \n");
scanf("%d" , &answer);
//if users answer is equal to 4.
if (answer == 4)
{
printf("You entered %d, you are correct\n", answer);
questionansc = questionansc +1;
} //End If
//If the answer is not equal to 4.
else
{
printf("You entered %d, you are wrong correct answer is 4 \n", answer);
questionansic = questionansic +1;
} // End Else
counter = counter +1;
//End Question 1.
} //End While
printf("You got %d questions correct \n" , questionansc);
printf("You got %d questions wrong" , questionansic);
flushall();
return 0;
} // End Main`

It actually prints them and then exits, but it exits so quickly you don't have a chance to see this.
You can pause execution using system("pause") on Windows, but that's considered bad practice. You could use getch() or something, but you could also simply invoke the program from an existing CMD/Terminal and in this way the output will stay there after the program is done.

Related

For loop only executes once, raising a number to another number

New to programming/coding, and couldn't get why my code doesn't work.
It's supposed to show you the result of raising a number to another number. But it only ends up looping once.
Example of error:
Input an integer: 3
Raise integer to what number: 4
3 raised to 4 is 9
My code:
#include <stdio.h>
int raiseToPow(int nNum1, int *nResult) {
*nResult = nNum1 * nNum1;
}
int main() {
int nNum1, nNum2, nResult, i;
printf("Input an integer: ");
scanf("%d", &nNum1);
printf("\n");
printf("Raise integer to what number: ");
scanf("%d", &nNum2);
printf("\n");
for (i = 0; i < nNum2; i++) {
raiseToPow(nNum1, &nResult);
}
printf("%d raised to %d is %d", nNum1, nNum2, nResult);
}
you should initialize nResult by 1 because your variable doesn't have anything inside. Also, replace *nResult = nNum1 * nNum1 by *nResult = *nResult * nNum1
It's looping the right number of times, you just need to put the print inside the loop. Also you should add a newline to the end of your print.
for(i = 0; i < nNum2; i++)
{
raiseToPow(nNum1, &nResult);
printf("%d raised to %d is %d\n", nNum1, nNum2, nResult);
}

Logic error with array and for loop

If I enter an amount of 5 players (5 elements in the score[] array) in the scanf("%d", &numPlayers) the for loop cycles the players all the way up to player 5 (element 4 of score[]), and then jumps to the winMsg function. The score of that element is a large value, even though I set all the score[] element's to 0 in the first for loop. If I enter 6 or more elements, the second for loop never executes. Program runs no problem with 4 or less elements in score[]. I am using gedit and terminal in Ubuntu. Any ideas? Fairly new to programming. I appreciate any help.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int rollDie(){
return (rand()%6 + 1);
}
void winMsg(int winRoll, int player, int winScore){
printf("Congratulations Player %d! Your winning roll was a %d, putting your score at %d!\n\nGame Over\n\n", player + 1, winRoll, winScore);
return;
}
int main(){
srand(time(NULL));
int numPlayers = 0;
int roll = 0;
int i = 0;
int score[numPlayers];
char choice[2];
printf("Welcome to the \"Roll to Win\" game. Each roll adds to the current player's score, according to the die's number. A roll of 1 will cause the player to recieve no points that round, and then be skipped to the next player. First player to reach 100 or over wins! Please enter number of players: \n\n");
scanf("%d", &numPlayers);
printf("\n");
while (numPlayers >= 100 || numPlayers <= 0){
printf("Please enter a number of players less than 100, greater than 0.\n\n");
scanf("%d", &numPlayers);
printf("\n");
}
for (i = 0; i < numPlayers; ++i){
score[i] = 0;
printf("Set Player %d score to %d.\n", i + 1, score[i]);
}
printf("Starting with Player 1.\n\n");
for (i = 0; i < numPlayers; ++i){
roll = rollDie();
if (roll == 1){
printf("Player %d rolled a 1. Skipping turn. Current score: %d.\n\n", i + 1, score[i]);
}
else{
do{
score[i] += roll;
if (score[i] >= 100){
winMsg(roll, i, score[i]);
exit(0);
}
printf("Player %d rolled a %d, continue rolling (enter r to roll, or sr to stop rolling)? Current score: %d.\n\n", i + 1, roll, score[i]);
scanf("%s", choice);
printf("\n");
while ((strcmp ("r",choice) != 0) & (strcmp ("sr",choice) != 0)){
printf("Please enter a correct selection (enter r to roll, or sr to stop rolling).\n\n");
scanf("%s", choice);
printf("\n");
}
if (strcmp ("sr",choice) == 0){
printf("Player %d decided to stop rolling. Continuing to next player.\n\n", i + 1);
break;
}
roll = rollDie();
if (roll == 1){
printf("Player %d rolled a 1. Skipping turn. Current score: %d.\n\n", i + 1, score[i]);
break;
}
} while (strcmp (choice,"r") == 0);
}
if (i == numPlayers - 1){
i = -1;
}
}
}
Notice, that you set the size when initializing array before it is known, therefore you end up with garbage.
Doing int score[numPlayers]; and later scanf("%d", &numPlayers); will not do what you think it does.
it is not standard C++ to have a static array size which is not a constant,if you want that behavior you should use std::vector.
Even if this is working for you, then you should first ask for the number of players and then create the array. i.e
scanf("%d", &numPlayers);//first
....
int score[numPlayers];//then

Loop doesn't stop!? (C++ programming)

I don't understand why my loop stops, i want the user to keep asking for a number and find its square root. If the user enters negative number THEN it should stop. please help, cant see my mixtake...
CODE:
int main (void)
{
double number, calc;
printf ("Enter a number to find its sqrt");
while (1)
{
scanf ("%lf",&number);
if (number > 0)
{
calc = sqrt(number);
printf ("The sqrt of %lf is %lf", &number, &calc);
}
else
printf ("Try again:\n");
}
return (0);
}
Not allowed to answer but, I see thanks you two!!
(Didnt know i must exist loop)
You must exit the loop somewhere.
if(number < 0)
break;
Alternatively you can do this (which would be better in this case):
number = 0;
while(number >= 0)
{
....
}

Complete Beginner: Null pointer issue?

I have looking all over forums to try and understand this issue. The reasons I cannot fully understand the issue and why I cannot find a solution is because I am fairly new with C++ and I do not understand the error message.
This is my code in C++ that finds the number of possibilities from permutation or combination formulas. Every I try and compile and run, I get messages that say:
First-chance exception at 0x6a8613af (msvcr100d.dll) in
Combinations_Permutations.exe: 0xC0000005: Access violation reading
location 0x00000005. Unhandled exception at 0x6a8613af (msvcr100d.dll)
in Combinations_Permutations.exe: 0xC0000005: Access violation reading
location 0x00000005.
I've learned on many other forums that the "access violation reading location 0x00..." could definitely indicate null pointer. But I cannot see where I encounter such a null issue. Maybe my variables are being accessed globally, where they are not YET initialized?
Here is my code, I have been at it for a while... like I said I'm fairly new. So please inform me of my mistake(s). Thank you.
My code:
#include <iostream>
#include "conio.h";
using namespace std;
int run_combination(int n, int r);
int run_permutation(int n, int r);
int solve_factorial(int f);
int f_value = 1; //factorial value used recursively
int n_input, r_input;
char choice;
char order;
void main(){
//if user types choice as 'q', while loop ends
while(choice != 'q'){
printf("How many values? (1-9) \n");
printf("User: ");
cin >> n_input;//user input for variable n
printf("n_input: %i", n_input);
printf("\nHow many will be chosen at a time out of those values? (1-9)\n");
printf("User: ");
cin >> r_input; //user input for variable r
printf("\nDoes order matter? (y/n)\n");
printf("User: ");
cin >> order; //'y' if order is taken into consideration(permutation)
//'n' if order it NOT taken into consideration(combination)
int solution = 0; //temporary variable that represents the solution after running
//n and r through the permutation or combination formula
//if user input values for n and r are in between 1 and 9, then run
//combination or permutation
if (n_input <= 9 && n_input >= 1 && r_input <= 9 && r_input >= 1){
if (order == 'y')
solution = run_permutation(n_input, r_input);
else if (order == 'n')
solution = run_combination(n_input, r_input);
else
printf("\nError. Please type 'y' or 'n' to determine if order matters.\n");
//if n < r, run_permutation or run_combination returns 0
if (solution == 0){
printf("Error! You can't choose %i values at a time if there \n",
"are only %i total values. Type in new values next loop \n.", r_input, n_input);
}
else
printf("Number of possibilities: %s", solution);
}
else{ //else error message if numbers are out of range...
printf("Next loop, type in values that range from 1 to 9.\n");
}
//option 'q' to quit out of loop
printf("Type 'q' to quit or enter any key to continue.\n");
printf("User: ");
cin >> choice;
}
_getch();
}
/*
Returns solved combination of parameters n and r
Takes the form: n! / r!(n-r)!
*/
int run_combination(int n, int r){
if (n < r) //solution is impossible because you can't choose r amounnt at a time if r is greater than n
return 0;
int n_fac = solve_factorial(n); //n!
int r_fac = solve_factorial(r); //r!
int nMinusr_fac = solve_factorial(n-r); //(n-r)!
int solve = ((n_fac) / ((r_fac)*(nMinusr_fac))); // plugging in solved factorials into the combination formula
return solve;
}
int run_permutation(int n, int r){
if (n < r)
return 0;
int n_fac = solve_factorial(n);
int nMinusr_fac = solve_factorial(n-r);
int solve = ((n_fac) / (nMinusr_fac)); //plugging in factorials into permutation formula
return solve;
}
int solve_factorial(int f){
if (f-1==0 || f == 0){ //if parameter f is 1 or 0, return 1
int temp = f_value;
f_value = 1; //reset f_value so that f_value remains 1 at the start of every new factorial
return temp;
}
else{ //else multiply f_value by f-1
f_value *= f;
return solve_factorial(f-1);
}
}
This is a mistake:
printf("Number of possibilities: %s", solution);
solution is an int, not a null terminated string: use %d.
Using std::cout which is typesafe, instead of printf(), would have prevented this error:
std::cout << "Number of possibilities: " << solution;
The problematic line is:
printf("Number of possibilities: %s", solution);
You're telling printf that solution is a char*, and so it tries to dereference (char*)solution to print the contents of the "C-string" (presumably when solution has the value 5 in the case of your particular error message).
Change %s to %d, or use std::cout instead of printf to gain type-safety and avoid this sort of issue in the first place.

First Semester CS Student needs help understanding statement in While loop

I normally post on DreamInCode.net but the site seems to be down right now. I'm a first semester CS student at De Anza. I don't understand really what the lineCount = 1; does in the else statement. I know what it does when I remove the statement but I don't understand it. If I could have someone explain it to me maybe in a different way that the book just happens to skip over, I would greatly appreciate it.
#include <stdio.h>
int main (void) {
int num;
int lineCount;
printf ("\nEnter a starting number to decend between 1 and 100: ");
scanf ("%d", &num);
if (num > 100)
num = 100;
lineCount = 0;
while (num >= 0)
{
if (lineCount < 10)
lineCount++;
else
{
printf ("\n");
lineCount = 1; // this line here is what I don't understand
}
printf ("%4d", num--);
}
return 0;
}
lineCount isn't actually counting lines. It's counting the number of numbers you've printed on the current line.
When that reaches 10, it breaks the line and starts a new one, resetting the counter to 1. 1 instead of 0 because you're placing another number on the new line.