+ 3

Explain for loop plse i don't understand that*str

https://code.sololearn.com/ci6wl04V0LgZ/?ref=app

18th Jul 2018, 5:14 AM
Programmer Raja
Programmer Raja - avatar
9 Respostas
+ 7
I code in JavaScript. But it is the same principal: for(i = 0; i < 10; i++) at first with 'i = 0' you create a variable 'i' . Then with 'i < 10' you are setting the test condition. Basically saying the loop is true as long as i is less than 10. Then in the third part 'i++' you are saying keep increasing i by 1 until it is no longer less than 10. Or else the condition is false and the loop must stop.
18th Jul 2018, 10:43 AM
Ryan Els
Ryan Els - avatar
+ 5
Boopathi Don't afraid of the unusual form of the for loop here. It doesn't bite! All three expressions inside a for loop are optional* which in this case we've just used the loop step expression to move through each element of the array. Suppose the array s' internal representation makes up as address value 280 n/a 279 n/a ... ... 201 n/a 200 n/a The array occupies a memory block from 200 to 280 when get declared as char s[80]; In case of *str, it's a simple integer pointer which gets initialized to the address of the first element of the array as str = s Now, str is equal to 200 as the address of the first element of the array. Every time that str increases as ++str The next address of the array will be stored in str. (e.g. 201, 202, ...) Also, *str in if (*str == 32), dereferences the current character pointed by the stored address in str and then compare it against the space character.
18th Jul 2018, 8:25 AM
Babak
Babak - avatar
+ 4
Corrected version of the code #include <stdio.h> int main() { char s[80],*str; int space = 0; printf("enter the string"); gets(s); str=s; for( ; ; str++) { if(*str == 32) break ; ++space; } printf("%d",space); } The for loop traverses through the array using str pointer. Using pointer in this context makes it possible to increment the pointer with ++ operator. Then, the loop continues to cycle before the first space is encountered in the inputted character sequence. Finally, it counts the number of characters before exiting the loop and prints it out on the console screen.
18th Jul 2018, 6:10 AM
Babak
Babak - avatar
+ 4
Boopathi Which part do you want to know more about?
18th Jul 2018, 6:16 AM
Babak
Babak - avatar
+ 4
Cont. ____ * for ( loop counter initializer ; loop condition ; loop step ) without them you've got an infinite loop as for ( ; ; ) Which is equivalent to while (true)
18th Jul 2018, 9:01 AM
Babak
Babak - avatar
+ 3
muppatti ramya sri Sure. Try to experiment with it if you are willing to get the whole idea of what happens.
19th Jul 2018, 3:01 PM
Babak
Babak - avatar
+ 1
understand .but cam you explain briefly plse
18th Jul 2018, 6:15 AM
Programmer Raja
Programmer Raja - avatar
+ 1
for loop *str??????
18th Jul 2018, 7:57 AM
Programmer Raja
Programmer Raja - avatar
+ 1
without a condition for loop works???? for( ; ; i++)
19th Jul 2018, 2:36 PM
Ramya
Ramya - avatar