Sample Questions

  1. Write a program, using pointers, which accepts a string and displays the length of the string.
  2. Write a program that accepts (wo strings, compares them, and displays which is bigger.
  3. Write a program that copies a string into another.

Write a program that. given two strings, append the second string to the first

 Sample Questions and answers

  1. The following program accepts a string as input and displays its length
    #include <stdio.h>
    main()
    {
    int n=0;
    char *ptr=”pointer”;
    puts(“Enter the string”);
    gets(ptr);
    fflush(stdin);
    for(;*ptr!=’’;ptr++)
    	n++;
    printf(“
    The length of the string is %d”, n);
    }​
  2. Program that accepts two strings and compares them.
    #include <stdio.h>
    main(){
    char *str1="string one";
    char *str2 ="string two";
    puts ("
    Enter first string"):
    gets (str1) ;
    fflush(stdin) ;
    puts ("
    Enter second string");
    gets (str2) ;
    fflush (stdin);
                for(;*str1==*str2 && (*str1! ='’ || *str2!=’); str1++, str2++) ;
    if(*str1==’ ’ && *str2==''){
    printf(“
    The strings are equal”);
    return;
    }
    if (*str1> *str2)
    printf(“
    The first string is bigger than the second”);
                   else
    printf(“
    The second string is bigger than the first”);
    
    return;
    }​
  3. The following program copies a string into another
    #include <stdio.h>
    main(){
    char *string1= "string one";
    char *string2 ="string two";
    puts ( "
    Enter the string");
    gets (string2);
    fflush (stdin) ;
    while (*string2!=’'){
    *string1=*string2 ;
    String1++;
                   }
    *string1= '’ ;
    printf("
    The copy is over”);
    return;
    }​
  4. As an extension of the previous program that copies the second string into the first, the following program concatenates the two strings
    #include <stdio.h>
    main(){
    char *string1="string one”;
    char *string2 ="string two";
    puts ("
    Enter first string");
    gets (string1) ;
    fflush(stdin);
    puts ("
    Enter second string”);
    gets (string2);
                fflush(stdin);
    for(;*string1 != ‘’;string1++);  /* traverse to the end of string1 */
    while (*string2! = ‘’){
    *string1=*string2;
    string1++;
    string2++;
    }
    *string1 = ‘’;
    return;
        }​