I'm having problem with displaying the sentence array outside of for loop
int example(string sentence)
{
int i = 0;
for (i; 1 < 50; i++)
{
cout<<sentence[i]<<endl;
}
cout<<sentence[i]<<endl;
return 0;
}
outside of for loop, sentence[i] isn't showing the character at sentence[49]
can someone tell me the reason?
Try this
int example(string sentence)
{
int i = 0;
for ( ; i < 50; i++)
{
cout<<sentence[i]<<endl;
}
cout<<sentence[i]<<endl;
}
You want to check if i is less than 50, not if 1 is less than 50, because that would always be true and the loop never terminates. Also, in the snippet I posted, i will have the value of 50 after the loop, so there better be a 51st element (0-based array).
The reason that it isn't displaying sentence[49] is that i is 50 after the loop runs. The i++ in your loop increments i after the loop iteration has run. So when i is 49 it will run through the loop and and then increment i to 50. Then it comes around to the conditional i < 50 and it sees that i is now 50 and the loop terminates. Then when you call sentence[i] outside of the loop it is trying to display sentence[50]. To get at the last character in sentence I would suggest one of the following:
cout << sentence[i - 1] << endl;
or the much easier to read:
cout << sentence.back() << endl;
Related
so I made a simple loop that finds out if an array has the elements with the values of 0 and 1.
if the loop indeed finds 0 or 1 inside of the array, it will say "YES", otherwise "NO".
yes, the program works just fine, but at the end of the program it prints out "YES" or "NO" as many times as i put cin>>dim to.
for example if dim which means (dimension[of the array]) is 5 it's going to print either "YESYESYESYESYES" or "NONONONONO"
I have to use return 0 in order to make it print it out like once, but I feel like this is not the right way to do it. Please help me with this. thanks!
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, dim, v[100];
cin>>dim;
for(i=0;i<dim;i++)
cin>>v[i];
for(i=0;i<dim;i++)
if(v[i]==0 || v[i]==1){
cout<<"YES"; return 0;}
else{
cout<<"NO"; return 0;}
return 0;
}
The break statement can be used to break out of loops. The example from cppreference:
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 5; k++) { //only this loop is affected by break
if (k == 2) break;
std::cout << j << k << " ";
}
}
As the comment suggests, break only breaks the innermost loop.
In your code you always exit from the loop on the very first iteration, hence you do not need the loop in the first place. This will have the same output as your code:
int main() {
int i, dim, v[100];
cin >> dim;
for(i=0; i < dim; i++)
cin >> v[i];
if(v[0] == 0 || v[0] == 1) {
cout << "YES";
} else {
cout << "NO";
}
}
After reading the question again...
I made a simple loop that finds out if an array has the elements with the values of 0 and 1
If you exit the loop after checking the first element then you only check the first element. If you want to see if an array contains only 1 or 0 or it contains at least one element which is 0 or 1 (not 100% clear which one you want), then you rather need this:
bool only_zero_or_one = true;
bool one_zero_or_one = false;
for (int i = 0; i < dim; ++i) {
zero_or_one = ( v[i] == 0 | v[i] == 1);
only_zero_or_one = zero_or_one && only_zero_or_one;
one_zero_or_one = zero_or_one || one_zero_or_one;
}
Only for one_zero_or_one you can break the loop once zero_or_one == true.
Moreover, you should rather use a std::vector. In your code, if the user enters a dim which is greater than 100 you write beyond the bounds of v. This can be avoided easily:
size_t dim;
std::cin >> dim;
// construct vector with dim elements
std::vector v(dim);
// read elements
for (size_t i=0; i < v.size(); ++i) std::cin >> v[i];
// .. or use range based for loop
for (auto& e : v) std::cin >> e;
but I feel like this is not the right way to do it
Returning is an entirely right way to break out from a loop.
Another right way is the break statement, which jumps to after the loop.
Even better, you can actually check if v[i]==0 or 1 inside the input for loop immediately after taking input and set a flag to true. Depending on requirement, you can either break or wait until the entire input is read and then come out and check for flag==true and then print "YES" and print "NO" if flag==false.
This will save you running the loop again to check for 0 or 1.
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:
Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.
I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!
int main() {
for (int i=2; i <=10; i++){
for (int j=2; j<=i; j++){
if (i%j==0 && j!=i) {
break;
}
else {
cout<< i <<endl;
break;
}
}
}
}
In addition to Sumit Jindal's answer inner for loop can be done by this way as well:
for(int j=2; j*j<=i ; j++)
If we think about every (x,y) ordered pair that satisfies x*y = i, maximum value of x can be square root of i.
The problem lies in the if-else branch. Your inner loop will be run exactly once because it will break out of the inner loop as a result of your if else branch.
When you first enter the inner loop the value of j is 2. Your condition will test if variable i is divisible by 2. If it is it breaks. Other wise (your else branch) will print the value of i and breaks out.
Hence printing odd numbers.
Break out of the inner loop and check whether j equals i in outer loop. You have to make j available for outer loop.
Your print statement is within the inner loop, and it should not be - it's only a prime if you run all the way through the inner loop without finding a divisor.
As a second point, you only need to check for divisors up to the square root of i, not all the way up to i.
You are breaking the inner loop after the first iteration itself, which is checking if the number(ie i) is different from j and is divisible by 2 or not (since j=2 for the first iteration)
I am getting 2,3,5,7,9 as my output
This is because every odd number fails the if and is printed in else condition
A minor correction in your code, adding a flag. Also you don't need to run the inner loop i times, infact only i/2 times is sufficient. This is simple mathematics, but will save significant number of CPU cycles (~5000 iterations lesser in your case)
#include <iostream>
int main()
{
int n = 10;
for(int i=2; i<=n; i++){
bool isPrime = true;
for(int j=2; j<=i/2; j++){
if(i!=j && i%j==0){
isPrime = false;
break;
}
}
if(isPrime)
std::cout << i << " ";
}
return 0;
}
Another version, if you don't mind output in reverse order.
int n = 10;
for (int i = n; i > 1; --i)
{
int factorCount = 0;
for (int j = 2; j <= n; ++j)
{
if (i % j == 0)
factorCount++;
if (factorCount > 1)
break;
}
if (factorCount == 1)
cout << i << endl;
}
int main() {
for (int i = 2; i <= 100; i++) {
for (int j = 2; j < i; j++) {
if (i%j == 0)
break;
if (j==i-1) // means has never run previous if blog
cout << i << endl;
}
}
return 0;
}
I am attempting to fill an array backwards from 20 to 0 but whenever I print it out it still prints out forwards. For instance I want to put in 1,2,3,4,5 and have it come out as 5,4,3,2,1.
I have attempted to do a for loop that counts backwards from 20 to 0 but when i print it it is still coming out incorrect. Any help?
int temp;
for (int i = 20; i > 0; i--)
{
cout << "Please enter the next number. Use a -1 to indicate you are done: ";
cin >> temp;
while(temp > 9 || temp < -2)
{
cout << "You may only put numbers in 0 - 9 or -1 to exit. Please enter another number: ";
cin >> temp;
}
arr1[i] = temp;
cout << arr1[i];
}
for (int i = 21; i > 0; i--)
{
cout << arr1[i];
What's the size of your array?
Assume that the size is 21 (indexes from 0 to 20).
First of all please note that your first loop will never populate the array at index 0 (something like this arr1[0] = temp will never be executed inside your first loop).
If you want to avoid this behavior you should write your first for loop like this:
for (int i = 20; i >= 0; i--){...}.
The second for loop has some issues:
You are traversing the array backwards while you want to do the opposite.
The loop starts from an index out of bound (21).
The loop may print some undefined values (You should remember the index of the last added value).
I suggest you to use other data structures like a Stack but if you want to use an array you can edit your code as follows:
int i;
for (i = 20; i >= 0; i--){...}
for (i; i <= 20; ++i) { cout << arr1[i]; }
If you don't want to declare int i; outside of the loop you can do something like that:
int lastAdded;
for (int i = 20; i >= 0; i--){
...
lastAdded = i;
}
for (int i = lastAdded; i <= 20; i++) { cout << arr1[i]; }
Edit: Note that neither your code nor mine stops asking for a new value after the insertion of a -1.
If you want to achieve this behavior you should use a while loop instead of the first for loop and check for the exit condition.
char ph[6]={'a','b','c','d','e','f'};
that is my code and this is how I summon them
for(int i=1;i>=3;i++)
{
cout<<ph[i]<<" ";
}
but it turn out blank
Your loop is never going to run.
for(int i=1;i>=3;i++)
Means start at 1 and while we are greater then 3 continue the loop. Since we are never greater than 3 the loop ends.
If you want to print the first 3 elements of the array, then you would use:
for(int i = 0; i < 3; i++)
cout<<ph[i]<<" ";
My program is supposed to take in a number from user input, determine whether or not it is prime, and then if it is not, output the factors of the entered number, 5 to a line. The 5 to the line part is where everything goes haywire, the loop i wrote should work fine as far as i can tell, however no matter how much i change it around, it does one of two things, 1) goes infinite with either new lines or the first factor, or 2) outputs a line with 5 of each factor. Here's the code:
else
{
cout << "\nNumber is not prime, it's factors are:\n";
for (int x = 2; x < num; x++)
{
factor=num%x;
if (factor==0)
{
int t=0;
cout << x << "\t";
t++;
for (int t; t <= 5; t++) // THE TROUBLE LOOP
{
if(t>=5)
{
t=0;
cout << endl;
}
}
}
}
}
Replace the declaration of t in the loop since you've declared t prior to the loop:
for(; t <= 5; t++)
With int t in the loop declaration you are overriding t as an uninitialized variable that will have a garbage value.
Outside of this problem your loop is infinite since you will be resetting t to 0 whenever it equals 5.
In the for loop change the
int t
to
t=0
it is the
for(int t,t<=5,t++)
the int t part in particular that is causing the issue.
#GGW
Or this:
int t = 0;
//some code
for(t; t <= 5; t++)
//more code