Answer to Question #327267 in C++ for Zee

Question #327267

Make a file by yourself named ”Integer.txt” and add 5 integer values in it. Now, write a C++



program that reads data (5 integers) from the file and store them in integer array. Also make another



integer array (int result []) of same size to store the results. The program should check for each number



in array if it is prime number or not. If the number is prime, update value in result[] array from 0 to 1.



Lastly, write output in another file named “Result.txt”



Example



Input:



Integer.txt



2 11 1 17 8



Output:



Result.txt



1 1 0 1 0



Hint: Prime number are those which is only divisible by 1 or itself.




1
Expert's answer
2022-04-13T02:14:57-0400
#include <iostream>
#include <fstream>
#include <string>


using namespace std;



bool isPrime(int n){

    if (n<2){
        return false;
    }
    int k=2;
    int c=0;
    while (n>1){
        if (n%k==0){
            c+=1;
            n/=k;
        }
        else {
            k++;
        }
    }
    return c==1;
}


int main()
{

    ifstream inputFile ("Integer.txt");


    ofstream outputFile;


    outputFile.open ("Result.txt");



    
    int numbers[5];


    int primes[5];


    int element;
    if (inputFile.is_open()){
        int i=0;
        while (i<5)
        {
          inputFile >> element;  
          numbers[i++]=element;
        }
    inputFile.close();
    }
    if (outputFile.is_open()){
        int i=0;
        while ( i<5)
        {
            if(isPrime(numbers[i])){
                primes[i]=1;      
            } else {
                primes[i]=0;
            }
            outputFile << primes[i] << " ";
            i++;
        }
    outputFile.close();
    }
    // Result.txt
    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