Answer to Question #327361 in C++ for Farhan

Question #327361

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” 



1
Expert's answer
2022-04-11T12:13:34-0400
#include<iostream>
#include<string>
#include<fstream>


using namespace std;


bool isprime(int n)
{
	bool isPrime = true;
	if (n == 0 || n == 1)
		isPrime = false;
	else
	{
		for (int i = 2; i <= n / 2; ++i)
		{
			if (n%i == 0)
			{
				isPrime = false;
				break;
			}
		}
	}
	return isPrime;
}


int main()
{
	const int N = 5;
	int arr[N];
	cout << "Please, enter 5 values: ";
	for (int i = 0; i < N; i++)
	{
		cin >> arr[i];
	}
	ofstream of;
	of.open("Integer.txt");
	if (!of.is_open())
		cout << "File isn`t opened!";
	else
	{
		for (int i = 0; i < N; i++)
		{
			of << arr[i] << " ";
		}
	}
	of.close();
	int arrFromFile[N];
	ifstream ifs("Integer.txt");
	if (!ifs.is_open())
		cout << "File isn`t opened!";
	else
	{
		string line;
		string str = "";
		getline(ifs, line, '\n');
		int k= 0;
		for (int i = 0; i < line.size(); i++)
		{
			if (line[i] == ' ')
			{
				arrFromFile[k++] = stoi(str);
				str = "";
			}
			else
				str += line[i];
		}
	}
	ifs.close();
	int result[N];
	for (int i = 0; i < N; i++)
	{
		if (isprime(arrFromFile[i]))
			result[i] = 1;
		else
			result[i] = 0;
	}
	cout << "\nResult array: ";
	for (int i = 0; i < N; i++)
	{
		cout << result[i] << " ";
	}
	ofstream ofr;
	ofr.open("Result.txt");
	if (!ofr.is_open())
		cout << "File isn`t opened!";
	else
	{
		for (int i = 0; i < N; i++)
		{
			ofr << result[i] << " ";
		}
	}
	ofr.close();
}

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