theboringdeveloper
theboringdeveloper

Reputation: 1485

Not Getting Any output While Printing after combining strings

To combine First , middle and last name of a person.

int main()

{

    int i,j,k;

    char first_name[11]="Gursheesh";

    char middle_name[10]="Singh";

    char last_name[10]="Chawla";

    char name[30];

   for(i=0;first_name!='\0';i++)

   {

    name[i]=first_name[i];

   }

   name[i]=' ';

   i++;

   for(j=0;middle_name!='\0';j++)

   {

    name[i+j]=middle_name[j];

   }

   name[i+j]=' ';

   j++;

   for(k=0;last_name!='\0';k++)

   {

    name[i+j+k]=last_name[k];

   }

   name[i+j+k]='\0';

   printf("%s",name);

}

this is the code

the compiler at run time shows nothing

I cannot find the mistake,help me.

is it having some loop continue this infinity or some logical misktake.

Upvotes: 0

Views: 75

Answers (3)

awadhesh14
awadhesh14

Reputation: 89

Here is the correct code.

#include <stdio.h>
int main(){

   int i,j,k;

   char first_name[11]="Gursheesh";

   char middle_name[10]="Singh";    

   char last_name[10]="Chawla";

   char name[30];

   for(i=0;first_name[i]!='\0';i++)

   {

    name[i]=first_name[i];

   }    

   name[i]=' ';

   i++;

   for(j=0;middle_name[j]!='\0';j++)

   {

    name[i+j]=middle_name[j];

   }

   name[i+j]=' ';

   j++;

   for(k=0;last_name[k]!='\0';k++)

   {

    name[i+j+k]=last_name[k];

   }

   name[i+j+k]='\0';

   printf("%s",name);

}

Upvotes: 1

anfauglit
anfauglit

Reputation: 161

Cleaner approach using pointers and storing inputs in an array.

#include <stdio.h>

int main (void)
{
    char result[30];
    char *pntResult = result;
    char *appendStr (char *dest, char *strToAppend);

    char *name[3] = { "FirstName", "MiddleName", "LastName" };
    int i;

    for ( i = 0; i < 3; ++i )
        pntResult = appendStr (pntResult, name[i]);

    *(pntResult - 1) = '\0';

    printf ("%s\n", result);

    return 0;
}

char *appendStr (char *dest, char *strToAppend)
{
    while ( *strToAppend )
        *dest++ = *strToAppend++;

    *dest++ = ' ';

    return dest;
}

Upvotes: 1

Nikita
Nikita

Reputation: 6427

All your loops are infinite:

for(i=0;first_name!='\0';i++)

condition first_name!='\0' is always true. You should check for first_name[i] != '\0':

for(i=0; first_name[i] != '\0'; i++)

By the way, to copy strings it's better to use strcpy function.

Upvotes: 3

Related Questions