Alice1nw0
Alice1nw0

Reputation: 69

how to add a number to each character of a string

I have to code a function in C which which receives a string of characters and then adds to each character the number 13. I've come up with this solution :

#include<stdio.h>

main() 
{
     char text[100];
     gets(text);
     code (text);
     }

 code (char text[100])
{
    int i;
    for(i=0;i<=98;i++)
    {
        text[i]=text[i] + 13 ;
    }
    printf ("%s",text);
    return (0);

}

Is this right?

Upvotes: 0

Views: 1415

Answers (2)

Ayushi Jha
Ayushi Jha

Reputation: 4023

code function should have a return type, if it does not require to return anything, set its type to void.
A function prototype/definition should be present before you use it.
The user may not necessarily input a string of a fixed length, so use the strlen function from the string.h header file to calculate the legth of input string.
The standard definition of main() should be as int main(){ return 0;}

#include<stdio.h>
#include<string.h>
void code(char []);
int main()
{
    char text[100];
    gets(text);
    code (text);
    return 0;
}

void code (char text[100])
{
    int i;
    int length=strlen(text);
    for(i=0;i<=length;i++)
    {
        text[i]=text[i] + 13 ;
    }
    printf ("%s",text);
    //return (0);
}

Upvotes: 0

user4227915
user4227915

Reputation:

You need look some details:

// a void function should NOT return

void code (char text[]){
// when passing a string as argument, you don't need to indicate its' size

    int i = 0; // pay attention to give a value when initializing

    while (text[i] != '\0') { // '\0' indicates string's end...

        // while not the end
        text[i] += 13;    // same as text[i] = text[i] + 13;
        i += 1;           // same as i = i + 1;

    }

    printf("%s", text);
    // the string was encoded
}

Example:

char text[100];  // its' size is 100, but..
gets(text);      // if you read "hello" from input/keyboard

the result will be:

value ->        h  e  l  l  o  \0 
                |  |  |  |  |   |
position ->     0  1  2  3  4   5  ....

Your text ends in position 5.... because that, you need search for '\0', to find where the string ends..

Hope it helps.

Upvotes: 1

Related Questions