Program Compiles, Runs, but doesn't end in DevC++ - c++

I wrote a program to sum all odd numbers less than or equal to N. It's not the most efficient or eloquent program, but it works in the compiler on Codepad.org and does not work in DevC++. Usually when a program I wrote is stuck in some kind of infinite loop the program crashes in DevC++ and Windows stops it and lets me know.
Here, the program compiles and runs, but just sits with the cursor blinking and does nothing. Windows doesn't stop it, nothing happens, the program doesn't finish, no matter for how long I let it sit. I'm guessing this is a problem with DevC++ unless it's a problem with my code that Codepad overlooks. Will anyone explain to me what is happening here?
Here is my code:
#include <iostream>
using namespace std;
int odd(int N)
{
int i;
int sum = 0;
for(i = 0; i <= N; ++i)
{
while((i % 2) != 0)
{
sum = sum + i;
}
}
return sum;
}
int main()
{
int N;
cout << "Pick a value: ";
cin >> N;
cout << "The sum of all numbers <= to " << N << " is: " << odd(N);
return 0;
}
I've made the suggested change to an if-statement and the same problem is occuring:
#include <iostream>
using namespace std;
int odd(int N)
{
int i;
int sum = 0;
for(i = 0; i <= N; ++i)
{
if ((i % 2) != 0)
{
sum = sum + i;
}
}
return sum;
}
int main()
{
int N;
cout << "Pick a value: ";
cin >> N;
cout << "The sum of all odd numbers <= to " << N << " is: " << odd(N);
return 0;
}

while((i % 2) != 0)
{
sum = sum + i;
}
This is a infinite loop.Because if (i % 2 != 0) is true then the program will increment sum again and again.What you are probably looking to do is have an if statement instead of while

Seems like the edit is working, please try deleting the old output file and rebuilding and re-compile the entire program.
The output seems to be as follows:
Pick a value: 52
The sum of all odd numbers <= to 52 is: 676
Process exited after 1.034 seconds with return value 0
Press any key to continue . . .

make sure the window of the previous run is closed else the compiler will not recompile but just runs the previous version before you changed it.you may see this as an error stated at bottom in debug mode.
the while() is an infinite loop because i is not changed inside the while() or its {} so use if

Related

Why isn't break good enough?

C++
When I first ran this code with a different input value of 881, 643, 743, etc... which are all primes numbers, I got a result of "True" but when I input a higher number like 804047277, it came back as "True" when it should have been "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
I corrected my code (The code below) and received the correct answer, which was "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
return 0;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
Shouldn't the break in the if statement stop the loop overall? I am just trying to understand why the break wasn't good enough, and I had to return 0;
I would correct your code like following (see description afterwards):
Try it online!
#include <iostream>
int main() {
int num = 0;
std::cin >> num;
for (int i = 2; i < num; ++i)
if (num % i == 0) {
std::cout << "True (Composite)" << std::endl;
return 0;
}
std::cout << "False (Prime)" << std::endl;
return 0;
}
Input:
804047277
Output:
True (Composite)
As it is easy to understand, your program is intended to check primality and compositness of a number.
Mistake in your program is that you show False (Prime) when division by a very first i gives non-zero remainder. Instead, to actually check primality, you need to divide by all possible i and only if ALL of them give non-zero, then number is prime. It means that you shouldn't break or show False on very first non-zero remainder.
If ANY of i gives zero remainder then given number by definition is composite. So unlike the Prime case, this Composite case should break (or return) on very first occurance of zero remainder.
In code above on very first zero remainder I finish program showing to console that number is composite (True).
And only if whole loop finishes (all possible divisors are tested) then I show False (that number is prime).
Regarding question if break; is enough to finish a loop, then Yes, after break loop finishes and you don't need to return 0; after break, this return statement never finishes.
Also it is well known fact that it is enough to check divisibility until divisor equal to Sqrt(num), which will be much faster. So your loop for (int i = 2; i < num; ++i) should become for (int i = 2; i * i <= num; ++i) which is square times faster.

Why doesn't cout work in my code and doesn't show (i - 1) to me?

Can anyone help me with this code?I don't know why cout doesn't work and it doesn't show the (i - 1) in line 14;
The question is:
Joe have 240 minute to do his exam.First question need 5 minute time,second question want 10 minute and etc.He need k minutes to eat dinner after exam.Now we want to know how many questions can he do.
n is number of questions and k is the time that takes for eating dinner.
#include <iostream>
using namespace std;
int main()
{
int i, n, k, sum = 0;
cin >> n >> k;
for(i = 1; i <= n; i++){
if(sum <= 240 - k){
sum += 5 * i;
}
else{
cout << i - 1;
break;
}
}
}
cout is buffered. i probably does appear, just not where you're looking: right before the next prompt, because you're not sending a newline.
cout << i - 1 << '\n';
You may also see:
cout << i - 1 << endl;
Here, endl is a newline plus an instruction. When inserted into the ostream, if causes a flush, forcing all pending output to be written. That can be handy when you need to interleave buffers on one device, as when sending standard input and standard output to the same file or terminal.
because there is case like for n = 5 and k = 10 where sum cannot reach the threshold to actually print. i'm not sure about what you want to do but printing out of the loop might help.
#include <iostream>
using namespace std;
int main()
{
int i, n, k, sum = 0;
cin >> n >> k;
for(i = 1; i <= n; i++){
if(sum <= 240 - k){
sum += 5 * i;
}
else{
break;
}
}
cout << i - 1;
}

