C Program to Return Second Word of a String in Uppercase

Write a program to return second word of a string in uppercase in C language.

For example,

My name is John Smith


  1. Let the input string be str.
  2. Set i = 0.
  3. Increment i until str[i] is equal to blank character. By doing so, we are basically skipping the first word of the string.
  4. Declare a temporary array temp[]. temp[] stores the second word of str in uppercase.
  5. Increment i.
  6. Insert each character of str starting from str[i] to temp[] using a loop till str[i] is equal to the blank character. If str[i] is lowercase, it is converted to uppercase before we insert it to temp[].
  7. Return temp.

C Program to Print Second Word of a String in Uppercase


  1. There is only one blank character between each word.
  2. There is no blank space at the beginning and end of the string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// return second word of str in uppercase
char* second_word_uppercase(char* str) {

	int n = strlen(str); // store length of str in n
	int i, j;

	char* temp = (char*)malloc(sizeof(str) + 1); // array to store second word of str

	// skipping first word of str
	while (i < n && str[i] != ' ') {

	// if i == n, then the sentence have no second word
	// we simply return NULL
	if (i == n) {
		return NULL;

	// storing second word of str in temp
	j = 0;
	while (i < n && str[i] != ' ') {

		// if str[i] is lowercase, we first convert it to uppercase
		// and then store it to temp[j]
		if (str[i] >= 'a' && str[i] <= 'z')
			temp[j] = str[i] - 'a' + 'A';
		// if str[i] is already uppercase, set temp[j] to str[i]
			temp[j] = str[i];

		++i, ++j;


	temp[j] = '\0';

	return temp;


int main() {

	char str[100];
	printf("Enter a String: ");

	printf("Output: %s", second_word_uppercase(str));



Enter a String: My name is John Smith
Output: NAME


You can use isupper() to check if a character is uppercase or not and toupper() to convert a character to uppercase. Both isupper() and toupper() are part of <ctype.h> header file.

Leave a Comment

Your email address will not be published. Required fields are marked *