Issue related to output

code 1;
#include <stdio.h>

int main(void) {
// your code goes here
int t;
char a[10000];
scanf("%d",&t);
while(t–){
int n,temp;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%c",&a[i]);
}
for(int i=0;i<n-1;i=i+2){
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
for(int i=0;i<n;i++){
a[i]=‘z’-(a[i]-‘a’);
}
for(int i=0;i<n;i++){
printf("%c",a[i]);
}
printf("\n");
}
return 0;
}
code 2:
#include <stdio.h>

int main(void) {
// your code goes here
int t;
char ar[10000];
scanf("%d",&t);
while(t–){
int n,x;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf(" %c",&ar[i]);
}
for(int i=0;i<n-1;i=i+2){
x=ar[i];
ar[i]=ar[i+1];
ar[i+1]=x;
}
for(int i=0;i<n;i++){
ar[i]=‘z’-(ar[i]-‘a’);
}
for(int i=0;i<n;i++){
printf("%c",ar[i]);
}
printf("\n");
}
return 0;
}
why code 1 is just giving output h
while code 2 is absolutely correct
there is nothing difference in it

Hey @vishwajeet_56, the above 2 codes are not same though its looking. There is a little difference which makes the 2 codes so different.
See in line no. 15 of both the codes, the scanf(“%c”, &a[i]); and scanf(" %c", &ar[i]);

In 1st case, when you input n and hit enter… the newline is read by the scanf in loop for a[0] and you got unexpected output.
In 2nd case, you added a space before %c in scanf format, it means it ignores the incoming white spaces and newlines while reading the input n. So it will not read newline as happened in case 1 and you got the expected result.

Now the question is… what is space actually doing?
As I said before… it will not read the white spaces and newline character coming from the input buffer. It is like a filler for space and newline before reading character. (like * to ignore any character in scanf).

You can read these articles for more clarity about scanf:

Happy Coding :slightly_smiling_face:

2 Likes

Thankyou!