It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I am having trouble forming the output statement for this program. The correct output should print the same input number that its numerical value holds. .
It looks like you want something similar to this:
#include <iostream>
using namespace std;
int main()
{
int standard, count1, count2, count3, count4, count5;
// Initialize your int's
standard = count1 = count2 = count3 = count4 = count5 = 0;
do {
cout<< "Enter value: ";
cin >> standard;
// Switch through your cases
switch(standard)
{
case 1:
count1++;
break;
case 2:
count2++;
break;
case 3:
count3++;
break;
case 4:
count4++;
break;
case 5:
count5++;
break;
}
} while(standard != 0);
// Do this type of loop for all your count vars
for(int i=0;i<count1;++i)
cout<< "1";
for(int i=0;i<count2;++i)
cout<< "2";
// And so on...
return 0;
}
For the for loops, note that you are going from 0 to < the total number. If you went to <= you would go passed that number. The range [0,4] = 5 (or in our case [0,5) for the set of integers) and so does [1,5] so remember to mind your offsets. Good luck!
EDIT: Also recognize that the position of the switch statement has been moved. By placing it in the loop, you actually count every time it runs through the loop. For instance, the loop "blocks" (in other words, it waits for input) at your cin line. When it receives an input (though you have no error-checking, so a non-int value may cause a segfault), it will then check it against the switch statement and increment accordingly.
By placing the switch statement outside the loop (as you initially had it), please realize that nothing happens. You have no default condition in your switch statement, nor a case for handling 0. If you check your switch after the loop, standard == 0 since that is how you exited the loop in the first place (therefore, standard's last value will be retained).
Furthermore, revisit the for loop syntax. This can be done in several ways, there are many good articles here on SO which can help you further by using the search function, but it basically works like this:
for(STARTING_POINT;SOME_CONDITION;SOME_CHANGE);
STARTING_POINT = The value where you should start your loop
SOME_CONDITION = When this condition is true, then the loop will terminate
SOME_CHANGE = how to change your variable (i.e. from starting point) until it reaches the condition
So a loop which looks like this:
for(int i=1;i<=5;++i){ ... }
means to initialize int i to value 1
Until i <= 5 run through your loop
Then, on every iteration, increment i by one (which is ++i or i++)
Finally, as you can see, I added an initialization line to my int's. What this does is it gives your variables some starting value rather than garbage value.
I hope this helps
Regards,
Dennis M.
You definitely need to move the switch statement within the while loop (Edit: this was based on the OP's initial posting of the code).
I really don't understand what you're trying to accomplish, but this part here:
for (count1=0; count1<=5; count1++)
cout << "1";
Is going to print out '1' 6 times in a row, regardless of the input. Could you explain a bit more what you're trying to do?
Here's my interpretation: You want to input a sequence of numbers (ending with zero), then output those exact same numbers, using loops.
Here's some pseudocode to give you a hint.
Declare an array of int's large enough to hold all your input numbers.
Declare a counter c = 0.
Begin loop while input is not 0
Input number from user and store it in array[c].
Increment counter c.
End loop
Begin loop i from 0 to c-1
Output number that is in array[i].
End loop
No need to use a switch statement and a counter for each possible number. Just store each input in it's own spot in an array.
Related
I am currently learning C++ at my school, and am making a word sleuth as part of a project that I have to submit. For this, I have already made the grid of alphabets and other necessary things (clues, rules, etc.). I am taking the input in the form of coordinates in an integer array whereby the user enters 4 values in the array, signifying the initial row and column number and the final row and column number, corresponding to which are the first and last alphabets of a particular word.
After doing this, I am now comparing the array input by the user with the array I have already defined that has the coordinates of that particular word. This is shown here :
cout<<"Enter the coordinates of starting and final characters : row1 col1 row2 col2 "<<endl;
for (z = 0; z < 4; z++) //first for loop
cin>>p[z]; //taking the input as an array 'p'
for (b = 0; b < 4; b++) //second for loop
{
if (p[b] == messi[b])
b+=0;
}
if (b == 4)
cout<<"Great!!!! You have answered the question correctly"<<"\n\n";
else
cout<<"You got this one wrong mate! Try again :)"<<"\n\n";
Here, messi[b] is the array which has the coordinates corresponding to the word 'MESSI' in the grid. Now, to my mind, the 'if' statement after the second for loop must contain the condition to check if b = 3. However, when I do that, the output always comes out to be what the 'else' statement says i.e. "You got this..." for every input. However, when I impose the condition to check if b = 4, the output comes out to be what the 'if' statement says i.e. "Great!!..." for every input.
What wrong am I doing? I hope I am clear enough in explaining the problem to you. I am using CodeBlocks 16.01.
It's a bit unclear what you are doing, as the program stands, b will always be equal to 4 after the second for-loop since the last time to condition was true, b < 4. So after the increment, it will be 4.
Inside the second for-loop you also have the NOP code b += 0; which does absolutely nothing to the code. What is the intention here?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
there is a program written below. I am not understanding that how does it reverse an char array. I mean it works fine, it does reverse the string which is stored in char array by user, but I want to know how does it work and how does it reverse the order? Basically I am not understanding the first for loop, it does not have any statements in the body plus the first part of the for loop is missing. Please explain in simple and easy words, not in typical or difficult words. I am not a native English speaker. Thanks a lot.
#include <iostream>
using namespace std;
int main()
{
char name[99];
int counter=0;
cin >> name;
for(;name[counter]!='\0'; counter++)
{}
cout << "\nName: ";
for (;counter > 0; counter--)
{
cout << name[counter-1];
}
}
C strings are null ('\0') terminated. The first loop increments counter until the end of the string contained in name is found. That is indicated by the null character. The important part is that counter is declared outside of the first for loop and it stays in scope, and with the same value, when the second loop is executed. The second loop then starts at the end of the string in name printing the characters until the it prints the first character.
In Your Program, First For loop is to know number of characters in name variable.
Let me explain you how it works.
For loop have basic structure like
for(i=10;i>0;i--)
{
//Body part of for
}
First part i=0 is initialization, second part is condition and third part is Increment/Decrements. In your program, We have already initialize value of counter as 0. This loop is just for counting number of characters so after every loop count variable will increment. We do not need to write anything in body part.
after completing first for loop count variable have same value as name variable's characters.
Again in second loop we don't need to initialize count values because count already have some value stored in it.
Hope You understand now..!!
you start your counter at 0.
for(;name[counter]!='\0'; counter++){}
the for loop above increments the counter until it reaches '\0' .At this point your counter has incremented to the number of characters of what you typed as name. eg: if you typed hello counter is now at 5.
for (;counter > 0; counter--){cout << name[counter-1];
}
In the above for loop,you start by having the counter value at 5 then printing out each character of your array in reverse because first iteration your counter is 5, you print name[4] which is o then counter decrements so you print name[3]=l,then name[2]=l,
then name[1]=e , then name[0] =h. Note: if your counter is at value n you are printing n-1. so when your counter decrements to 1 you print name[0]. then the counter finally decrements to 0 where the loop becomes false. Also you are not reversing the array elements themselves but are just printing them in reverse.
#include <iostream>
using namespace std;
int main()
{
char name[99];
int counter=0; // variable to store the number of characters in name.
cin >> name;
// the for loop is counting each letter until the end of the string, storing the result in counter.
for(;name[counter]!='\0'; counter++)
{}
cout << "\nName: ";
// if the name you entered was "Billy" counter would = 5
for (;counter > 0; counter--)
{
// since counter = 5 counter subtracts 1 to get to the "5th" spot in the array which is when counter = 4
// name[0] = B
// name[1] = i
// name[2] = l
// name[3] = l
// name[4] = y
// now starting from position 4 in the array counter-- subtracts 1
// from counter each time it runs through the loop to get to each previous letter.
cout << name[counter-1];
}
}
I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.
Hi Im trying to translate this code to TI-BASIC. Im having problems with how to change for loop into while loop and also with incrementing a number in TI-BASIC.
#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
You can efficiently use a While loop in this situation:
Input "NUMBER: ",A
1->B
3->I
√(A->D
If not(fPart(A/2
DelVar BWhile I<=D and B
fPart(A/I->B
I+2->I
End
If not(B
Disp "NOT
Disp "PRIME
In TI-Basic a While loop works as you would expect and you can have conditions for it.
Incrementing a number is as simple as saying
X+i->X
Where 'i' is the incrementer.
To change a For loop into a While loop, you'll have to set up the While loop to constantly check to see if the number and increment have passed the upper bound while increasing the increment each run through.
If you wanted to mimic i++ or ++i in TI-Basic (Using a While loop), all you would have to change would be the arrangement of the code. Please note that TI-Basic For statements always operates under ++i.
Example (i++):
0->X
While X<10
Disp X
X+1->X
End
This will display (With each number on a new line)
0 1 2 3 4 5 6 7 8 9
Example (++i):
0->X
While X<10
X+1->X
Disp X
End
This will display (With each number on a new line)
1 2 3 4 5 6 7 8 9 10
Let it be noted that TI-Basic For statements are much much faster than While loops when it comes to incrementing and should almost always be considered superior for the task.
Integrating Timtech's idea to skip even numbers effectively halves the required time to check the primality of the number with the addition of only a few extra lines.
I expanded the idea to skip multiples of two and multiples of three.
Input "Number:",X:abs(X->X
0
If not(fPart(X/2)) or not(fPart(X/3:Return
For(B,5,sqrt(X),6)
If not(fPart(X/B)) or not(fPart((X+2)/B:Return
End
1
Test Number: 1003001
Time Required: ~4 Seconds (So much better than 15 :D)
Size: 65 Bytes
I dont see why you would want to use a while loop as ti-basic has for loops:
0->F
Input "ENTER NUMBER:",N
For(I,2,int(N/2
If N/I=int(N/I
Then
int(N/2->I
1->F
End
End
If F
Then
Disp "NUMBER IS PRIME
Else
Disp "NUMBER IS NOT PRIME
End
N/I=int(N/I is a way to check for a number's remainder (another way of saying N%I==0 but ti basic does not have modulus). Another trick here is setting I to its maximum bound (int(N/2) as a sort of "break" like other languages would have
I am writing a C++ program that prompts the user for an input and then keeps track of how many times that input is entered. I am currently using a do-while loop and a switch statement. The part I am having trouble with is the switch statement. I can't figure out how to keep track of how many times an input is entered. For example:
Enter Value: 4
Enter Value: 4
Enter Value: 4
Enter Value: 3
Enter Value: 3
// I then want the program to be able to know and then eventually output, how many times the number '4' and '3' were entered.
I thinking possibly using some sort of increment counting form, but not 100% sure.
Thanks!
You'll probably want to use a std::map<int,int>. Here's why.
Let's look at alternatives, starting with the obvious:
int count0;
int count1;
int count2;
int count3;
int count4;
...
switch(input) {
case 0: ++count0; break;
case 1: ++count1; break;
case 2: ++count2; break;
case 3: ++count3; break
case 4: ++count4; break;
}
This does what you ask: you evaluate the input, and keep track of the number of times that specific input has been seen. This form does suffer from many problems:
It requires one line of source code for each alternative. This becomes a problem when the user can enter any value, say, from 0 to 10,000!
It has duplicate, virtually identical lines.
It has many variables, each of which has to be entered independently, but uses identically.
We can reduce the variable count by specifing an array:
int count[5];
...
switch(input) {
case 0: ++count[0]; break;
case 1: ++count[1]; break;
case 2: ++count[2]; break;
case 3: ++count[3]; break;
case 4: ++count[4]; break;
}
This still suffers from too many almost-but-not-quite identical lines of code. Let's try to get rid of the switch statement:
int count[5];
...
++count[input];
Ah, now we are getting somewhere! By eliminating the switch statement, we have one easily-maintained line of code. But what if the user (accidentally or maliciously) enters a 6? Then we will increment count[6], which does not exist. This is a Bad Thing. We could increase the size of the array:
int count[50000];
...
++count[input];
Now we are safe from the user. If he enters a 6, the Bad Thing no longer happens. Uh-oh, what about if the user enters 51000? We will increment count[51000] which does not exist. It should be obvious that we can't win this game -- for any number we choose, the user might choose that number plus 1.
Even if we could win, we'd still lose. If we are only asking the user to enter a few numbers, then we will have wasted the other 49,997 entries in the arary.
Fortunately C++ has a data structure that we can use which:
can take arbitrary numbers as its range, and
is space-efficient (compared to a large wasted array).
That data structure is called a map:
std::map<int,int> count;
...
++count[input];
A map is sort of like an array, but grows itself in a special way. Only the entries that we use are ever allocated, and every entry that we use is automatically allocated.
std::map<int, int> frequency;
int value_entered_by_user = f();
frequency[value_entered_by_user]++;
If your range of input values is limited, you can use an array. Each element of the array represents an input value. Initialize the elements to 0 at the beginning and increment the appropriate element when its corresponding input value is entered.