2
#include <stdio.h>

char s[] = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";

int main ()  
{
   int i, c;
   while ((c = getchar()) != EOF) {
      for (i = 1; s[i] && s[i] != c; i++);
      if (s[i]) putchar(s[i-1]);
      else putchar(c);
      /* code */
   }
   return 0;
}

Whats does the condition s[i] && s[i] != c; inside the for loop mean?
I haven't seen it before. Thanks!

Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
Miguel
  • 23
  • 4

2 Answers2

5

First of all the variable s is a null terminated C-string, which is an array of chararcters with the last character being '\0'. You access that array with the index i in your code.
With that for loop you loop through the s string until a null terminator '\0' or the char c is found. The null terminator '\0' is 0 decimal which means false in boolean logic because everthing else than 0 is true.

If you write for example:

char a = 'A';   /* same as char a = 65; */
if (a) { ... }; /* same as if (a != 0)  */

that means: if a is true which is: if a is not false and better: if a is not equal to 0. This statement will evaluate to true because 'A' is 65 decimal (ASCII code) which is not equal to 0.

The for loop you've asked for can be rewritten as:

for (i = 1; s[i] != '\0' && s[i] != c; i++);

I would recommend to use explicit statements like s[i] != '\0' because it is easier to read.

Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
-3

s[i] in if is going to check whether an element exists on s[i] . if element exists on s[i] then it's truthy if not then it's falsy .

c is being intialized with user input in while loop

c = getchar()



s[i] != c // it means that my inputted value can not be equal to s[i].
Nirmal Dey
  • 191
  • 5
  • Your answer contains two false assertions : First, if a char `c` is assigned the value `'\0'`, i.e the null character, then `if(c)` would return false, and `c` would 'exist'(it is just `null`). Second, it seems to me that trying to access a 'non-existing element' in C, such as out-of-bounds, results in undefined behavior. Most of time, the program would return false, but it still is UB, and thus shall never be considered reliable. – m.raynal Jul 10 '17 at 11:47