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)
{
....
}
Related
If number is like 25,35 output is "This number is prime",even though I know it's not a prime number. Why am I getting that output? With several other casual numbers it works.
#include<iostream>
using namespace std;
bool isPrimeNumber(int number){
bool isPrimeFlag=true;
for(int i=2;i<number;i++){
if(number % i == 0)
isPrimeFlag=false;
break;
}
return isPrimeFlag;
}
int main(){
int number;
cout<<"Number: ";
cin>>number;
bool isPrimeFlag = isPrimeNumber(number);
if(isPrimeFlag)
cout<<"Prime Number"<<endl;
else
cout<<"Not Prime Number"<<endl;
}
for(int i=2;i<number;i++){
if(number % i == 0)
isPrimeFlag=false;
break;
}
C++ is not Python: indentation does not affect your program's semantics - what matters are braces, and you have a missing brace for the inner if so the break instruction is always executed even if the if( number % i ) statement is false.
Whenever writing in C, C++, and other easy-to-shoot-yourself-in-the-foot languages it helps to use a linter tool that will force you to always use braces.
for(int i=2;i<number;i++){
if(number % i == 0) {
isPrimeFlag=false;
break;
}
}
I just started learning C++ and am trying to learn how to use scanf and printf for faster input and output. Here is the code I'm currently working on:
#include <stdio.h>
using namespace std;
int main() {
int time, record;
double down, loan;
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF) {
double value = down + loan;
double owed = loan;
double payment = owed/time;
// current simulated month and depreciation
int rday, c = 0;
double temp, dep;
bool found = false;
// finds value and owed after records
while (!found && record > 0) {
scanf("%d %lf", &rday, &temp);
// adjusts value and owed to day before listed on record
while (!found && c <= rday) {
if (c == rday) {
dep = temp;
}
value *= 1 - dep;
if (c > 0) {
owed -= payment;
}
c++;
// determines if found date
if (owed < value) {
found = true;
}
}
record--;
}
// finds point where owed < value
while (!found && value < owed) {
value *= 1 - dep;
owed -= payment;
c++;
}
if (c - 1 == 1) {
printf("%d month\n", c - 1);
}
else {
printf("%d months\n", c - 1);
}
}
return 0;
}
When I run this on Code::Blocks, it prints the correct answers, but the outermost while loop doesn't terminate even when I enter CTRL+Z (I am using Windows). Here is my input:
30 500.0 15000.0 3
0 .10
1 .03
3 .002
12 500.0 9999.99 2
0 .05
2 .1
60 2400.0 30000.0 3
0 .2
1 .05
12 .025
-99 0 17000 1
Here is an image of the what happens:
Error
I've tried changing the loop condition to scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4, but the same problem happens. Could someone please explain what the issue with my code is?
In the line
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) != EOF)
you expect 4 variables to be read into when the read is successful. When scanf is able to successfully extract the data from stdin for all the arguments, it will return 4. Change the check to use that number.
while (scanf("%d %lf %lf %d", &time, &down, &loan, &record) == 4)
It's because scanf never returns EOF, so the termination condition is never satisfied.
Thanks for the suggestions and answers, everyone! I figured out the bug. Kind of embarrassing, but it turns out the issue was with the last line of input.
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.
I am a C language beginner. I got this assignment to program for diving score. the rule is that the score has to be between 0 to 10, if the score is invalid, the program should ask for a new score, and there should be at least 4 judges to give the score.
I am having problem with the part with the for loop, I want the program to keep checking if the score is invalid or not, but I couldn't repeat the for loop. please help me, here is my code.
for (index = 0; index < judges; index++)
{
printf ("Enter the score for judges #%d(1-10): ", index + 1);
scanf ("%f", &score[index]);
if ((score[index] >= 0) && (score[index] <= 10))
{
totalscore += score[index];
}
else
{
totalscore = 0;
for (index = 0; index < judges; index++)
{
printf ("11111Enter the score for Judges #%d(0-10): ", index + 1);
scanf ("%f", &score[index]);
if ((score[index] >= 0) && (score[index] <= 10))
{
totalscore += score[index];
return EXIT_SUCCESS;
}
Use this pattern:
do
{
prompt();
scanf(&variable);
}
while (is_invalid (variable));
This way, you only need to check if the variable is valid in one place and you only need to prompt in one place.
Your multiple whiles and ifs are error prone and hard to get right.
So instead of:
printf ("Enter the number of judges (must bewteen 4-8): ");
scanf ("%d", &judges);
if ((judges < 4) || (judges > 8)){
while (true) {
printf ("\ninvaild number of judges\n\nEnter the number of judges (must between 4-8): ");
scanf ("%d", &judges);
if ((judges >= 4) && (judges <= 8)) {
break;
}}}
Use:
do
{
printf ("\n\nEnter the number of judges (must between 4-8): ");
scanf ("%d", &judges);
}
while ((judges < 4) || (judges > 8));
why you use the same variable "index" in the inner for loop? it'll mess up everything. suppose you have 4 judges, you have inputed 3 and 5. you try to input 17, and now the index is 2, right? but the score is invald, so it will goto the "else { xxxxx }" , here you have a inner for loop "for (index = 0; index < judges; index++)" , so the variable "index" come back to 0! IMO in this case, "while" is better:
while ((score[index] < 0) || (score[index] > 10))
printf(xxxxxxx)
scanf(xxxxxxx)
if you really need more than one for loop, you should use different variables:
for (i=0; i<judges; i++)
/*DO STH*/
for (j=0; j<judges; j++)
/*DO STH*/
for (k=0; k<judges; k++)
/*DO STH*/
Looking at your code, I believe that your problem isn't understanding "for" loops in C but rather building the correct flow of your program (your "algorithm" if you will) before approaching the code.
Practice Pseudo-Code for this:
For Each Judge:
Continue to ask for score until it is valid
Or you can break it down even more:
Beginning of loop:
Current Judge = 0
current Score = invalid
Do this while score is invalid
ask score of current judge.
Increment Current Judge
Unless no more judges, go to beginning of 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.