C - Exercise 6

C Programming

Share

In this exercise section of the tutorial we will write some C program.

Write a program in C to take user name as input and display a greetings message

In this code we are assuming that the user name will be less than 256 characters long.

We will be using the gets() function to take user name as input.

/**
 * file: string.c
 * author: yusuf shakeel
 * date: 2010-12-25
 * description: string program
 */

#include <stdio.h>
int main(void)
{
  //variable
  char name[256];
  
  //input
  printf("Enter your name: ");
  gets(name);
  
  //output
  printf("Hello, %s!\n", name);
  
  printf("End of code\n");
  return 0;
}

Output

Enter your name: Yusuf Shakeel
Hello, Yusuf Shakeel!
End of code

Write a program in C to print the following pattern

Pattern

A
Ap
App
Appl
Apple

The given pattern has 5 rows which is equal to the number of letters in the string "Apple".

To find the total number of characters in a string we will use the strlen() function from the string.h header file.

Note! A string is a sequence of characters stored in a character array. Therefore, we can access the elements in the array using the index.

/**
 * file: string-pattern.c
 * author: yusuf shakeel
 * date: 2010-12-25
 * description: string pattern program
 */

#include <stdio.h>
#include <string.h>
int main(void)
{
  //variable
  char str[] = "Apple";
  
  //length of the string
  int len = strlen(str);
  
  int r, c;
  
  //output
  for (r = 0; r < len; r++) {
    for (c = 0; c <= r; c++) {
      printf("%c", str[c]);
    }
    printf("\n");
  }
  
  printf("End of code\n");
  return 0;
}

Output

A
Ap
App
Appl
Apple
End of code
Share