How do I declare a variable in a if-else statement? - c++

I'm still a newbie at this and I really dont understand many things
THE ONLY THING THAT IS MISSING IS x=d/t and I don't know where to put it...
I already tried various methods but still can't figure out where to put it.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int d, t, s, z;
cout<<"Enter the distance of your destination:"<<endl;
cin >>d;
cout<<"Enter the time you want to get there:"<<endl;
cin >>t;
for (z=1; z<=5; z++)
{
cout<<"Enter your speed:"<<endl;
cin>>s;
if (int x=d/t && x>=s)
{
cout<<"Maintain your speed it is the appopriate speed: "<<s<<"mph"<<endl;
break;
}
else
{
cout<<"Go faster at this rate you won't get to your destination on time"<<endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
The Output always shows the if statement even though it should already show the else statement..
I really need help on this..

Just put it outside the if
int x = d / t;
if (x && x >= s)
or maybe you want this
int x = d / t;
if (x >= s)

This is the code:
int main(int argc, char *argv[])
{
int d, t, s, z;
cout<<"Enter the distance of your destination:"<<endl;
cin >>d;
cout<<"Enter the time you want to get there:"<<endl;
cin >>t;
for (z=1; z<=5; z++)
{
cout<<"Enter your speed:"<<endl;
cin>>s;
int x=d/t;
if (x>=s)
{
cout<<"Maintain your speed it is the appopriate speed: "<<s<<"mph"<<endl;
break;
}
else
{
cout<<"Go faster at this rate you won't get to your destination on time"<<endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}

Write instead:
int x=d/t;
if(x && x>=s)
{
// ...
to get the result exactly for what you have written.

You don't do that.
Use this if you want to do exactly what you've written:
int x = d/t;
if (x && x >= s)
{
...
}
but you probably really just wanted:
if(x >= s)

Try
int x = d/t;
if (x >= s) {
....
As per a book on C++

why declare x at all?
if(d/t>=s)

I guess your problem is that the input data (distance, time) should be double, not int. In C++, division of integers truncates, i.e., 2 / 3 == 0. Has thrown me off a couple of times... Integers are for counting, not for measurements.
And don't worry about writing some expression several times, current compilers are smart enough to notice and compute it once. In any case, write the simplest, clearest code possible. Only if that shows to be too slow (unlikely) does it really pay to go over the code to tighten it up. Your time writing the code, understanding what is really written when it misbehaves, and fixing it is more valuable than a few seconds of computer time.
Never forget Brian Kernighan's "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." Also Donald Knuth's "Premature optimization is the root of all evil".

Related

How to end program in a do-while (C++)

Here is my code. I am trying to get the entire program to end if it goes into the second if statement inside the do-while loop. But every time I run it, it crashes. I am not sure what I am doing wrong.
#include <iostream>
using namespace std;
int main() {
int myData[10];
for(int i=0;i<10;i++){
myData[i] = 1;
cout<<myData[i];
}
do{
int i;
cout<<endl<<"Input index: ";
cin>> i;
int v;
cout<<endl<<"Input value: ";
cin>>v;
if(i>=0||i<10){
myData[i]=v;
for(int i=0;i<10;i++){
cout<<myData[i]<<" ";
}
}
if (i<0||i>=10){
cout<<"Index out of range. Exit.";
return 0;
}
}while(1);
}
if(i>=0||i<10){
Think about which numbers are either greater than zero or less than ten. I'm sure you realise that is true of all numbers. What you meant to write is
if(i>=0&&i<10){
This explains your crash, you are accessing the myData array with an index that is outside the array bounds.
It's very common for beginners to get && and || confused especially where there is negation involved as well.
Other people have told you the problem:
if(i>=0||i<10){
I'm going to explain why you hit this. You hit it because you didn't use any whitespace.
if (i >= 0 && i < 10) {
Please, please, please, for all that is good in the world, use whitespace liberally. You absolutely will have fewer bugs, because my version is far easier to read. Furthermore if you work with older developers (like me) we can actually read your code far more easily.

i'm getting an error in for loop and if statements:

#include <iostream>
using namespace std;
int main() {
int i,t,km,sum=0;
std::cin >> t;
for( i=0;i<t;i++){
cin>>km;
}
for(i=0;i<t;i++){
if(km>300){
sum=km*10;
cout<<sum;
}
else if(km<=300){
sum=300*10;
cout<<sum;
}
else{
cout<<"wrong!";
}
}
return 0;
}
i'm not getting what's wrong with the code, when i'm entering number of test cases(t) as 1 it's running. but afterwars it's only executing the else block.
We'll start with a mini code review:
#include <iostream>
using namespace std; // Bad practice; avoid
/* Generally poor formatting throughout */
int main() {
int i,t,km,sum=0; // Prefer each variable declared on its own line; i is unnecessary
std::cin >> t;
for( i=0;i<t;i++){ // Overwrites `km` t times
cin>>km;
}
for(i=0;i<t;i++){ // Only does work on the last number entered
if(km>300){
sum=km*10; // You likely want to be adding on, not overwriting
cout<<sum;
}
else if(km<=300){
sum=300*10;
cout<<sum;
}
else{ // Impossible to reach given your two other conditions
cout<<"wrong!";
}
}
return 0;
}
The comments have spelled a lot of this out. You overwrite km t times. You only end up running your check on the last value of km that was entered, t times. You likely want to process t inputs, and the way to do this is with a single loop instead of the two that you have.
You overwrite your sum instead of (I assume) adding on to it. You wanted to sum += and not just sum =. The computer is actually pretty dumb, but it's very good at doing exactly what you told it to do. It is incapable of guessing your intent. That's supposed to be comforting, but it can be interpreted many ways.
I would also recommend taking the time to come up with better variable names. It looks like you're doing some calculations, possibly having to do with legs of a trip, but it's unclear. Making your code harder to read by choosing horrible names like t won't allow others to easily help you, and it will make your own code seem like a foreign language after just a couple days. Help yourself and others out by choosing good names.
As I stated, you might have been able to figure this out on your own if the code was indented properly. Consistent and proper formatting is extremely important for readability. If you don't want to be bothered doing it yourself, tools like clang-format exist.
Here's your code again, touched up a bit. I took a couple guesses at intended behavior.
#include <iostream>
int main() {
int t;
int km;
int sum = 0;
std::cin >> t;
for (int i = 0; i < t; i++) {
std::cin >> km;
if (km > 300) {
sum += km * 10;
std::cout << sum << '\n';
} else if (km <= 300 && km > 0) {
sum += 300 * 10;
std::cout << sum << '\n';
} else {
std::cout << "wrong!";
}
}
return 0;
}

Reducing time in the following code

I gave this solution at the codechef for the problem code : FCTRL.
I saw the compile time of others people using the same the language c ( i am using c++ gcc 4.8.1) is somewhat less,
mine is 0.46s while their is 0.23
Can somebody help me in reducing the time if possible?
#include<iostream>
using namespace std;
int main()
{
long int t,i,temp;
cin>>t;
long int n[t],a[t];
for(i=0;i<t;i++)
{
temp=1;
a[i]=0;
cin>>n[i];
while(temp)
{
temp=n[i]/5;
a[i]+=temp;
n[i]=n[i]/5;
}
}
for(i=0;i<t;i++)
cout<<a[i]<<"\n";
return(0);
}
From your description, as you are using c++ and they are using c, it might be due to how the compiler handles each instruction.
Also you may try replacing
temp=n[i]/5;
a[i]+=temp;
n[i]=n[i]/5;
By
temp=n[i]/5;
a[i]+=temp;
n[i]=temp; //why compute the value again
And see if some time reduces or not
You worst offense to C++ is using Variadic-Length arrays, those are non-standards.
And in fact, it turns out you absolutely do not need them. This problem can be solved on a line-per-line basis so using arrays to hold the input and output is useless.
Here is your program, simplified. I also noted that temp was useless within the loop (though it was likely optimized out anyway, it polluted the code).
#include <iostream>
int main()
{
size_t number = 0;
std::cin >> number;
for(size_t i = 0 ; i < number; ++i)
{
size_t a = 0, n = 0;
std::cin >> n;
while (n)
{
n /= 5;
a += n;
}
std::cout << a << '\n';
}
}
Is it possible to do better ? Oh yes! The main issues here is that the C++ streams are none too fast so you may get a good boost by switching to the C reading methods... however they are not as nice (and safe).

which is a better approach for fibonacci series generation

The two general approaches for Fibonacci series generation are:
The traditional approach, i.e., running through a for loop inside a function.
Recursion
I came across another solution
#include <iostream>
using namespace std;
void fibo() {
static int y = 0;
static int x = 1;
cout << y << endl;
y = x + y;
x = y - x;
}
int main() {
for (int i = 1; i <= 1; i++) {
fibo();
}
return 0;
}
This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?
I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?
Disadvantages I can immediately see:
By essentially making the state global, it's not thread-safe
You can only ever run through the sequence once, as there's no way to reset
I would favour an approach which keeps the state within an object which you can ask for the next value of - an iterator, basically. (I've never been certain how easily the Fibonacci sequence maps to C++ iterators; it works fine with C# and Java IEnumerable<T> and Iterable<T> though.)
The solution you found is decent for when you need to store the state (for example, when you calculate a Fibonacci number, do something based on it, and then calculate another), but using this from two places in your code will likely give funny results. This is because the static variables will always be the same, no matter from where you call it. I would instead suggest:
class FiboNumbers {
public:
FiboNumbers() :
x_(1), y_() {}
int getNext() {
x_ += y_;
y_ = x_ - y_;
return x_;
}
private:
int x_, y_;
};
This offers the same keeping-of-state, but allows you to create multiple instances of the class, therefore allowing you to have different parts of the code that calculate their own Fibonacci series.
Minor note: the code I posted will produce the same series as the example you posted, but it will produce the real Fibonacci sequence, which starts with 0 1 1 2...
I am a C++ student (1.5 months into it).
Give feedback to this different way I have thought of for Fibonacci series.
#include<iostream>
using namespace std;
void fibseries(long int n)
{
double x=0;double y=1;
for (long int i=1;i<=n;i++)
{
if(i%2==1)
{
cout<<x<<" ";
x=x+y;
}
else
{
cout<<y<<" ";
y=x+y;
}
}
}
main()
{
long int n=0;
cout<<"The number of terms ";
cin>>n;
fibseries(n);
return 0;
}
I'm not sure what this function is really supposed to do. It
only works in the exact loop you present, and as others have
pointed out, it only works once. (And there's probably a typo
in your loop, since your complete program outputs "0", and
nothing else.) What advantage does it offer over:
int y = 0;
int x = 1;
for ( int i = 0; i < count; ++ i ) {
std::cout << y <<std::endl;
y = x + y;
x = y - x;
}
? It's more complex, far less robust, and far less useful.
As was said before, the advantage of the static variables is, in principle, that it's cheaper to calculate the n -th Element of a sequence where the n - 1 -th has already been evaluated.
The big drawback, apart from the problems inherent to static variables, is that you don't have any way to get back to an earlier point in the sequence, nor do you really have a good control over where in the sequence you are at a given time.
Using a class, as recommended by Sevis, is certainly the better way of implementing such a static-like approach: this makes everything safer, gives you an easy way to get back to the sequence start (by simply reinitializing the object) and also makes it possible to implement further functionality, like going back k steps, looking up the present position, etc..
I think this pointer approach would be more useful for you.
void main()
{
int i,p, *no,factorial,summ;
int fib(int p);
clrscr();
printf("\n Enter The Number:");
scanf("%d", no);
printf("\n The Fibonnacci series: \n");
for(i=0; i < *no; i++)
printf("%d\n", fib(i));
getch();
}
int fib(int p)
{
if(p == 0)
return(0);
if(p >= 1 && p <= 2)
return(1);
else
return(fib(p - 1) + fib(p - 2));
}

Prime numbers program

I'm currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which required me to read in a number from a given txt file. This number would be N. Now I'm suppose to find the Nth prime number for N <= 10 000. After I find it, I'm suppose to print it out to another txt file. Now for most parts of the question I'm able to understand and devise a method to get N. The problem is that I'm using an array to save previously found prime numbers so as to use them to check against future numbers. Even when my array was size 100, as long as the input integer was roughly < 15, the program crashes.
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main() {
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime;
trial >> prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[100], b, c, e;
bool check;
b = 0;
switch (prime) {
case 1:
{
write << 2 << endl;
break;
}
case 2:
{
write << 3 << endl;
break;
}
case 3:
{
write << 5 << endl;
break;
}
case 4:
{
write << 7 << endl;
break;
}
default:
{
for (int a = 10; a <= 1000000; a++) {
check = false;
if (((a % 2) != 0) && ((a % 3) != 0) && ((a % 5) != 0) && ((a % 7) != 0)) // first filter
{
for (int d = 0; d <= b; d++) {
c = num[d];
if ((a % c) == 0) {
check = true; // second filter based on previous recorded primes in array
break;
}
}
if (!check) {
e = a;
if (b <= 100) {
num[b] = a;
}
b = b + 1;
}
}
if ((b) == (prime - 4)) {
write << e << endl;
break;
}
}
}
}
trial.close();
write.close();
return 0;
}
I did this entirely base on my dummies guide and myself so do forgive some code inefficiency and general newbie-ness of my algorithm.
Also for up to 15 it displays the prime numbers correctly.
Could anyone tell me how I should go about improving this current code? I'm thinking of using a txt file in place of the array. Is that possible? Any help is appreciated.
Since your question is about programming rather than math, I will try to keep my answer that way too.
The first glance of your code makes me wonder what on earth you are doing here... If you read the answers, you will realize that some of them didn't bother to understand your code, and some just dump your code to a debugger and see what's going on. Is it that we are that impatient? Or is it simply that your code is too difficult to understand for a relatively easy problem?
To improve your code, try ask yourself some questions:
What are a, b, c, etc? Wouldn't it better to give more meaningful names?
What exactly is your algorithm? Can you write down a clearly written paragraph in English about what you are doing (in an exact way)? Can you modify the paragraph into a series of steps that you can mentally carry out on any input and can be sure that it is correct?
Are all steps necessary? Can we combine or even eliminate some of them?
What are the steps that are easy to express in English but require, say, more than 10 lines in C/C++?
Does your list of steps have any structures? Loops? Big (probably repeated) chunks that can be put as a single step with sub-steps?
After you have going through the questions, you will probably have a clearly laid out pseudo-code that solves the problem, which is easy to explain and understand. After that you can implement your pseudo-code in C/C++, or, in fact, any general purpose language.
There are a two approaches to testing for primality you might want to consider:
The problem domain is small enough that just looping over the numbers until you find the Nth prime would probably be an acceptable solution and take less than a few milliseconds to complete. There are a number of simple optimizations you can make to this approach for example you only need to test to see if it's divisible by 2 once and then you only have to check against the odd numbers and you only have to check numbers less than or equal to the aquare root of the number being tested.
The Sieve of Eratosthenes is very effective and easy to implement and incredibly light on the math end of things.
As for why you code is crashing I suspect changing the line that reads
for( int d=0; d<=b; d++)
to
for( int d=0; d<b; d++)
will fix the problem because you are trying to read from a potentially uninitialized element of the array which probably contains garbage.
I haven't looked at your code, but your array must be large enough to contain all the values you will store in it. 100 certainly isn't going to be enough for most input for this problem.
E.g. this code..
int someArray[100];
someArray[150] = 10;
Writes to a location large than the array (150 > 100). This is known as a memory overwrite. Depending on what happened to be at that memory location your program may crash immediately, later, or never at all.
A good practice when using arrays is to assert in someway that the element you are writing to is within the bounds of the array. Or use an array-type class that performs this checking.
For your problem the easiest approach would be to use the STL vector class. While you must add elements (vector::push_back()) you can later access elements using the array operator []. Vector will also give you the best iterative performance.
Here's some sample code of adding the numbers 0-100 to a vector and then printing them. Note in the second loop we use the count of items stored in the vector.
#include <vector> // std::vector
...
const int MAX_ITEMS = 100;
std::vector<int> intVector;
intVector.reserve(MAX_ITEMS); // allocates all memory up-front
// add items
for (int i = 0; i < MAX_ITEMS; i++)
{
intVector.push_back(i); // this is how you add a value to a vector;
}
// print them
for (int i = 0; i < intVector.size(); i++)
{
int elem = intVector[i]; // this access the item at index 'i'
printf("element %d is %d\n", i, elem);
}
I'm trying to improve my functional programming at the moment so I just coded up the sieve quickly. I figure I'll post it here. If you're still learning, you might find it interesting, too.
#include <iostream>
#include <list>
#include <math.h>
#include <functional>
#include <algorithm>
using namespace std;
class is_multiple : public binary_function<int, int, bool>
{
public:
bool operator()(int value, int test) const
{
if(value == test) // do not remove the first value
return false;
else
return (value % test) == 0;
}
};
int main()
{
list<int> numbersToTest;
int input = 500;
// add all numbers to list
for(int x = 1; x < input; x++)
numbersToTest.push_back(x);
// starting at 2 go through the list and remove all multiples until you reach the squareroot
// of the last element in the list
for(list<int>::iterator itr = ++numbersToTest.begin(); *itr < sqrt((float) input); itr++)
{
int tmp = *itr;
numbersToTest.remove_if(bind2nd(is_multiple(), *itr));
itr = find(numbersToTest.begin(), numbersToTest.end(), tmp); //remove_if invalidates iterator
// so find it again. kind of ugly
}
// output primes
for(list<int>::iterator itr = numbersToTest.begin(); itr != --numbersToTest.end(); itr++)
cout << *itr << "\t";
system("PAUSE");
return 0;
}
Any advice on how to improve this would be welcome by the way.
Here is my code. When working on a big number, it's very slow!
It can calculate all prime numbers with in the number you input!
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
int m;
int n=0;
char ch;
fstream fp;
cout<<"What prime numbers do you want get within? ";
if((cin>>m)==0)
{
cout<<"Bad input! Please try again!\n";
return 1;
}
if(m<2)
{
cout<<"There are no prime numbers within "<<m<<endl;
return 0;
}
else if(m==2)
{
fp.open("prime.txt",ios::in|ios::out|ios::trunc);//create a file can be writen and read. If the file exist, it will be overwriten.
fp<<"There are only 1 prime number within 2.\n";
fp<<"2\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
else
{
int j;
int sq;
fp.open("prime.txt",ios::in|ios::out|ios::trunc);
fp<<"2\t\t";
n++;
for(int i=3;i<=m;i+=2)
{
sq=static_cast<int>(sqrt(i))+1;
fp.seekg(0,ios::beg);
fp>>j;
for(;j<sq;)
{
if(i%j==0)
{
break;
}
else
{
if((fp>>j)==NULL)
{
j=3;
}
}
}
if(j>=sq)
{
fp.seekg(0,ios::end);
fp<<i<<"\t\t";
n++;
if(n%4==0)
fp<<'\n';
}
}
fp.seekg(0,ios::end);
fp<<"\nThere are "<<n<<" prime number within "<<m<<".\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
}
For one, you'd have less code (which is always a good thing!) if you didn't have special cases for 3, 5 and 7.
Also, you can avoid the special case for 2 if you just set num[b] = 2 and only test for divisibility by things in your array.
It looks like as you go around the main for() loop, the value of b increases.
Then, this results in a crash because you access memory off the end of your array:
for (int d = 0; d <= b; d++) {
c = num[d];
I think you need to get the algorithm clearer in your head and then approach the code again.
Running your code through a debugger, I've found that it crashes with a floating point exception at "if ((a % c) == 0)". The reason for this is that you haven't initialized anything in num, so you're doing "a % 0".
From what I know, in C/C++ int is a 16bit type so you cannot fit 1 million in it (limit is 2^16=32k). Try and declare "a" as long
I think the C standard says that int is at least as large as short and at most as large as long.
In practice int is 4 bytes, so it can hold numbers between -2^31 and 2^31-1.
Since this is for pedagogical purposes, I would suggest implementing the Sieve of Eratosthenes.
This should also be of interest to you: http://en.wikipedia.org/wiki/Primality_test
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false; // Basically the idea for this for loop is to run checks against integers. This is the main for loop in this program. I re initialize check to false ( check is a bool declared above this. )
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++) // This for loop is used for checking the currentInt against previously found primes which are stored in the num array.
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;} // this is the check. I check the number against every stored value in the num array. If it's divisible by any of them, then bool check is set to true.
if ( currentInt == 2)
{ check = false; } // since i preset num[0] = 2 i make an exception for the number 2.
if (!check)
{
e=a;
if(currentPrime <= 100){
num[currentPrime]= currentInt;} // This if uses check to see if the currentInt is a prime.
currentPrime = currentPrime+1;} // increases the value of currentPrime ( previously b ) by one if !check.
if(currentPrime==prime)
{
write<<e<<endl;
break;} // if currentPrime == prime then write the currentInt into a txt file and break loop, ending the program.
Thanks for the advice polythinker =)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime, e;
trial>>prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[10000], currentPrime, c, primePrint;
bool check;
currentPrime=0;
num[currentPrime] = 2;
currentPrime=1;
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false;
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++)
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;}
}
if (!check)
{ e=currentInt;
if( currentInt!= 2 ) {
num[currentPrime]= currentInt;}
currentPrime = currentPrime+1;}
if(currentPrime==prime)
{
write<<e<<endl;
break;}
}
trial.close();
write.close();
return 0;
}
This is the finalized version base on my original code. It works perfectly and if you want to increase the range of prime numbers simply increase the array number. Thanks for the help =)
Since you will need larger prime number values for later questions, I suggest you follow dreeves advice, and do a sieve. It is a very useful arrow to have in your quiver.