Code gives desired output but keeps on running

This code I wrote is supposed to subtract one from the number inputed, or divide by 2 based on whether it is a multiple of 3 or not. However, every time I try to run the code, It outputs the numbers I want but then doesn't stop running. I am new to coding and not sure how to fix this.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
int n;
cout << "Enter a positive number: " << endl;
cin >> n;
if (n < 0) {
cout << "Invalid input." << endl;
}
while (n >= 1) {
if (n % 3 == 0) {
n = n-1;
cout << n << endl;
}
else if (n % 3 != 0) {
n = n / 2;
cout << n << endl;
}
}
return 0;
}
This is a screenshot of the output I get. Instead of giving me the opportunity to run the code again it just stays like this:
I may be misunderstanding what you're asking, however, traversing through the code you can identify that nothing is being done to make the code run again. You would need add what you have inside another while loop. This new while loop would be something like while (input != 0) then run everything you have. In your input statement you could say "Please enter a positive number or enter 0 to exit". This is just an example of an approach, but the premise is that you need something to keep this loop running.

Difficulty implementing limit to how many integers print on each line C++

I have seen this question around, but I am having difficulty implementing some of the solutions into my own code.
The program being worked on finds all the prime numbers in an array and times how long it takes to find all the prime numbers. One of the stipulations though is making the program print only 10 numbers per line. I have tried a couple different methods to get this to work, but none of them print how I need them to. Here is the current code:
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;
static const int N = 1000;
int main()
{
int i, a[N];
clock_t start = clock();
for (i = 2; i < N; i++) a[i] = i;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++) a[i*j] = 0;
start = clock() - start;
for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";
printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);
return 0;
}
I'm sure this is a simple mistake on my own part, or maybe I dont have the proper understanding on how this works. If anyone can shed some light on the subject it would be greatly appreciated, thank you.
Just create a new counter, to count the number of primes found.
int primes = 0;
for (i = 2; i < N; i++) {
if (a[i]) {
primes++;
cout << " " << i;
if ( primes % 10 == 0)
cout << "\n";
}
}
for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";
What this snippet does is not at all what you want it to do. If your whitespace is any indication, it looks like you expect this all to be nested in the same for loop. However, it's actually processed like this:
for (i = 2; i < N; i++) if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0) cout << "\n";
In other words, two completely separate statements. The first one goes through every element of a[i] and outputs them with a space. When that loop is done to completion, the second statement then checks a condition and adds a newline (that check is also broken, but I'll get into that later).
In order to break after every tenth element, the newline check needs to be processed for each element, or at least each element printed, rather than at the end.
So as written, what you seem to expect would actually be something like:
for (i = 2; i < N; i++) {
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";
}
The braces { } are important here, since they ensure that all the enclosed statements are part of the for loop and processed for each iteration, not just the single statement immediately following it.
Which brings up the second issue: That newline check does not do what you think it does. From your explanation, what you want is for the check to trigger on every tenth value printed, and add a newline. However, if ((i = 1) % 10 == 0)…doesn't do that. At all.
Rather than triggering on every tenth value, all if ((i = 1) % 10 == 0 does is set i to 1 (which will really break your for loop) and then never trigger since i = 1 will always return 1 anyway. It's just a convoluted way to do exactly what you don't want.
As Amadeus mentions, one easy way to implement this is just to use a counter that increments every time you print a value, and test against that instead:
for (i = 2; i < N; i++) {
if (a[i]) {
cout << " " << i;
primes++;
if (primes % 10 == 0)
cout << "\n";
}
}
Again, note the braces enclosing the three statements for the if (a[i]) clause. This ensures the increment and newline check only happen every time a value is actually printed, rather than for every iteration of the for loop.

C++ - Nothing is displayed in console, no errors displayed, -1 is returned

I've recently (very, very recently) have gotten into programming in C++. I'm writing a program to find the highest prime number below prime. However, when I execute the code, nothing is displayed, and in the console it says this:
Process returned -1 (0xFFFFFFFF) execution time : 0.409 s
Press ENTER to continue.
I've tried some debugging, and I've figured out the problematic section is lines 17-19 (the if statement), but I can't figure out what I'm doing wrong.
C++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//cout << "maybe here?";
int prime = 1000;
//cout << "here";
while(true){
//cout << "here2";
int testr = ceil(sqrt(prime));
cout << testr;
bool isprime = true;
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
isprime = false;
}
}
if(isprime){
break;
}else{
prime--;
}
}
cout << prime;
}
Any and all help is appreciated! Thanks!
Additional Info:
I'm using Code::Blocks on Mac OSX 64 bit. I'm used to programming in Java, so it may just be a C++ thing I'm unaware of.
Quite a few issues.
1) The answer to your question "find the lowest prime number below prime" is 2, no programming required.
2) Assuming you want to find the greatest prime number below prime, you should test all numbers from prime - 1, downwards.
3) The very first iteration of your loop:
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
will cause an exception: division by 0.
The reason is that you are trying to divide by 0 in your for loop you should begin with 2. Take a look at this one, it's optimal I guess.
bool isPrime(int n) {
if(n<2)
return false;
for(int i=2;i*i<=n;i++)
if(n%i==0)
return false;
return true;
}