Please use C language and make sure the code can run in Code

Please use C language and make sure the code can run in Codeblck.

Thank you.

Consider the array int array [ arrayLength] = { 4 , 6 , 7 , 3 , 8 , 2 , 1 , 9 , 5 };

and write a program to do the following:

Ask the user for a number between 1 and 9. If the user does not enter a number between 1 and 9, repeatedly ask for a number until the user does. Once the user entered a number between 1 and 9, print the array. Then search the array for the number that the user entered and print the index of that element.

Hints: • The user might enter a character or a sequence of characters.

Use the following code segment to detect for invalid input.

if ( scanf (\"%d \", & number ) != 1) ;

{

char buffer [100];

gets( buffer );

}

Solution

#include <stdio.h>

int main(){

    //declaration of array length

    int arraylength = 9;
    //initialising the array in which to search
    int array [9] = { 4 , 6 , 7 , 3 , 8 , 2 , 1 , 9 , 5 };

    //decraling variables
    int number;
    char line[100];
    int isint;

    //taking input number
    printf(\"Enter number: \");
    fgets(line, sizeof line, stdin);
    isint = sscanf(line, \"%d\", &number);

    //if invalid input, print the statement and take input again
    if (!isint){
        printf(\"That was not a number. Please enter a number between 1 and 9.\ \");
    }

    while(number>9 || number<1){
        //taking input number
        printf(\"Enter number: \");
        fgets(line, sizeof line, stdin);
        isint = sscanf(line, \"%d\",&number);

        //if invalid input, print the statement and take input again
        if (!isint){
            printf(\"That was not a number. Please enter a number between 1 and 9.\ \");
        }
    }

    //searching the number in the list
    for(int i=0; i<arraylength; i++){
        if(array[i]==number){

            //if found print the index at which found
            printf(\"Found at %d\ \", i);
        }
    }

}

Please use C language and make sure the code can run in Codeblck. Thank you. Consider the array int array [ arrayLength] = { 4 , 6 , 7 , 3 , 8 , 2 , 1 , 9 , 5 }
Please use C language and make sure the code can run in Codeblck. Thank you. Consider the array int array [ arrayLength] = { 4 , 6 , 7 , 3 , 8 , 2 , 1 , 9 , 5 }

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site