Junior Bill gates
Junior Bill gates

Reputation: 1866

operation of for loop

i am working in embedded c for last some month and till now i have come across simple for loops like:

for(i=0;i<10;i++)

but now i came across a new type of for loop which is:

for(t=0; string[t]; ++t)

can anyone please tell me how this loop works. The sample code is:

#include <stdio.h>
#include <ctype.h>

void print_upper(char *string);

int main(void)
{
    char s[80];
    printf("Enter a string: ");
    gets(s);
    print_upper(s);
    printf(''\ns is now uppercase: %s", s);
    return 0;
}

/* Print a string in uppercase. */
void print_upper(char *string)
{
    register int t;
    for(t=0; string[t]; ++t)
    {
        string[t] = toupper(string[t]);
        putchar(string[t]);
    }
}

Upvotes: 0

Views: 166

Answers (2)

Joe
Joe

Reputation: 47609

If the string is null-terminated, then the last character will be a null. This evaluates as false. The middle clause of the for syntax is a boolean expression. If it is true, the loop continues, if it is false, the loop terminates. The loop indexes character t of the string, and increments t, meaning that it tests each character in turn to see if it is 'true'.

This syntax would therefore loop over every character in the string and stop at the end.

Upvotes: 7

Mansuro
Mansuro

Reputation: 4617

the loop has 3 parts

  1. t=0; initialization

  2. string[t]; condition to exit the loop, if string[t] is null which is like saying the condition is false, the loop will exit

  3. ++t incrementation, once it has made one loop, it increments t

so basically, your loop checks string char by char, once it finds the null caracter, it exits

Upvotes: 1

Related Questions