Write a function which, given a string and an integer n, adds n to all the characters of the string.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <string.h>
#define MAX 100

void get_line(char *, int);
int add_n(char *, int);

int main(int argc, char ** argv) {
    char line[MAX];
    int n = 2;
    get_line(line, MAX);
    add_n(line, n);
    return 0;
}

void get_line(char line[], int N) {
    char c;
    int i;
    for (i = 0; i < N-1 && (c = getchar()) != '\n'; i++)
        line[i] = c;
    line[i] = '\0';
}

int add_n(char line[], int n) {
    for (int i = 0; i < strlen(line); i++) {
        line[i] += n;
    }
    printf("\n%s\n", line);
}

When you compile and execute the above program it produces the following result on Linux:

When the user types the word "good", he gets "iqqf"

good

iqqf

Brief Explanation

  • The program starts by using the function get_line to get the next input line. This is stored in an array of character (string) called line. The null character (\0) is used to ensure termination.
  • The function add_n iterates through all the characters of the string and adds the value of integer n to each.
  • Using printf function, the modified string is printed to the stdout.

Add comment


Security code
Refresh