Coding Practice

Write a c program to reverse an array before target number and after target number

Reverse an array where the output will be like this...

Write a c program to reverse an array before target number and after target number. i.e. if the array is 1 2 3 4 5 6 7 and the target number is 4 then it will print 3 2 1 4 7 6 5

Sample Output
Enter array size: 7
Enter array numbers: 1 2 3 4 5 6 7
Enter a target number: 4
3 2 1 4 7 6 5

Process returned 0 (0x0)   execution time : 10.573 s
Press any key to continue.
Source Code
#include<stdio.h>

int main()
{
    int a[100], i, j, k, size, num, LHS[100], RHS[100];

    /**
    LHS = Left Hand Side
    RHS = Right Hand Side

    LHS is the left side of its target number
    and RHS is the right side of target number.
    */

    printf("Enter array size: ");
    scanf("%d", &size);

    printf("Enter array numbers: ");
    for(i = 0; i < size; i++)
    {
        scanf("%d", &a[i]);
    }

target:
    printf("Enter a target number: ");
    scanf("%d", &num);

    for(i = 0; i < size; i++)
    {
        if(num == a[i])
        {
            break;
        }
    }
    if(num != a[i])
    {
        printf("\nTarget number not found!\nThe target number must be include in input number.\n\n");
        goto target;
    }

    for(j = i - 1, k = 0; j >= 0 ; j--, k++)
    {
        LHS[k] = a[j];
    }
    for(j = 0; j < i; j++)
    {
        a[j] = LHS[j];
    }
    for(j = size - 1, k = i + 1; k < size; k++, j--)
    {
        RHS[k] = a[j];
    }
    for(j = i + 1; j < size; j++)
    {
        a[j] = RHS[j];
    }
    for(i = 0; i < size; i++)
    {
        printf("%d ", a[i]);
    }
    printf("\n");

    return 0;
}
Sample Output
Enter array size: 5
Enter array numbers: 1 2 3 4 5
Enter a target number: 9

Target number not found!
The target number must be include in input number.

Enter a target number: 7

Target number not found!
The target number must be include in input number.

Enter a target number: 3
2 1 3 5 4

Process returned 0 (0x0)   execution time : 16.298 s
Press any key to continue.

No comments:

Post a Comment

Change Theme
X