Thread: how do i make the condition statement in my for loop a variable?

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    18

    how do i make the condition statement in my for loop a variable?

    hi the code I'm talking about is this :
    Code:
    #include <iostream>
    int main()
    {
       using namespace std;
       char h[] = "Hello"
    
       for (int i = 0; i = 5; i++)
          cout << h[i];
    }
    how do i make the "i = 5" a variable not a constant? like i = '\0' or something so it automatically stops when it reaches the end of the string not because i = 5.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,739
    "i = 5" is assignment, not comparison. "i == 5" is comparison.

    The middle statement in a for loop is the condition to keep looping. As long as that condition is true, the loop keeps running. Using "i < 5" is what you probably want to use.

    If you just want to print the string, you don't need a loop. Just do:
    Code:
    cout << h << endl;
    But if you want to do something else with the characters of the string, there are two or three different ways you can approach this:
    Code:
    #include <cstring>
    
    int len = strlen(h);
    for (int i = 0; i < len; i++) {
        // do stuff with h[i]
    }
    Code:
    for (int i = 0; h[i] != '\0'; i++) {
        // do stuff with h[i]
    }
    Code:
    // If you can change the pointer, not applicable in your case
    while (*h != '\0') {
        // do stuff with *h
        ++h;
    }
    Lastly, I know you're simply learning right now, but remember to prefer C++ strings to the old C-strings, they're far more easy to use.
    Last edited by GReaper; 02-02-2017 at 10:52 PM.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. If statement wont check the second condition
    By BIGDENIRO in forum C Programming
    Replies: 9
    Last Post: 09-25-2013, 05:41 AM
  2. using two GetAsyncKeyState a while statement with an or condition
    By Rob Fisher in forum Windows Programming
    Replies: 3
    Last Post: 01-11-2013, 04:59 AM
  3. Can I call a function inside condition of if statement?
    By Meerul264 in forum C++ Programming
    Replies: 2
    Last Post: 12-14-2012, 11:06 PM
  4. if-else statement condition
    By YouMe in forum C Programming
    Replies: 16
    Last Post: 07-04-2012, 09:48 AM
  5. need while(for(loop)) to be condition
    By thestien in forum C++ Programming
    Replies: 4
    Last Post: 10-12-2006, 08:32 AM

Tags for this Thread