Void function doesn't print - c++

I am trying to write a code to print values using function and the program doesn't print anything and I don't know why. I know void function don't return any value so I put cout inside the function and I call is correctly
#include <iostream>
using namespace std;
void Print(int n){
for (int i = 0; i <= n; i++){
if (n%i == 0){
cout << i << ' ';
}
}
cout << endl;
}
int main(){
int x;
cin >> x;
Print(x);
return 0;
}

Start your loop from 1 in Print function. You can not mod a number with 0. Division by zero is not allowed.

When you run your program, it wont print anything. You have to enter a number first, then press Enter/Return, and then it should print something.
Assuming you do this and it still does not print, that will be because your Print has a loop that starts from i = 0, and you then do n % i. Doing the modulo % operation with a right-hand-side operand of 0 is not going to work. Start the loop from i = 1 or something else >0.
Lastly, your program will terminate in main at the return 0; right after the first Print. This means that most of your main won't actually be executed. This is probably intentional, but keep that in mind.
Fix these issues and make sure you enter a number into your program when it runs that is valid, like 12, and it should print something.

Related

Does it matter where I initialize my integer?

I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.
However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?
Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.
#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;
int main() {
int value = 0; // where I input
cin >> value;
// if you put int result above cin program changes.
int result = value % 2;
if (result == 0) {
cout << "Even number." << endl;
}
else {
cout << "Odd number." << endl;
}
return 0;
}
Any code whichever programming language you use runs from top to bottom.
You need to first declare the variable, give it a value and then check for being even or odd.
When you used cin after setting the value of result = value%2; the compiler used the originally initialized value for value which is 0 to compute the value of result which will be 0%2.
That's why you need to use cin>>value; before setting result = value%2;.
C++ read the code top to bottom , line by line. So you will have to int your variable first.I made a much more simpler version of the program if you want to read it:
#include <iostream>
using namespace std;
int main() {
int a;
cout << "a=";
cin >> a ;
if(a%2==0)
{cout<<"a is even";}
else
{cout<<"a is uneven";}
}
When you put int result = value % 2; before cin >> value;, your program will calculate the result before you put a value inside int value via your input.
So your program does calculate int result = 0 % 2;

C++ "While" Loop

I'm struggling to apply a "While" loop to the following problem: Design the logic for a program that allows a user to enter a number. Display the sum of every number from one through the entered number.
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
I know my code isn't correct as it is just adding one to the initial value until the user's number is reached, thus making the output the user's number. How would I go about adding each subsequent value without writing them out e.g. user's number is 10, so the program would add 1+2+3+4+5+6+7+8+9+10 and output the total of 55?
Thank you!
Here's a tip. You'll want to start at the users number and count down to 0. Like this:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
EDIT: It appears you've posted pseudocode; usually a big no-no here unless stated otherwise. It's better to post the actual code as it's easier to tell what exactly is going on.
The function you need could look like this for c++:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
An alternative is:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
This works because the sum of all integers from 1 to n is n*(n+1)/2

C++ Array in a prime number search

So I was trying to answer a question on Project Euler (The question was: Find the 10,001 prime number), and ran into a problem that I don't know why it is happening. When I run the following C++ code,
#include <iostream>
using namespace std;
int main()
{
int arr[10001]={2}, term=1, i, num=3;
while(term!=10001)
{
for(i=0; i<term; i++)
{
if(num%arr[i]==0){
break;
}
}
if(i==term){
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
}
num++;
}
cout<< arr[term]<< endl;
}
I always get cout<< arr[term]<< endl; printing out whatever n++;(next number in this case but if I were to change that to n=856then it would print out that number). I dont understand why that array term would change since I thought it would only change when arr[term]=num;is executed
Your code has undefined behaviour because you are accessing the array outside of its bounds.
When the loop breaks, the value of term is 10001, which is the 10002nd element of the array arr whereas your array memory allocated only for 10001 elements.
To print the last element of the array, do:
cout<< arr[term - 1]<< endl;
In every iteration, you execute
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
So when the while ends, term is one more that the one you used for the last assignment.
You have to output the arr[term-1] instead of arr[term] because term is incremented at the end of the assignment to the arr[], hence the term variable is 1 more 10001.
Edited code:
#include <iostream>
using namespace std;
int main()
{
int arr[10002]={2}, term=1, i, num=3;
while(term!=10001)
{
for(i=0; i<term; i++)
{
if(num%arr[i]==0){
break;
}
}
if(i==term){
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
}
num++;
}
cout<< arr[term-1]<< endl;
//Your 'term' variable actually is term + 1, hence, you have
//to print the element at 'term - 1'.
}

