Answer to Question #145472 in C for chinnari rao

Question #145472
allocate the memory at runtime to store 10 integers and ask values from the user.now,create another array of same size and fill the elements based on the preocessing of elements in the first array as follows:
if the number at any location is prime,then store P at the same location in second array
if the number is not prime but if it is even,the store E
in case above conditions are not true ,then store N
1
Expert's answer
2020-11-19T16:48:46-0500
#include <stdio.h>
#include <stdlib.h>


int isPrime(int num)
{
    int i;
    int flag=0;

    // 1 is not prime nor composite
    if(num==1)
        return 0;

    for(i=2; i<num; i++)
    {
        if(num%i ==0)
        {
            flag =1;
            break;
        }
    }

    //flag is 1, if number is not prime
    if(flag==1)
        return 0;
    else
        return 1;
}

int main()
{


    int* ptr;
    char *cptr;
    int n=10, i;

// Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
    cptr = (char*)malloc(n * sizeof(char));
// Check if the memory has been successfully
    if (ptr == NULL) {
        printf("Error Memory not allocated.\n");
        exit(0);
    }
    else
    {


        for (i = 0; i < n; i++)
        {
            printf("Enter %d element:",i+1);
            scanf("%d",&ptr[i]);
        }

        for(i=0;i<n;i++)
        {
            if(isPrime(ptr[i]))
                cptr[i]='P';

            else if(ptr[i]%2==0)
                cptr[i]='E';

            else
                cptr[i]='N';

        }

        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
            printf("%c, ", cptr[i]);
        }
    }

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS