for-loop variable takes a random value at the beginning - c++

So, I am trying to do this code, which lets the user know whether a given nr. is a perfect one or not. But I am facing some difficulties in a part of my code. I also tried to solve it with a debugger, and I always see the initial value of variable "i", which I use in my for-loop, take a huge random value for no reason at all. While for the nr. 6, you get the correct answer, for nr. 28 you don't.
And maybe this is the reason why my code doesn't work as it should
#include <iostream>
using namespace std;
int main()
{
int a,a_half,sum_divisor=0;
float multi=0.0;
cout <<"Give number: ";
cin >>a;
a_half = a/2;
for(int i = 1;i<=a_half;i++)
{
multi=a/i;
if(int(multi)==multi)
{
sum_divisor+=i;
}
}
if(sum_divisor==a)
{
cout << a<<" is a perfect one!"<<endl;
}else
{
cout <<a<<" is not a perfect number";
}
return 0;
}

Related

How Do I Code a Contact List Program in C++ Using Functions & Vectors?

I am trying to write a contact list program in the C++ programming language and I think I have a good base set up for one. The premise of the program is that two vectors of values are entered. One vector for the contact name and another for the phone number. Once a few of these values are taken in by the program, a single contact name is supposed to signify to the program that its corresponding phone number should be outputted.
(Note: The '3' is supposed to tell the program how many values are to be stored in each vector. In this case, it is 3 contact names and 3 phone numbers.)
Ex. Input: 3 Joe 123-5432 Linda 983-4123 Frank 867-5309 Frank
Ex. Output: 867-5309
But I am getting an error message that reads, "Exited with return code -11 (SIGSEGV)." I'm not sure where I could be leaking any memory but maybe I just can't see it.
Any help that can fix this error would be greatly appreciated.
Below is code that I have written so far:
#include <iostream>
#include <vector>
using namespace std;
string GetPhoneNumber(vector<string> nameVec, vector<string> phoneNumberVec, string contactName) {
string theName;
string thePhoneNum;
string theContName;
int N;
int nElements;
cin >> N;
cin >> theName;
cin >> thePhoneNum;
cin >> theName;
cin >> thePhoneNum;
cin >> theName;
cin >> thePhoneNum;
nameVec.push_back(theName);
phoneNumberVec.push_back(thePhoneNum);
cin >> contactName;
nElements = phoneNumberVec.size();
for (int i = 0; i < nElements; i++) {
if (i == N) {
return phoneNumberVec.at(i);
}
}
}
int main() {
vector<string> nameVec;
vector<string> phoneNumberVec;
string contactName;
cout << GetPhoneNumber(nameVec, phoneNumberVec, contactName) << endl;
return 0;
}
The issue is that you are supposed to return a std::string from GetPhoneNumber, but there are code paths where no return is specified.
What happens is that the program has now invoked undefined behavior, as returning no value from a function that's supposed to return a value leads to undefined behavior occurring.
The fix is to return a std::string from the GetPhoneNumber function from all code paths. Namely right here:
for (int i = 0; i < nElements; i++) {
if (i == N) {
return phoneNumberVec.at(i);
}
}
return ""; // or some appropriate string.
}
To prove that this is the issue, if you do not have that return statement, and instead did this:
for (int i = 0; i < nElements; i++) {
if (i == N) {
return phoneNumberVec.at(i);
}
}
std::cout << "There will be a problem" << std::endl;
}
You will see the string,
There will be a problem
outputted, proving you are reaching that point in the function without returning a value.
Here is a live example.
The other issue is that i could never equal N, since a std::vector uses 0-based indexing. If N is 1, then the highest index for i will be 0.
The fix is to compare i to N-1.

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;