passing int variables in C++ - error check not returning value

okay so I am trying to check variables when they are input by the user, however they don't seem to stick. now the error check seems to work, but the variable is lost somewhere leaving 'num = 0'
I had copied some of this code from another source but I am not sure where it is going wrong.
I would like to input a number, check if it is an integer, and then return said integer to the variable 'num'.
#include <iostream>
using namespace std;
int checkCin(int var) {//open function
bool ok = false;//set variable to false
while (!ok)/*if variable is false, loop*/ {//open loop
cin >> var;
//this will cheack if anything is in variable other than an integer
if(!cin.fail() && (cin.peek()==EOF || cin.peek()=='\n')) {//open if
ok = true;//this will end loop
return var;
}//close if
//this will clear the cin and ignor whats left - ignoring this part stops an infinate loop cycle
else {//open else
cin.clear();
cin.ignore(256,'\n');
cout << "Error, enter a number" << std::endl;
}//close else
}//close loop
//prepared for next input
ok = false;
}//close function
int main() {
int num = 0;
checkCin(num);
cout << num << endl;
system("pause");
return 0;
}
You are returning the read number from your function by doing
return var;
at some point, but you are not using the result in your main function. You just have
checkCin(num);
in there, which throws away the result. Also, the input argument does not really make sense, because you pass by value and therefore cannot modify the value seen in main inside the function. What you could do is declare checkCin without parameters and assign the return value in main, i.e.
num = checkCin();
This would be most obvious for someone reading your program the first time, because checkCin doesn't need the original value of var and therefore it doesn't need to be passed in.
Another way would be to declare checkCin as taking a reference and returning nothing, i.e. void checkCin(int& var). Then you could keep your code in main, because now the function can actually modify the variable num passed in from main. However, this second solution would be quite uncommon for a function that returns only a single simple piece of data like an int.
Here's a cleaned up version of your code (you also see, with proper indentation, the "open loop", "close loop", etc. comments would not be necessary, because nesting levels are obvious):
#include <iostream>
using namespace std;
int checkCin() {//open function
int var;
while (true) { //open loop
cin >> var;
//this will cheack if anything is in variable other than an integer
if(!cin.fail() && (cin.peek()==EOF || cin.peek()=='\n')) {//open if
return var;
} else { //open else
cin.clear();
cin.ignore(256,'\n');
cout << "Error, enter a number" << std::endl;
} //close else
} //close loop
} //close function
int main() {
int num = checkCin();
cout << num << endl;
system("pause");
return 0;
}

loop in c++ that keeps track when the count is divisible by 4

Hello I am having trouble with a c++ program. Basically its a loop that iterates the amount of times the user wants it to. Now when it reaches a number divisible by 4 it keeps track of that number and finally then outputs how many times the number entered was divisible by 4.
#include<iostream>
using namespace std;
int num;
int count;
int test = 0;
int main()
{
cin>> num;
for (int count = 0; count < num; count++)
if (count % 4 == 0)
(test++);
else
cout<<"";
return 0;
}
Well - if you use return in main, your program will just exit, because that's what return does - ends the function and returns some value. If you want to actually print the value of test, do it before you return:
cout << test;
getch(); // use this so the console won't close automatically
return 0;
Also, the whole program could be written much better:
int main()
{
cin>> num;
cout << num/4;
getch(); // use this so the console won't close automatically
return 0;
}
Do you need to use a loop? If you just need "How many times is a given number divisible by 4" and are not required to loop
#include<iostream>
using namespace std;
int main()
{
int num;
cin>> num;
cout<< num<<" is divisible by 4 "<< (num>>2) <<" time"<<(num>>2>1?"s":"") <<endl;
return 0;
}
num>>2 is bit shifting to teh right twice, which is the same as doing an integer divide by 4. It could be replaced by num/4 if you wanted. Integer division always truncates, so for all positive numbers, it's like rounding down: the same behavior your loop gives you.