How to Write this code for Pseudo Code for c++ ? -------------------------------
ID: 3820543 • Letter: H
Question
How to Write this code for Pseudo Code for c++ ?
-----------------------------------------------------------------------------------------------
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
//Function prototype
bool isPrime(int);
//Main function
int _tmain(int argc, _TCHAR* argv[])
{
int num;
int currNum, count;
//Opening file
fstream fout("PrimeOut.txt", ios::out);
//Verifying file opening status
if(fout.fail())
{
cout << " Error!! creating file... ";
return -1;
}
//Reading a number
cout << " Enter a number (1 - 100): ";
cin >> num;
//Validating number
while(num < 1 || num > 100)
{
//Reading a number
cout << " Error!! Not in range... Enter a number (1 - 100): ";
cin >> num;
}
//Initializing values
count = 0;
currNum = 2;
cout << " ";
//Iterating loop till count reaches the number
while(count < num)
{
//Checking for prime number
if(isPrime(currNum))
{
//Printing prime number to console
cout << setw(5) << currNum;
//Printing prime number to file
fout << setw(5) << currNum;
//Incrementing count
count++;
}
//Checking for ten numbers
if(count % 10 == 0)
{
//If there are ten numbers, print new line
cout << endl;
fout << endl;
}
//Incrementing current number
currNum++;
}
//Closing file
fout.close();
cout << " ";
system("PAUSE");
return 0;
}
//Function that checks for prime number
bool isPrime(int n)
{
int k;
//Iterating from 2 to 1 less than the number
for(k = 2; k <= n - 1; k++)
{
//If there is any divisibility, it is not a prime number
if ( n % k == 0 )
return false;
}
//If k is equal to n, it is a prime number
if ( k == n )
return true;
else
return false;
}
Explanation / Answer
Main :
int currNum, count,num;
//OPEN FILE FOR WRITING
fout = "PrimeOut.txt"
//VERIFYING FILE OPENING STATUS
if(fout is null)
Display Error : "Error!! creating file..."
exit;
//READING A NUMBER FROM USER WITBEEN 1 AND 100
Display Message : "Enter a number (1 - 100):"
num = ReadNumber()
//VALIDATING NUMBER
loop till(num < 1 or num > 100)
//DISPLAY ERROR AND AGAIN READING NUMBER
Display Error : "Error!! Not in range..."
Display Message : "Enter a number (1 - 100): "
num = ReadNumber()
loop end
//Initializing values
count = 0
currNum = 2
//ITERATING LOOP TILL COUNT REACHES THE NUMBER
loop till (count < num):
//CHECKING FOR PRIME NUMBER
if(isPrime(currNum))
PrintOnConsole(currNum)
fout.Write(currNum);
count++;
//Checking for ten numbers
if(count MOD 10 == 0)
//If there are ten numbers, print new line
PrintOnConsole(" ")
fout.Write(" ")
//Incrementing current number
currNum++;
loop end
//Closing file
close(fout);
}
boolean isPrime(n)
{
int k;
loop from k = 2 to k =(n - 1) :
if ( n MOD k == 0 )
return false;
if ( k == n )
return true;
else
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.