We have a sorted array and we want a function that inserts a new character typed by the user into that array and in its appropriate position.
eg.
if array is: cdef
and the user types the character ‘a’ then the new array will be
new array: acdef

In the code below we have an array of only 30 characters (including the NULL). The function checks if the array is filled before doing any change. The FOR loop in main() is just for you to see and test the function. The exercise ONLY needs the function “f()”;

There are 2 solutions of this exercise:

Solution 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE 30

//the first while finds the position where the new character should be placed
//then we start from the position found and copy each character moving to the right
//till every character is in its position
//then a NULL character is entered at the end to end the string
void f(char *seq,char ch){
    char temp;
    int length;
   
    length=strlen(seq);
    //checks whether the array is filled up
    if(length==ARRAY_SIZE-1)
        return;
   
    while(*seq!='\0'){
        if(ch<*seq)
            break;
        seq++;
    }
   
    while(1){
        temp=*seq;
        *seq=ch;
        if(*(seq+1)=='\0'){
            *(seq+1)=temp;
            *(seq+2)='\0';
            break;
        }
        else
            ch=temp;
        seq++;
    }
}

int main(){
    char seq[30];
    char ch;
    int i;
    seq[0]='\0';
    for(i=0;i<5;i++){
        printf("Enter letter to add: ");
        scanf(" %c",&ch);
        f(seq,ch);
        printf("The new seq: %s\n",seq);
    }
    return 0;
}

Solution 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE 30

//the first while finds the position where the new character should be placed
//then we start from the end of the array (only the entered characters and not 30) and
//move everything one position to the right in order to make space for the new one
//then a NULL character is entered at the end to end the string
void f(char *seq,char ch){
    int i,length;
   
    length=strlen(seq);
    //checks whether the array is filled up
    if(length==ARRAY_SIZE-1)
        return;
       
    while(*seq!='\0'){
        if(ch<*seq)
            break;
        seq++;
    }
   
    for(i=length;i>0;i--)
        seq[i]=seq[i-1];
    *seq=ch;
    seq[length+1]='\0';
}

int main(){
    char seq[ARRAY_SIZE];
    char ch;
    int i;
    seq[0]='\0';
    for(i=0;i<5;i++){
        printf("Enter letter to add: ");
        scanf(" %c",&ch);
        f(seq,ch);
        printf("The new seq: %s\n",seq);
    }
    return 0;
}