+ 1
Nested if and for
Is it possible to nest a "for" into an "if"? I've created this code but it keeps giving me error and it's driving me crazy: https://code.sololearn.com/cKoE25Zn10g9/?ref=app I know that the same thing can be done in many simpler ways but I'm trying to apply what I've learned. Thanks!!
3 odpowiedzi
+ 6
If you want to test a condition for each value in the loop, doing so in the way you tried is impossible.
A for-loop is not a something the compiler recognizes as a value and can work with.
However, you can nest an if-statement in a for-loop:
for (int a = 0; a < 10; ++a) {
if (++value > 15) {
//do something
}
}
That code segment would run the for-loop ten times and check in each iteration if value is bigger then 15, then you can do whatever you want based on the result.
+ 5
#include <iostream>
using namespace std;
int main() {
int value;
cin >> value;
if(value > 15) {
for(int a=0; a<10; a++)
value=value+1;
cout<<value;}
else {cout<<"too small";}
return 0;
}
+ 3
non so
Debugging is a vital part of coding, You will come to find that a lot of your time will be spent debugging code. It is in your best interest to learn how to read and understand error messages.
Your code as is, produced five error messages, three of them produced by one line of code alone. Each error message is telling you that there is something wrong with the code's formatting (syntax). That is your cue to inspect and debug your code.