I'm working on a project to print out a table of exponential numbers using nested for-loops. Users specify the number of rows to print and the number of powers. For example, if the users specifies 2 rows and 3 powers, the program should print 1,1,1 and 2,4,9 (2^1,2,3 etc). I should note this is for class and we aren't allowed to use cmath, otherwise I would use pow(). I can't seem to figure out the correct function in a nested for loop that can change both values of the base and the exponent. Here's what I have so far. Thanks for your help!
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
for (int q = 1; q <= i; q++)
{
a = (q * q); //This only works for static numbers...
cout << setw(8) << a;
}
cout << endl;
}
}
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
int a = 1;
for (int q = 1; q <= r; q++)
{
a = (a * i);
cout << setw(8) << a;
}
cout << endl;
}
Several things to note. First, you can compute the powers by maintaining the variable a and multiplying it by i for each power. Also, I think you want the upper bound on your second loop to be r and not i.
You need couple to change the way accumulate the values of raising a number to a power.
Also, you are using the wrong variable to end the loop in the inner for-loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
a = 1; // Start with 1
for (int q = 1; q <= p; q++) // That needs to <= p, not <= i
{
a *= i; // Multiply it by i get the value of i^q
cout << setw(8) << a;
}
cout << endl;
}
}
Related
I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9
Looking for some insight on how to calculate a sum of user inputted numbers within a for statement and print it after the for loop has been completed.
So far I have this code:
//this code will sort 2 numbers then print them in ascending order and
before exiting, add them all together
// then average them
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z, sort1, sort2;
for (n=0;n<3;n++){
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
if (m>z){
sort1 = z;
sort2 = m;
}
else{
sort1 = m;
sort2 = z;
}
cout << sort1 << sort2 << endl;
}
int sum = m+z;
int sum2 = m+z+sum;
float sum3= m+z+sum2;
cout << " sum of all numbers entered: " << sum << endl;
cout << " average of the numberes entered: " << sum3 /6 << endl;
}
So I know that the sum function i have is incorrect, it only evaluates the last m+z entered by the user and not the others. If i put the sum function in the loop, once it breaks, it dumps all information within the loop rendering the sum value obsolete. Wondering if there's another way to achieve the sum function within the loop but only print once outside the loop.
Are there any other loops that don't delete information within the loop that you can extract outside?
All loops in C++ are scoped, that means that any variables declared within a scope are not accessible outside (of the scope) nor will they persist to the next iteration.
int sum = 0; // declare sum outside of loop
for(int n = 0; 0 < 3; n++)
{
int m, z; // These will be reset every iteration of the for loop
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
/*
Sort and print goes here...
*/
sum += m + z;
}
std::cout << "The sum: " << sum <<std::endl;
#include<iostream>
using namespace std;
int main()
{
int total = 0, i, j, sort1, sort2;
//this For-Loop will loop three times, every time getting two new
//integer from the user
for (int c = 0; c < 3; c++) {
cout << "Enter two integers ( n n ): ";
cin >> i;
cin >> j;
//This will compare if first number is bigger than the second one. If it
//is, then second number is the smallest
if (i > j) {
sort1 = j;
sort2 = i;
}
else {
sort1 = i;
sort2 = j;
}
cout << "The numbers are: " << sort1 << " and " << sort2 << endl;
//This statement will add into the variable total, the sum of both numbers entered before doing another loop around
total += i + j;
}
cout << "The sum of all integers entered is: " << total << endl;
system("pause");
return 0;
}
My program has to count how many numbers in a range are even and how many of them are odd but I can't seem to figure it out.It kinda works
but when I put numbers in it spouts out nonsense. I'm an extreme nooob when it comes to programing, I think that the problem has to be at line 21 for (i=n; i<=m; i++) { ?
But I'm not sure. I have a programing book but it does not help much,maybe someone can help?
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
Assuming you mean even and odd numbers your problem lies in this code:
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}
What you might want do to do is add 1 (instead of whatever i is):
for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}
Also I'd suggest using better variable names, for example even and odd instead of a and b and so on. It makes code easier to understand for everybody, even for you.
Just a little more tips. Assigning variables as soon as you declare them is good practice:
int m = 0;
You can declare variable inside of for loop, and in your case there is no need to declare it out of it:
for (int i = n; i <= m; ++i) { ... }
Example how it can change look and clarity of your code:
#include <iostream>
using namespace std;
int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;
cout << "Enter a number that begins interval: ";
cin >> from;
cout << "Enter a number that ends interval: ";
cin >> to;
for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}
cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;
return 0; // don't forget this! main is function returning int so it should return something
}
Ok, so as per the new clarification the following should work
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a++;
}else {
b++;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
So the following changes were done:
The for loop was closed
a = a + i or b = b + i was wrong as you are adding the counter value to the count which should be a++ or b++. Changed that also
The last two lines where you are showing your result was out of the main method, brought them inside the main method
Hope you find this useful.
You don't need to use loop to count even and odd numbers in a range.
#include <iostream>
int main ()
{
int n,m,even,count;
std::cin >> n >> m;
count=m-n+1;
even=(count>>1)+(count&1 && !(n&1));
std::cout << "Even numbers: " << even << std::endl;
std::cout << "Odd numbers: " << count-even << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
cout << " even : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 == 0)
cout << i << " ";
}
cout << " odd : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 != 0)
cout << i << " ";
}
return 0;
}
//input n = 5
// output is even : 2 4 6 8 10
// odd : 1 3 5 7 9
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a = 0;
b = 0;
for (i = n; i < = m; i++) {
if (i%2 == 0){
a = a + 1;
} else {
b = b + 1;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
Not sure why you are looping through all the elements (half of them are going to be even and the other half odd). The only case where you have to consider when the interval length is not divisible by two.
using namespace std;
int main()
{
int n;
int m;
int x;
int odds;
int evens;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
cout << n << " " << m << endl;
x = m - n + 1;
odds = x / 2;
evens = odds;
if (x % 2 != 0) {
if (n % 2 == 0) {
evens++;
} else {
odds++;
}
}
cout << " even numbers: " << evens << endl;
cout << " odd numbers: " << odds << endl;
}
This is a more readable version of #Lassie's answer
So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs
I would like to analyze the complexity of my code algorithm.Therefore,i must have 2 different programs giving the same functions to allow me to start off.
Currently this is my own code.
I'm not sure if it is allowed that i would like to have someone that could volunteer his own way code to compute summation of factorial for me as the 2nd program code.
Preferrably a nested loop.
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++)
{
c = c * i;
a = a + c;
}
cout << "The sum of the factorials is " << a << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
static const int results[] = {
0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113,
4037913, 43954713, 522956313
};
cout << "The sum of the factorials is " << results[val < 0 ? 0 : val] << endl;
system("pause");
return 0;
}
Note that I replicated the defect in the original program which causes it to return the incorrect value if the user enters 0.
This alternate version assumes 32-bit integers because it takes advantage of overflow behavior. Extending to 64-bit integers is left as an exercise.
I do not understand what you do with another nested way but i hope this can help...
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++){
c *= i;
a += c;
}
int c2=1;
for (i = val; i > 1; i--){
c2*=i;
c2++;
}
cout << "The sum of the factorials is " << a << endl;
cout << "The sum of the factorials is " << c2 << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int suma = 0;
int n = 0;
cout << "Sum of factorials\n";
cout << "-------------------------------\n";
cout << "Insert number of n: ";
cin >> n;
int i = 1;
while (i <= n)
{
int factorial = 1;
for(int j=1; j<=i; j++)
{
factorial = factorial * j;
}
suma += factorial;
i++;
}
cout << "Sum of factorials is: " << suma;
system("pause");
return 0;
}