Strings - Find output programs in C (Set 1)

String is the set of characters terminated by NULL, it is also known as character array.

This section contains programs with the output and explanation based on C programming language strings.

Predict the output of following programs.

Program - 1

#include <stdio.h>
int main()
{
	printf("%s\n",4+"Hello world");
	printf("%s\n","Hello world"+4);
	return 0;
}

Output

o world
o world

Explanation

Both 4+"Hello world" and "Hello world"+4 will print the string from 4th index.


Program - 2

#include <stdio.h>
#include <string.h>

int main()
{
	char str[]="Hello";
	
	str[strlen(str)+1]='#';
	printf("str= %s\n",str);
		
	return 0;
}

Output

str= Hello

Explanation

In the variable str, "Hello" stored at following indexes
str[0]: 'H'
str[1]: 'e'
str[2]: 'l'
str[3]: 'l'
str[4]: 'o'
str[5]: '\0'
strlen(str)+1 will return 6, then character '#' will be stored at str[6].
Since printf, prints characters of the string till NULL, it will not print '#' as it exists after the NULL. Thus, the output will be "str= Hello".


Program - 3

#include <stdio.h>

int main()
{
	char str[]={0x41,0x42,0x43,0x20,0x44,0x00};
	printf("str= %s\n",str);		
	return 0;
}

Output

str= ABC D

Explanation

Here, str is initializing with with the hexadecimal values of the character, these are the characters which are being initialized:

0x41 (A), 0x42 (B), 0x42 (C), 0x20 (SPACE), 0x4D (D)


Program - 4

#include <stdio.h>

int main()
{
	char str[]="Hello";
	char *ptr=str;
	
	while(*ptr!='\0')
		printf("%c",++*ptr++);
	
	printf("\n");
		
	return 0;
}

Output

str= Ifmmp

Explanation

*ptr will return the character pointed by the pointer; initially it will return character stored at first byte, which will be checked with NULL.
++*ptr++ will evaluate as:
++*ptr: it will return the character and print next character (due to increment operator ++*ptr)
ptr++: it will point the next index


Program - 5

#include <stdio.h>

int main()
{
    char str[5]={0},loop=0;
    
    while(loop<5)
        printf("%02X ",str[loop++]);
    printf("\n");
	
	return 0;
}

Output

00 00 00 00 00

Explanation

Here, str is initialized with 0 (that is equivalent to NULL, all 5 elements of the character array witll be initialized with it), and %02X will print the value of character array (str) in 2 bytes padded hexadecimal code, thus the output will be "00 00 00 00 00".





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.