How to count how many times a loop has been executed my code doesn't work as I expected it,
find the primes numbers before n number input by user and display them and count how many
numbers are in total
ex.
number input lets say 7,
and there are 3 numbers before 7
so it displays 2,3,5,7 and there are 3 prime numbers before 7
#include <iostream>
using namespace std;
int main()
{
int n, i, k;
int counter = 0;
bool isprime;
cout << "Enter a positive integer n: ";
cin >> n;
for(int k = 2; k <= n; k++)
{
isprime = true;
for(int i = 2; i <= k - 1; i++)
if(k%i == 0)
{
isprime = false;
}
if(isprime)
cout << k << "\t";}
cout << "\nThere are " << counter << " primes less than " << n;
return 0;
}
In your example, counter is never modified from its initial value. Try having it count what you want to count.
Added: ...
BTW. Prefer
for (i = 0; i < n; ++i)
for looping. The "i < n" is more idiomatic (easier to read) and the ++i normally will be more efficient than i++.
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int main()
{
int num;
int count = 0;
cout << "Enter your range: ";
cin >> num;
for(int i = 1; i <= num; i++)
{
count = 0;
for(int j = 2; j <= sqrt(i); j++)
{
if(i % j == 0)
{
count++;
break;
}
}
if(count == 0 && i != 1)
cout << i << " ";
}
cout << endl;
}
This will increase the count variable every time there's a prime number.
#include <iostream>
using namespace std;
int main()
{
int n, i, k;
int counter = 0;
bool isprime;
cout << "Enter a positive integer n: ";
cin >> n;
for(int k = 2; k <= n; k++)
{
isprime = true;
for(int i = 2; i <= k - 1; i++)
if(k%i == 0)
{
isprime = false;
}
if(isprime)
{
cout << k << "\t";
counter++;
}
}
cout << "\nThere are " << counter - 1<< " primes less than " << n;
return 0;
}
As said above counter is not incremented.
You should make a function
isPrime?(int n)
{
int sqrt_n = sqrt(n)
for(int i = 2; i <= sqrt_n; i++){ //You could check only to sqrt(n)
if(n%i == 0)
{
return false;
}
}
return true;
}
And then you could use that function as follow:
int main()
{
int n, i, k;
int counter = 0;
cout << "Enter a positive integer n: ";
cin >> n;
for(int k = 2; k <= n; k++)
{
if(isPrime?(k)) {
counter++;
cout << k << "\t";
}
cout << "\nThere are " << counter << " primes less than " << n;
return 0;
}
Related
I am trying to get the height of these slashes to be a certain length based on input. So far, I have:
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
}
I need it to then reverse and go back.
It prints:
//
////
//////
If the user entered 3.
It should print:
//
////
//////
////
//
Can anyone lead me in the right direction? I am new to cpp.
You can use a different kind of loop and add a bool variable to track when the program have reached "n". Then, after the program reaches "n", it sets the bool variable to true and starts to substract until i equals 0
Code below, read comments and ask if you have any further questions:
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You have entered: " << n << "\n";
int i = 1;
bool reachedN = false; // tells if [i] has reached [n]
while (i != 0)
{
// Print required slashes
for (int j = 1; j <= i; j++)
{
cout << "//";
}
cout << '\n'; // new line
// Add until i == n, then substract
if (i == n)
{
reachedN = true;
}
if (reachedN)
{
--i;
}
else
{
++i;
}
}
}
If you enter 3, the output is the following:
This is one way to achieve that:
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
for (int i = n - 1; i > 0; i--) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
}
This is a shorter solution with only two for-loops.
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
n = n * 2 - 1;
int r = 0;
for (int j = 0; j < n; j++)
{
if (j > n / 2) r--;
else r++;
for (int i = 0; i < r; i++)
{
cout << '/' << '/';
}
cout << "\n";
}
return 0;
}
I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo
so i got this code.
int n;
int m=1;
int a=9;
cout<<"Enter N Number = ";
cin>>n;
n=n*2-1;
for(int y=1;y<=n;y++)
{
for(int x=1;x<=n;x++)
{
if(x==y+n/2 || x==y-n/2 || x==n-y+1-n/2 || x==n-y+1+n/2)
{
if(m<=9)
{
cout<<m++;
}
else if(m>9&&a>0)
{
a--;
cout<<a;
}
}
else
{
cout<<" ";
}
}
cout<<endl;
}
This is what i get :
Diamond Shape(Fail)
And what i expected is there's no number "0" on the bottom of the shape, so after it printed the number 1 its bounce back to number 2,3 and so on
pardon for my bad english
Do you want it to be like this?
Check this out!
I can code in Pascal, C++ and Java.
PS: I am not a native English speaker too.
First Answer: This is not the best answer, I will improve it tomorrow afternoon.
#include <iostream>
using namespace std;
int get() {
static int counter = 0;
static bool reverse = false;
!reverse ? counter++ : counter--;
if (counter==10 or counter==0) reverse = !reverse;
counter==10 ? counter = 8 : 0;
counter==0 ? counter = 2 : 0;
return counter;
}
int main() {
int number;
cout << "Enter N Number = ";
cin >> number;
//forward:
for (int i = 0; i < number; i++) {
for (int j = number-i-1; j > 0; j--)
cout << " ";
cout << get();
if (i!=0) {
for (int j = 0; j < i * 2 -1; j++) cout << " ";
cout << get();
}
cout << endl;
}
//backward:
for (int i = number-1; i > 0 ; i--) {
for (int j = number-i; j > 0; j--)
cout << " ";
cout << get();
if (i!=1) {
for (int j = i * 2 -3; j > 0; j--) cout << " ";
cout << get();
}
cout << endl;
}
return 0;
}
Second Answer: Improved loops
#include <iostream>
using namespace std;
int nextNumber() {
static int counter = 0;
static bool reverse = true;
!reverse ? counter++ : counter--;
if (counter==-1) counter=1;
if (counter==9 or counter==1) reverse = !reverse;
return counter;
}
int main() {
int number;
cout << "Enter N Number = ";
cin >> number;
int space = number;
int middle = -3;
for (int row = 0; row < number*2-1; row++) {
if(row<number) {
space--;
middle += 2;
}
else {
space++;
middle -= 2;
}
for (int i = 0; i < space; i++)
cout << " ";
cout << nextNumber();
if(row!=0 and row!=number*2-2) {
for (int i = 0; i < middle; i++)
cout << " ";
cout << nextNumber();
}
cout << endl;
}
return 0;
}
So, I am trying to implement this algorithm from our textbook.
I wrote this :
// Knapsack_memoryfunc.cpp : Defines the entry point for the console application.
//Solving Knapsack problem using dynamic programmig and Memory function
#include "stdafx.h"
#include "iostream"
#include "iomanip"
using namespace std;
int table[20][20] = { 0 };
int value, n, wt[20], val[20], max_wt;
// ---CONCERNED FUNCTION-----
int MNSack(int i, int j)
{
value = 0;
if (table[i][j] < 0)
if (j < wt[i])
value = MNSack(i - 1, j);
else
value = fmax(MNSack(i - 1, j), val[i] + MNSack(i - 1, j - wt[i]));
table[i][j] = value;
return table[i][j];
}
// --------------------------
void items_picked(int n, int max_wt)
{
cout << "\n Items picked : " << endl;
while (n > 0)
{
if (table[n][max_wt] == table[n - 1][max_wt]) // if value doesnot change in table column-wise, item isn't selected
n--; // n-- goes to next item
else // if it changes, it is selected
{
cout << " Item " << n << endl;
max_wt -= wt[n]; // removing weight from total available (max_wt)
n--; // next item
}
}
}
int main()
{
cout << " Enter the number of items : ";
cin >> n;
cout << " Enter the Maximum weight : ";
cin >> max_wt;
cout << endl;
for (int i = 1; i <= n; i++)
{
cout << " Enter weight and value of item " << i << " : ";
cin >> wt[i] >> val[i];
}
for (int i = 0; i <= n; i++)
for (int j = 0; j <= max_wt; j++)
table[i][j] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= max_wt; j++)
table[i][j] = -1;
cout << " Optimum value : " << MNSack(n, max_wt);
cout << " \n Table : \n";
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= max_wt; j++)
if (table[i][j] == -1)
cout << setw(5) << "-";
else
cout << setw(5) << table[i][j];
cout << endl;
}
items_picked(n, max_wt);
return 0;
}
Here is the question and output :
It seems like its correct on some places like optimum value, yet isn't fully acceptable.
I've tried to debug it, but its quite hard with recursive functions. Can someone please help?
int MNSack(int i, int j)
{
value = 0;
if (table[i][j] < 0)
{
if (j < wt[i])
value = MNSack(i - 1, j);
else
value = max(MNSack(i - 1, j), val[i] + MNSack(i - 1, j - wt[i]));
table[i][j] = value;
}
return table[i][j];
}
The problem comes in here. When your table item is greater or equal to 0, you will skip the recursion but still set the table item to 0, which won't be right if your table item is greater than 0.
You only need to update the table item when it needs to be change, so put it in the braces will correct this.
The bottom up solution.
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
int table[20][20] = { 0 };
int value, n, wt[20], val[20], max_wt;
cout << " Enter the number of items : ";
cin >> n;
cout << " Enter the Maximum weight : ";
cin >> max_wt;
cout << endl;
for (int i = 1; i <= n; i++)
{
cout << " Enter weight and value of item " << i << " : ";
cin >> wt[i] >> val[i];
}
// Initialization
for (int i = 0; i <= n; i++)
for (int j = 0; j <= max_wt; j++)
table[i][j] = 0;
// In practice, this can be skipped in a bottom up solution
for (int i = 1; i <= n; i++)
for (int j = 1; j <= max_wt; j++)
table[i][j] = -1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= max_wt; j++)
{
if (j < wt[i])
table[i][j] = table[i - 1][j];
else
table[i][j] = max(table[i - 1][j], val[i] + table[i - 1][j - wt[i]]);
}
}
cout << " Optimum value : " << table[n][max_wt] << endl;
cout << " \n Table : \n";
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= max_wt; j++)
if (table[i][j] == -1)
cout << setw(5) << "-";
else
cout << setw(5) << table[i][j];
cout << endl;
}
return 0;
}
You can see that this changes the recursion to a loop, and therefore avoids the global variables. It also makes the code simpler, so that you can avoid checking if the table item is valid (equal to -1 in your example).
The drawback of this solution is, it always traverses all the possible nodes. But it gains better coefficient per item because the recursion and double checking the table item costs more. Both top-down and bottom-up have the same order of complexity O(n^2), and it's hard to tell which one is faster.
I need help with getting this users input of an integer and retrieving the even numbers and displaying them with spaces.I already have the input processed into an array and have it reversed (thanks to stackoverflow) now need to extract the even numbers from the array and display them.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int evenNumbers(char even[], int num[], int indexing[]);
int main()
{
char integers[5];
int numbers[5];
int even[5] = {0,2,4,6,8};
int evens;
cout << "Please enter an integer and press <ENTER>: " << endl;
for (int j = 0; j < 5; j++)
cin >> integers[j];
for (int j = 0; j < 5; j++)
{
numbers[j]= integers[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << integers[j - 1] << " ";
}
cout << endl;
//having problems finding the even numbers and displaying the even numbers
//from the users input of integers, i have only learned how to display the
//subscript by a linear search
evens = evenNumbers(integers, numbers, even);
if (evens == -1)
cout << "There are no even numbers" << endl;
else
{
cout << "The even numbers are: " << (evens + 1) << endl;
}
system("pause");
return 0;
}
int evenNumbers(char even[], int num[], int indexing[])
{
int index = 0;
int position = -1;
bool found = false;
for (int j = 0; j < 5; j++)
{
num[j]= even[j] - '0';
}
while (index < 5)
{
if (num[index] == indexing[index])
{
found = true;
position = index;
}
index++;
}
return position;
}
If you want to display the even numbers from the array integers you can use a simple for loop and if statement:
for(int i = 4; i >= 0; i--)
{
if(integers[i] % 2 == 0)
cout << integers[i] << " ";
}
Your approach is all wrong, you can't detect even numbers by searching a list, you need a mathematical test for evenness. Write a function called is_even which tests one number and returns true if it is even and false if it is not. Then you can use that function, very simply, like this
for (int j = 0; j < 5; j++)
{
if (is_even(integers[j]))
cout << integers[j] << " ";
}
cout << endl;
Now you just need to write the is_even function.
void evennumbers(int num[])
{
for(int i=0;i<5;i++)
{
if(num[i]%2==0)
cout<<num[i]<<" ";
}
}
And avoid taking input to char what if user enters a number with more than one digit
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void validNum(char valid[]);
void reverseNum(char rev[], int num2[]);
void evenNumbers(char even[], int num3[]);
void oddNumbers(char odd[], int num4[]);
int main()
{
char integer[5];
int number[5];
cout << "Your number is: ";
validNum(integer);
cout << "Your number in reverse is: ";
reverseNum(integer, number);
cout << "Even numbers: ";
evenNumbers(integer, number);
cout << endl;
cout << "Odd numbers: ";
oddNumbers(integer, number);
cout << endl;
system("pause");
return 0;
}
void validNum(char valid[])
{
char ch;
cout << "Please enter an integer and press <ENTER>: " << endl;
ch = cin.get;
while (ch < 0 || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
cout << "ERROR: Please enter a positive integer and press <ENTER>: ";
for (int i = 0; i < 5; i++)
cin >> valid[i];
}
for (int j = 0; j < 5; j++)
{
cout << valid[j] - '0';
}
}
void reverseNum(char rev[], int num2[])
{
for (int j = 0; j < 5; j++)
{
num2[j]= rev[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << rev[j - 1]<< " ";
}
cout << endl;
}
void evenNumbers(char even[], int num3[])
{
for (int i = 0; i < 5; i++)
{
if (even[i] % 2 == 0)
{
cout << num3[i] << " ";
}
}
}
void oddNumbers(char odd[], int num4[])
{
for (int i = 0; i < 5; i++)
{
if (odd[i] % 2 == 1)
{
cout << num4[i] << " ";
}
}
}