I have to write out a list of prime numbers from 1-100, using a function we have previously wrote, to a file. The commented out part isn't anything related; it's just the previous code we used for the function. I don't know exactly what's going on because the file isn't even being created, and the part inside the for loop is executing with just 2's, 100 times.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
int p = 2;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
isPrime(p);
cout << p << endl;
outputFile << p << endl;
}
outputFile.close();
cout << "You should now have the file." << endl;
/* int n;
int counter = 0;
int p = 2;
cout << "Welcome to prime counter. " << endl;
cout << "Which prime number would you like? ";
cin >> n;
while (counter < n) {
if (isPrime(p)) {
counter++;
}
p++;
}
p = p - 1;
cout << "Prime number " << n << " is " << p << "." << endl;
*/
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
Could someone please explain what I'm doing wrong here, and why it isn't even creating the file?
You initialize p at the top with 2. You should be calling isPrime with i instead.
You're getting 2s because you're printing out and storing p, but the loop is going over i.
Here is the updated code. Upon research I did find where it was saving the files, and there are instances of it just not working at all. However, This code runs and does give me everything I need it to.. Thank you for the tips, and I appreciate the very.... constructive feedback.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
if (isPrime(i)) {
outputFile << i << endl;
}
}
outputFile.close();
cout << "You should now have the file." << endl;
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
Related
FizzBuzz program. The user enters numbers separated by a comma. The program reads input and lets the computer know if divisible by 3, 5 or both. When the user enters 15,5,30, the program will only output the first number, 15 and stops there. What am I doing wrong?
void processVector(vector<int> intVector)
{
bool loop;
for (int i = 0; i < intVector.size(); i++)
{
loop = true;
}
}
int main()
{
cout << "Welcome to the FizzBuzz program!" << endl;
cout << "This program will check if the number you enter is divisable by
3, 5, or both." << endl;
cout << "Please enter an array of numbers separated by a comma like so,
5,10,15" << endl;
cin >> userArray;
vector<int> loadVector(string inputString);
istringstream iss(userArray);
vector <int> v;
int i;
while (iss >> i);
{
v.push_back(i);
if (iss.peek() == ',')
iss.ignore();
if (i % 15 == 0)
{
cout << "Number " << i << " - FizzBuzz!" << endl;
}
else if (i % 3 == 0)
{
cout << "Number " << i << " Fizz!" << endl;
}
else if (i % 5 == 0)
{
cout << "Number " << i << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
system("pause");
}
Here is how I would approach the problem:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
std::cout << "Please enter your numbers seperated by a comma (5, 3, 5, 98, 278, 42): ";
std::string userString;
std::getline(std::cin, userString);
std::vector<int> numberV;
size_t j = 0; // beginning of number
for(size_t i = 0; i < userString.size(); i++){
if((userString[i] == ',') || (i == userString.size() -1)){ // could also use strncmp
numberV.push_back(std::stoi(userString.substr(j, i))); // stoi stands for string to int, and .substr(start, end) creates a new string at the start location and ending at the end location
j = i + 1;
}
}
for(size_t n = 0; n < numberV.size(); n++){
std::cout << numberV[n] << std::endl;
}
return(0);
}
This should give you a method to solve the problem (without handling the fizzbuzz part of your program) that I personally find simpler.
The basic form for using functions is:
<return type> <function_name(<inputs)>{
stuff
};
So, a basic function that takes a string and returns a vector (what you are wanting) would be:
std::vector myStringToVector(std::string inputString){
std::vector V;
// your code (see the prior example for one method of doing this)
return(V);
};
It also looks like they want a separate function for outputting your vector values, this could look something like:
void myVectorPrint(std::vector inputVector){
// your code (see prior example for a method of printing out a vector)
};
Thank you #Aaron for the help. Here is the finished code and it works great!
I had to take a little more time researching a few things and trying to understand which order and what to put where in terms of the functions and how to call them. I appreciate all the help as I said I am a noob.
#include "stdafx.h"
#include <iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
vector<int> loadVector(string inputString)
{
stringstream ss(inputString);
vector <int> numberV;
int n;
size_t j = 0; // beginning of number
for (size_t n = 0; n < inputString.size(); n++)
{
if ((inputString[n] == ',') || (n == inputString.size() - 1))
{
numberV.push_back(std::stoi(inputString.substr(j, n)));
j = n + 1;
}
}
return numberV;
}
void processVector(vector<int> intVector)
{
for (int i = 0; i < intVector.size(); i++)
{
int n = intVector.at(i);
if (n % 15 == 0)
{
cout << "Number " << n << " - FizzBuzz!" << endl;
}
else if (n % 3 == 0)
{
cout << "Number " << n << " Fizz!" << endl;
}
else if (n % 5 == 0)
{
cout << "Number " << n << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
}
int main()
{
cout << "Welcome to the FizzBuzz program." << endl
<< "Please enter an array of numbers separated by comma's (5, 10, 15)"
<< endl;
string inputString;
getline(cin, inputString);
try
{
vector<int> intVector = loadVector(inputString);
processVector(intVector);
}
catch (const exception& e)
{
cout << "Exception caught: '" << e.what() << "'!;" << endl;
}
system("pause");
return 0;
}
I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input
Hi guys here is my functional code but it does not works properly it should do read numbers from input.txt and count the sum of even,odd numbers in each line then conjunction of prime numbers( which does correctly) and also copy all numbers which are prime to the output.txt
here is my code the problem is : it copies also numbers which are not prime numbers. Thanks a lot !!!
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream read;
read.open("input.txt");
ofstream write;
write.open("output.txt");
string line;
int even, odd, primeXprime;
if(read.fail())
cout << "Cant open input.txt" << endl;
int x, p = 0;
if(read.is_open())
{
while(read, line)
{
even = odd = 0;
primeXprime = 1;
istringstream sRead(line);
while(sRead >> x)
{
if(x % 2 == 0)
even += x;
if(x % 2 != 0)
odd += x;
for(int i = 2; i <= x; i++)
{
if(x % i == 0)
p++;
if(p == 2)
{
primeXprime *= x;
write << x << " ";
p = 0;
}
else
break;
}
}
cout << "Sum of even numbers are: " << even << endl;
cout << "Sum of odd numbers are: " << odd << endl;
cout << "Sum of prime numbers are: " << primeXprime << endl;
cout << endl;
}
read.close();
write.close();
system("pause");
return 0;
}
}
Problem is with your Primality Testing algorithm , You cannot determine a number is prime or not until you divide it by all the numbers in the range [2,Sqrt(n)]
In line "if(p == 2)" you are assuming that it wont be divided by any number later on in the range .
Replace your entire for loop by
for(int i = 1; i < x; i++)
{
if(x % i == 0)
p++;
}
if(p < 2)
{
primeXprime *= x;
write << x << " ";
}
p = 0;
This is a program that is suppose to compare an answer sheet (which is a .txt file) to user input. Meaning I'm comparing two arrays but I'm having a PITA time making it work. It complies just fine but it just does not compare the user input array to the .txt file array and counts everything as wrong even when I manually put in the correct answers on the user input side. Any advice or suggestions would be appreciated! PS: I cannot use vectors, only arrays. That's not a personal choice but a requirement.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int CHOICE = 20;
const char KEY = 20;
char correctAnswers[KEY];
char A, B, C, D;
char userAnswers[CHOICE];
char rightOrWrong[CHOICE];
int totalMissed;
int sum = 0;
int count = 0;
ifstream inputFile;
inputFile.open("CorrectAnswers.txt");
while (count < KEY && inputFile >> correctAnswers[count])
count++;
inputFile.close();
for (int qst = 0; qst < 20; qst++)
{
cout << "Please put an answer for the question: " << endl;
cin >> userAnswers[qst];
cout << endl;
if (userAnswers[qst] == correctAnswers[qst])
{
rightOrWrong[qst] = 'C';
}
else
{
rightOrWrong[qst] = 'I';
}
}
for (int qst = 0; qst < 20; qst++)
{
if (rightOrWrong[qst] == 'C')
{
sum += 1;
}
else
{
cout << "Answer #" << qst << " is not correct" << endl;
}
}
totalMissed = 20 - sum;
cout << "This is your final score: " << endl;
cout << "You missed " << (20 - sum) << "/20 of the questions" << endl;
cout << "You overall percentage is " << (sum / 20) << "%." << endl;
if (sum < 14 && sum >= 0)
{
cout << "You have not passed the exam. You must have a 70% or higher to pass. Study harder next time!" << endl;
}
else
{
cout << "Pat yourself on the back! You've passed the test!" << endl;
}
return 0;
}
I apologize if this looks crappily formatted, it doesn't look like this normally.
Ok I have been struggling with this code and I think I have it written out right but here is the rules from my teacher
1 = implies right Number, Right Place.
2 = implies right Number, Wrong Place.
0 = implies Wrong Number.
So the computer decides on 12345; the user guesses 11235; the computer should respond with 10221. Hint: Watch out for a double number like 11 when there is only one.
I have it where it does all of that except I can not get it to show a 0 when it is wrong can you please help me every single part is written except that part here is my code
// Programming 2
// Mastermind
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
struct fields{//the list of variables used in my program
int size = 5;;
int range = 9;
char lowest = '0';
string guess;
string answer;
int number;
int correct;
int position;
bool gameover = false;
};
void gameplay(fields & info);//declaring the function
int main()
{
fields game;
gameplay(game);//calling the function
system("pause");
return 0;
}
void gameplay(fields & info){//calling the structure into the function
srand(time(0));//to randomize number
info.answer = "";//getting the number
for (int i = 0; i < info.size; i++)
{
char ch = info.lowest + rand() % info.range;
info.answer += ch;
}
info.number = 1;
info.correct = 0;
info.position = 0;
while (!info.gameover)//using a while loop to let them go until they guess it
{
cout << "Guess #" << info.number << ": Enter 5 numbers that are '0' through '9': ";//asking them to guess
cout << info.answer;
cout << "\n";
cin >> info.guess;
if (info.guess == info.answer)//if the guess is right this will end the game
{
cout << "Right! It took you " << info.number << " move";
if (info.number != 1) cout << "s";
cout << "." << endl;
info.gameover = true;
}
int correctNumbers = 0;
for (char const &ch : info.guess) //seeing if there are numebrs in the guess that is in the answer
{
if (info.answer.find(ch) != string::npos)
{
++correctNumbers;
}
}
int const digits = 5;
int correctPositions = 0;
int correctPosition[digits];
int test = 0;
for (int i = 0; i < digits; ++i)//telling which numbers is correct and displaying the 2 or 0 for number is correct or number is wrong
{
if (info.answer[i] == info.guess[i])
{
++correctPositions;
}
if (info.answer[i] == info.guess[i]){
correctPosition[i] = 2;
cout << correctPosition[i];
}
if (correctPosition[i] != 2){
correctPosition[i] = 1;
cout << correctPosition[i];
}
if (correctPosition[i] != 2 && correctPosition[i] != 1)){
correctPosition[i] = 0;
cout << correctPosition[i];
}
}
cout << "\nYou have " << correctPositions << " numbers in the correct position " <<endl;
cout << "You have " << correctNumbers <<" correct numbers in the wrong position"<< endl;
}
cout << "GAME OVER\n\n";
}