I have a problem that is asking for me to write a C++ program using for loops with less than 3 “cout” statements in your code to print the following pattern (ignore the pipes, the asterisks wouldn't appear without them):
|*
|***
|*****
|*******
|*********
|*********
|*******
|*****
|***
|*
This is my code I used for a fibonacci generator and I feel like it might be similar. I am able to print the "*" symbol but not in horizontal lines. What I need most help with is reversing the output. As in if given number n, I want the series to go n numbers into the series and then back down to 0.
#include <iostream>
using namespace std;
int main()
{
int y = 1, sum = 1, n;
cout << "Enter the number of terms you want" << endl;
cin >> n;
cout << "First " << n << " terms are :- " << endl;
for (int x = 0; x < n; x++) {
cout << "\n" <<endl;
for (int i = 0; i < sum; i++) {
cout << "*" << endl;
}
sum = y + 2;
y = sum;
}
}
It seems this is a homework, so I give some hints instead of a full solution.
For printing the *s in one line, please note that << endl will end the line in the output, i.e. print a line break. (The same does << "\n" by the way.) Not every cout statement has to have an << endl at its end.
For reversing the fibonacci sequence, once you have the last number in the variable sum, just do the reverse computation (i.e. subtraction). This could be done in a second set of loops, however, since you should not use cout statements too often, you better reuse the same loop by using some additional variable holding the current state (i.e. if you are counting up or down) and using an if to decide which computation to do. (I read the requirements such that only the cout statements for printing the pattern count to the "less than three" = 2)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Tried several times yet still didnt manage to find my mistake: here is my program. i need to find the odd numbers from 1 and integer x and find the sum of them cubed.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x;
int i = 1;
int result;
cout <<" Enter the value for n" << endl;
cin >> x;
while (i >x)
if (i%2 == 0) {}
else {
result += pow(i,3);
i++;
}
cout << "The sum of odd integers cubes from " << i << " to " << x << "= " << result << endl;
return 0;
}
Minimally, you should change the compare in while
from
while (i > n)
to
while (i <= n)
There a many numbers where i will be greater than the number entered, n.
You didn't add in your curly brackets for the while loop.
while (i > x)
if (i%2 == 0) {}
needs to be:
while (i > x){
if (i % 2 == 0) {}
}
Plus what are you doing inside of that if statement? You should decrement x, to find if each number is odd.
Plus, your program ends early because i is 1 and if the user enters a number above 1, your while loop won't even run. You're telling the while loop to run ONLY when i is larger than x. Try changing it to less than:
from:
while (i > x){
to:
while (i < x){
Plus you're not doing anything with x. You want to decrement x, not add i. Although, I would recommend using a do-while loop. ( a dowhile loop does one iteration first before incrementation)
do{
if (x % 2 == 0) { // if the remainder of x/2 is 0, do this
x--;
cout << "Equal: " << x << endl;
}
if(x % 2 != 0) { //if the remainder of x/2 is not 0, do this.
temp = pow(x,3);
//you don't want to take the power of the added sum,
//you were taking the power 3 of x which was being added to.
//you want to add the sums of each power. So here we have temp, a
//temporary variable to store your addends.
result = result + temp;
cout << "Not equal, temp:" << temp <<endl;
cout << "Result: "<< result << endl;
x--; //you didn't have a decrement, you need to bring x eventually down to i if you want the loop to end, or even look through all of the numbers
}
}
while (i < x);
//You have to have this semi colon here for the compiler to know its a do-while.
cout << "The sum of odd integers cubes from " << i << " to " << userVar
<< " = " << result << endl;
return 0;
}
note: if-else statements are for flow control, its like true and false, one or the other, so that your data will flow somewhere. I used two if statements because I want to have complete control over the flow.
note2: It's ok to use:
using namespace std;
at first, but eventually you want to start learning what library each command is using. When you get into more complex programming, you start using commands from different libraries than the standard one.
I'm new here and this forum has been a great help! Unfortunately, I'm not able to find the answer to my issue here or anywhere else on the web. I was hoping some of you can give me some help or tips on how to go about this.
The program will generate random numbers based on the max limit and the amount of random numbers that will generate.
I'm also required to find the smallest, largest number, as well as the average from all the numbers generated in the loop. The average I can find using the sum/MAX_COUNT_NUM. Unfortunately, I am stuck finding the smallest and largest number. Been at this for the past 6 hours. Please help anyway you can. Thank you.
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main(){
int UP_MAX, MAX_COUNT_NUM, RAND_NUM, MIN_COUNT_NUM;
cout << "This program creates random numbers" << "\n" << "\n";
cout << "Enter the upper limit of all generated random numbers: ";
cin >> UP_MAX;
cout << "\n" << "\n";
cout << "Enter the count of random numbers: ";
cin >> MAX_COUNT_NUM;
cout << "\n" << "\n";
cout << "Creating " << MAX_COUNT_NUM << " random numbers from 1 to " << UP_MAX << ": " << "\n" << "\n";
MIN_COUNT_NUM = 1;
int LARGE = 0;
int SMALL = 0;
for (; MAX_COUNT_NUM >= MIN_COUNT_NUM; MIN_COUNT_NUM++)
{
RAND_NUM = rand() % UP_MAX + 1;
cout << setw(8) << RAND_NUM;
if (RAND_NUM < SMALL)
{
SMALL = UP_MAX + 1;
}
if (RAND_NUM > LARGE)
{
LARGE = RAND_NUM;
}
}
Unfortunately, I need to do this without arrays and vectors. In my head, I'm thinking it should work as well but it doesn't. The largest number comes out fine, but the smallest comes out as 0 which makes me scratch my head.
I'm taking a beginners course and this got me stumped, so my way of thinking may be off beat. If there are any other tips you can provide, I definitely appreciate it.
The problem is with the initial values that you picked for LARGE and SMALL: you set both of them to 0, which is incorrect: you should set them both to the first random number that you generate.
Alternatively, you can set SMALL to the largest possible int, and LARGE to the smallest possible int. Use <limits> header and std::numeric_limits<int> class.
Note: SMALL = UP_MAX + 1; should be SMALL = RAND_NUM;
Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.
For an assignment in my C++ programming class, I was given the following code. The assignment simply says "This program should give the AND of the following numbers" Was wondering if could get clarification on the meaning. I have an idea but I think I still need a bit of advice. The code was provided jumbled on purpose which I had to clear up. Here is is cleaned up:
// Question2
// This program should give the AND of the inputted numbers.
#include <iostream>
//**Needs namespace statement to directly access cin and cout without using std::
using namespace std;
//**Divided up statements that are running together for better readability
//**Used more spacing in between characters and lines to further increase readability
////void main()
//**Main function should include int as datatype; main is not typically defined as a void function
int main()
{
int i;
int k;
//**Changed spacing to properly enclose entire string
cout << "Enter 0 (false) or 1 (true) for the first value: " << endl;
cin >> i;
cout<< "Enter 0 (false) or 1 (true) for the second value: " << endl;
cin >> k;
//**Spaced out characters and separated couts by lines
//**to help with readability
cout << "AND" << endl;
cout << "k\t| 0\t| 1" << endl;
cout << "---\t| ---\t| ---" << endl;
cout << "0\t| 0\t| 0" << endl;
cout << "1\t| 0\t| 1" << endl;
if(i==1&k==1)
cout <<"Result is TRUE" << endl;
else cout << "Result is FALSE" <<endl;
//**Main function typically includes return statement of 0 to end program execution
return 0;
}
Every number has a binary representation. They're asking for the logical and of the bits. Look up the & operator.
'&' is a bitwise and, which means it takes the binary representation of two numbers and compares each bit in the first number against the bit in the same position on the second. If both are 1, the resultant bit in the same position in the output number is 1, otherwise the bit is zero. if (i&k) would have the same result (assuming the input was always 0 or 1), but anyway your if statement compares whether the first bit is 0 or 1, and if both are 1 returns one.
the AND gate(output) will be true only if both inputs are true(1)
true if i==1 && k==1
false if i==0 && k==0,i==1 && k==0,i==0 && k==1.
Hi I'm not sure if this is the right place to ask this question.
Anyway I have written this code to parse a molecule formula and split it into atoms and amount of each atoms.
For instance if I input "H2O" I will for the atom array get {"H", "O"} and in the amount array I will get {2, 1}. I haven't taken account for amount that is larger than 9, since I don't think there are molecule which can bind to something that is larger than 8.
Anyway I'm quite newbie, so I wonder if this piece of code can be made better?
string formula = "H2O";
int no, k = 0, a = 0;
string atom[10];
int amount[10];
bool flag = true;
stringstream ss(formula);
for(int i = 0; i < formula.size(); ++i)
{
no = atoi(&formula[i]);
if(no == 0 && (flag || islower(formula[i]) ) )
{
cout << "k = " << k << endl;
atom[k] += formula[i];
flag = false;
cout << "FOO1 " << atom[k] << endl;
amount[a] = 1;
}
else if(no != 0)
{
amount[a] = no;
cout << "FOO2 " << amount[a] << endl;
a++;
flag = true;
k++;
}
else
{
k++;
a++;
atom[k] = formula[i];
cout << "FOO3 " << atom[k] << endl;
amount[a] = 1;
flag = false;
}
cout << no << endl;
}
Have you considered an approach with regular expressions? Do you have access to Boost or TR1 regular expressions? An individual atom and its count can easily be represented as:
(after edits based on comments)
([A-Z][a-z]{0,2})([0-9]*)
Then you just need to repeatedly find this pattern in your input string and extract the different parts.
There are many potential improvements that could be made, of course. But as a newbie, I guess you only want the immediate ones. The first improvement is to change this from a program that has a hard coded formula to a program that reads a formula from the user. Then try testing yout program by inputting different formulae, and check that the output is correct.
What if you modified it to be like this algorithm? This would maybe be less code, but would definitely be more clear:
// while not at end of input
// gather an uppercase letter
// gather any lowercase letters
// gather any numbers
// set the element in your array
This could be implemented with 3 very simple loops inside of your main loop, and would make your intentions to future maintainers much more obvious.