How to Create a Linear Searching Algorithm easier than what my textbook provides [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need help on something. The textbook I am reading that teaches c++ does not do a good job at teaching students the linear searching algorithm. As a result I have tried recreating the algorithm without using any functions. The problem is, the code I have written seems to have some bugs. Just to note I am using the Microsoft Visual Studios 2013 IDE. As a result, can anyone please tell me what is wrong with my code? Here is the algorithm I have written in English. The Algorithm will not show the variable and array definitions but the source code will.
P.S. This is not a homework assignment. It is just for fun :)
P.S. For some reason the code formatting was very glitchy.
Algorithm:
Ask the user to enter a number
Create a for loop
Inside the for loop traverse through each element in the array and compare
it with the number the user inputted
If the element in the array is EQUAL to the number the user inputted, display a message saying it was found
If the element in the array is NOT EQUAL to the number the user inputted, display a message saying it WASN'T found.
code:
#include <iostream>
using namespace std;
int main()
{
// Create the array
int array[6] = {1,2,3,4,5,6};
int number;
// Ask the user to enter a number
cout << "Enter a number: ";
cin >> number;
// Create a for loop to traverse through each number in the array
//to see if it equals the user inputted number
for (int i = 0; i < 6; i++)
{
if (number == array[i])
{
cout << "Number Found: " << array[i] << endl;
}
else if (number != array[i])
{
cout << "Number Not Found!" << endl;
}
}
return 0;
}
The output if I entered 3 would be the following:
Number Not Found!
Number Not Found!
Number Found: 3
Number Not Found!
Number Not Found!
Number Not Found!
your logic output decision for each iteration. But it seems you've to output your decision only once.
So, for this reason declare a boolean variable globally and set false as a value of this value.
For each iteration check it is found. if found then set the boolean value to TRUE.
for Final output check global boolean value either true or false and print output
Remove the cout from inside the loop. Use a flag, ie if the number is found, set it to true and then write the print statement outside using an if.
int flag=0;
for(int i=0;i<6;i++){
if(number==arr[i])
flag=i+1;
}
if(flag) cout<<"found at position"<<flag;
else cout<<"Not found";
PS: Buy a better textbook
Easier and more fun:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number;
vector<int> nums{1,2,3,4,5,6};
cout << "Find a number: ";
cin >> number;
for_each(cbegin(nums), cend(nums),
[&](const int& x)
{
if(x == number)
cout << "found " << x << endl;
else
cout << "could not find " << endl;
});
}
But a good starting point for linear search would be:
template<typename I, typename T>
I find (I first, I last, const T& val)
{
while (first != last) {
if (*first == val) return first;
++first;
}
return last;
}

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

Making an if condition return if its true or while return if its true

When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value?
Here is what I want to implement:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
bool tr=true;
while(tr)
{
if(n!=5)
cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
else
tr=false;
}
return 0;
}
You need to prompt the user in the while loop, so that it occurs in each iteration:
int n;
bool tr = true;
while(tr)
{
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n!=5) {
cout << "You entered " << n;
} else {
tr = false;
}
}
Just put all your code (except 'n' and 'tr' definition) in while loop as follow:
int main()
{
int n;
bool tr=true;
while(tr)
{
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
if(n!=5)
cout<<"You entered "<<n;
else
tr=false;
}
return 0;
}
The other answers all work, and there is something to be learned about improving program flow from them, but I believe the trick you're asking for is the continue keyword, which skips the remainder of this iteration of the loop.
bool tr = true;
int n;
while (tr)
{
cout << "Enter numbers...";
cin >> n;
if (n != 5)
continue;
else
tr = false;
}
EDIT Part 1: On the continue keyword.
You want to make your code as readable as possible. In this example, its use is unnecessary (as the other posters have shown); but it is the answer to the question "How do I skip the rest of processing in this iteration of my loop and continue to the next iteration?". Usually, such flow-breaking directives actually make code harder to read; but sometimes the opposite is true. Anything (or, at least, almost anything) that can be accomplished with continue or break, can be accomplished without them, so if you're going to use them, you want to have a definite reason for doing so. Usually, when I use continue, it's because I'm looping through a collection of inputs and I want to skip processing the loop whenever the input isn't in the format I'm expecting. Something like this (pseudo-code)...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
{
cout << "Bad input";
continue;
}
// Do massive block of calculating here.
}
is easier to read than this...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
cout << "Bad input";
else
{
// Do massive block of calculating here.
}
}
because the second version makes it harder to track what scope you're in, if you're looking toward the end of the massive block of calculating. In this case, I gain code readability by continue, so I use it. But simple code probably shouldn't use it. The break keyword is similar, though it's a lot easier to come up with examples where break is beneficial.
EDIT Part 2: On multiple iterations
This is just an issue of setting up the loop; there are no magic keywords here. The shortest way I can come up with, is probably something like this:
int n = 0;
int numberToTake = 10;
for ( int numbersTaken = 0; numbersTaken < numberToTake; ++numbersTaken)
{
cout << "Enter numbers...";
int n = 0;
for (cin >> n; n != 5; cin >> n)
cout << "Try again.";
// Do whatever processing on n you want to do here.
}
Though I should point out that, doing it this way, the only value you will ever get from the user will be 5, and if he inputs anything that doesn't fit in an integer, you will get unexpected behavior.
EDIT 3: After reading the comment more thoroughly, I think you're just looking for is the more traditional use of the for loop.
No need for the exra bool variable.
The idiom can be: Infinitely loop until the user enters 5:
for(;;) { // Loops infinitely
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n == 5)
break; // Exits the loop
cout << "You entered " << n; // Before the if if you want to print 5 as well
}