Number triangle using while loops - c++

I'm having trouble with my C++ programming class homework.
Here is the assignment:
Write a program which reads in the number of rows and prints 'n' rows
of digits.
1
12
123
1234
12345
where the i’th row is 1234 . . . k where k = i mod 10. If a row
has more than 10 digits, the digit after 9 should start again from 0.
For instance, if the number of rows is 15, the output should be: 1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int rows(0);
int i(0);
int j(0);
cout << "Enter number of rows: ";
cin >> rows;
int k=rows;
i=1;
while (i <= rows)
{
j=1;
while(j <= i)
{
cout << j;
j++;
}
cout << endl ;
i++;
}
return (0);
}
This works perfectly until I get to the 10th row. I'm not sure how to get the counter to reset back to 0 and go 1-9 again. I'm guessing an if statement, but I don't know how to correctly implement it. Any help would be greatly appreciated.

Using cout << j%10 will always print the ones digit of whatever j is equal to. So when j = 10, cout << j%10 will print 0, etc.

To expand on the other answer a bit:
% is referred to as the remainder operator. It is also sometimes called "modulo" or "modulus". It returns the remainder of the first argument divided by the second argument. So for this situation, since you want the number to be between 0 and 9, consider what happens when you have n % 10.
8 / 10 == 0 remainder 8
9 / 10 == 0 remainder 9
10 / 10 == 1 remainder 0
11 / 10 == 1 remainder 1
12 / 10 == 1 remainder 2
Etc.
In C++, as in most programming languages, you typically start counting at 0 and you exclude the final number in your range. So if you had n % 56, your output starting at 0 would go up to 55, and then reset to 0 again. The classical argument for this was written by Dijkstra:
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

Related

C++ How can I insert another loop or method to make 100 equivalent to 541?

My goal is to display the first list of prime numbers depending on user's input, when the user input 10, the program should display first 10 prime numbers which are 2 3 5 7 11 13 17 19 23 29. I'm thinking of having generated list from 2 which is the first prime number to 541 which is the 100th prime number then if the user input for example 100 then it will be equivalent to 2 upto 541. Will my algorithm works? currently I'm able to display prime numbers from 2 - 541 and stucked on implementing another loop for 1-100 input.
#include <iostream>
using namespace std;
int main() {
int N, counter, i, j, isPrime, n;
cout << "List of prime numbers from 1-100: ";
cin >> N; // if the user input 10 then the first 10 prime numbers are "2 3 5 7 11 13 17 19 23 29"
// list of prime from 2-541 (or first list from 1-100 prime numbers)
for (i = 2; i <= 541; i++) {
isPrime = 0;
for (j = 2; j <= i/2; j++) {
if (i % j == 0) {
isPrime = 1;
break;
}
}
if (isPrime == 0 && N != 101)
cout << i << " ";
}
}
Your current algorithm doesn't work, because N is never modified. If the user inputs 101 then nothing will be printed, because if (isPrime == 0 && N != 101) will always be false. If the user inputs anything else then it will always print the first 100 primes.
The key idea will be to count how many primes were found and break after the Nth prime. Or count down, how many primes we still need t ofind. The rough outline will be as follows:
for (i = 2; N > 0; i++) { // Loop as long as we need to find more primes
...
if(isPrime == 0) {
std::cout << ...
N--; // <- Found one prime, N-1 to go
}
}

Conversion of Decimal to Binary number with all the test Cases

Here's my Implementation i take the number and put it into the stack by doing mathematical calculation ... but it's not producing correct output even my logic regarding the problem is correct ...
Please detect what is wrong in my implementation. It's competitive programming Question asked by two companies in my College . So, please help me to correct the implementation....
I only want to know what is wrong with my implementation .....
Actual Question:
Input:
The first line of input contains an integer T denoting the number of test cases. There will be a single line for each testcase which contains N.
Output:
Print all binary numbers with decimal values from 1 to N in a single line.
Constraints:
1 ≤ T ≤ 106
1 ≤ N ≤ 106
Example:
Input:
2
2
5
Output:
1 10
1 10 11 100 101
Explanation:
Testcase 1: Binary numbers from 1 to 2 are 1 and 10.
This is the Required Output
Input:
2
2
5
Output:
1 10
1 10 11 100 101
And my output is :
For Input:
1
3
Your Output is:
Can any one here tell me the reason of incorrect output ..
#include<iostream>
#include <stack>
#include <queue>
using namespace std;
int main()
{
int T ;
cin>>T;
while(T--)
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
stack <int > s;
int num=i;
while(num>0)
{
s.push(num%2);
num=num/2 ;
}
for(int j=0;j<s.size();j++)
{
cout<<s.top();
s.pop();
}
cout<<" ";
}
cout<<endl;
}
return 0
This is the Required Output
Input:
2
2
5
Output:
1 10
1 10 11 100 101
And my output is :
For Input:
1
3
Your Output is:
Can any one here tell me the reason of incorrect output ..
The problem is here:
for(int j=0;j<s.size();j++)
{
cout<<s.top();
s.pop();
}
Suppose s has four elements.
On the first iteration, j is 0 and s.size() is 4.
On the second, j is 1 and s.size() is 3.
On the third, j is 2 and s.size() is 2, so the loop terminates.
That's two iterations instead of four.
Instead of counting the times you're going to pop, just pop until the stack is empty:
while (!s.empty())
{
cout << s.top();
s.pop();
}

Algorithm for Combinations of given numbers with repetition? C++

So I N - numbers I have to input, and I got M - numbers of places for those numbers and I need to find all combinations with repetition of given numbers.
Here is example:
Let's say that N is 3(I Have to input 3 numbers), and M is 4.
For example let's input numbers: 6 11 and 533.
This should be result
6,6,6,6
6,6,6,11
6,6,6,533
6,6,11,6
...
533,533,533,533
I know how to do that manualy when I know how much is N and M:
In example where N is 3 and M is 4:
int main()
{
int N = 3;
int M = 4;
int *numbers = new int[N + 1];
for (int i = 0; i < N; i++)
cin >> numbers[i];
for (int a = 0; a < N; a++)
for (int b = 0; b < N; b++)
for (int c = 0; c < N; c++)
for (int d = 0; d < N; d++)
{
cout << numbers[a] << " " << numbers[b] << " " << numbers[c] << " " << numbers[d] << endl;
}
return 0;
}
But how can I make algorithm so I can enter N and M via std::cin and I get correct resut?
Thanks.
First one short tip: don't use "new" or C-style arrays in C++ when we have RAII and much faster data structures.
For the solution to your problem I would suggest making separate function with recursion. You said you know how to do it manually so the first step in making it into algorithm is to tear down you manual solution step by step. For this problem when you solve it by hand you basically start with array of all first numbers and then for last position you just loop through available numbers. Then you go to the second last position and again loop through available numbers just now with the difference that for every number there you must also repeat the last spot number loop. Here is the recursion. For every "n"th position you must loop through available numbers and for every call the same function for "n+1"th number.
Here is a simplified solution, leaving out the input handling and exact print to keep code shorter and more focused on the problem:
#include <vector>
#include <iostream>
void printCombinations(const std::vector<int>& numbers, unsigned size, std::vector<int>& line) {
for (unsigned i = 0; i < numbers.size(); i++) {
line.push_back(numbers[i]);
if (size <= 1) { // Condition that prevents infinite loop in recursion
for (const auto& j : line)
std::cout << j << ","; // Simplified print to keep code shorter
std::cout << std::endl;
line.erase(line.end() - 1);
} else {
printCombinations(numbers, size - 1, line); // Recursion happens here
line.erase(line.end() - 1);
}
}
}
int main() {
std::vector<int> numbers = {6, 11, 533};
unsigned size = 4;
std::vector<int> line;
printCombinations(numbers, size, line);
return 0;
}
If you have any questions feel free to ask.
Totally there is no need for recursion here. This is a typical job for dynamic programming. Just get the first solution right for n = 1 (1 slot is available) which means the answer is [[6],[11],[533]] and then move on one by one by relying on the one previously memoized solution.
Sorry that i am not fluent in C, yet in JS this is the solution. I hope it helps.
function combosOfN(a,n){
var res = {};
for(var i = 1; i <= n; i++) res[i] = res[i-1] ? res[i-1].reduce((r,e) => r.concat(a.map(n => e.concat(n))),[])
: a.map(e => [e]);
return res[n];
}
var arr = [6,11,533],
n = 4;
console.log(JSON.stringify(combosOfN(arr,n)));
Normally the easiest way to do dynamic nested for loops is to create your own stack and use recursion.
#include <iostream>
#include <vector>
void printCombinations(int sampleCount, const std::vector<int>& options, std::vector<int>& numbersToPrint) {
if (numbersToPrint.size() == sampleCount) {
// got all the numbers we need, print them.
for (int number : numbersToPrint) {
std::cout << number << " ";
}
std::cout << "\n";
}
else {
// Add a new number, iterate over all possibilities
numbersToPrint.push_back(0);
for (int number : options) {
numbersToPrint.back() = number;
printCombinations(sampleCount, options, numbersToPrint);
}
numbersToPrint.pop_back();
}
}
void printCombinations(int sampleCount, const std::vector<int>& options) {
std::vector<int> stack;
printCombinations(sampleCount, options, stack);
}
int main()
{
printCombinations(3, {1,2,3});
}
output
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
Here is an algorithm to solve this, that does't use recursion.
Let's say n=2 and m=3. Consider the following sequence that corresponds to these values:
000
001
010
011
100
101
110
111
The meaning of this is that when you see a 0 you take the first number, and when you see a 1 you take the second number. So given the input numbers [5, 7], then 000 = 555, 001=557, 010=575 etc.
The sequence above looks identical to representing numbers from 0 to 7 in base 2. Basically, if you go from 0 to 7 and represent the numbers in base 2, you have the sequence above.
If you take n=3, m=4 then you need to work in base 3:
0000
0001
0002
0010
0011
0012
....
So you go over all the numbers from 0 to 63 (4^3-1), represent them in base 3 and follow the coding: 0 = first number, 1 = second number, 2 = third number and 3 = fourth number.
For the general case, you go from 0 to M^N-1, represent each number in base N, and apply the coding 0 = first number, etc.
Here is some sample code:
#include <stdio.h>
#include <math.h>
void convert_to_base(int number, char result[], int base, int number_of_digits) {
for (int i = number_of_digits - 1; i >= 0; i--) {
int remainder = number % base;
number = number / base;
result[i] = '0' + remainder;
}
}
int main() {
int n = 2, m = 3;
int num = pow(n, m) - 1;
for (int i = 0; i <= num; i++) {
char str[33];
convert_to_base(i, str, n, m);
printf("%s\n", str);
}
return 0;
}
Output:
000
001
010
011
100
101
110
111

How to make my output have space(even and odd number )

#include < stdio.h >
#include < conio.h >
#define BILMAX 10
int main()
{
int num[BILMAX],i;
printf("insert 10 number and separated by space:\n");
for (i = 0;i<10;i++)
{
scanf("%d",&num[i]);}
printf("\n\nEven Number : \n");
for(i = 0; i < 10; i++)
{
if(num[i] % 2==0)
printf("%d",num[i]);
}
printf("\n\nOdd Number : \n");
for(i = 0;i < 10; i++)
{
if(num[i] % 2 !=0)
printf("%d",num[i]);
}
getch();
return 0;
}
my output is like this
insert 10 number and separated by space:
1 2 3 4 5 6 7 8 9 10
Even Number:
246810
Odd Number:
13579
i want my output like this
insert 10 number and separated by space:
1 2 3 4 5 6 7 8 9 10
Even Number:
2 4 6 8 10
Odd Number:
1 3 5 7 9
i want my output have a space.
Please help
If you want to print a space after each number, change this line:
printf("%d",num[i]);
to
printf("%d ",num[i]);
Notice the space after %d.
Space an be inserted in a printf just by leaving a simple blank between quotes: " "
Just like printing your first program "Hello World" (space between Hello and World). Whatever you type inside the code it gets printed as it is.
For printing a space after each number do this
printf("%d ",num[i]);
Space can be provided by using escape sequence \t printf("%d \t",num[i]);

Help me add parameters to a function that draws a pattern

Please help me answer this question , void Function with parameters. I do not understand it very well
I want to write a program so that the user can input both characters that form the pattern
I need to define two (characters) variables which are (star) and (next), the statement must include three parameters – one that will be an (int) for the pattern
and two that will be (characters) for the character to display the pattern.
I have to change the function (drawpattern) to have three values parameters
an (int) parameter indicating the size of the pattern and two (characters) indicating the character that will be used to display the pattern .
input (4) for size, (Y) for the character to be used to start the pattern and (+) for the second and every alternate group
This is what I have done so far and I do not now if is okay:
#include <iostream>
using namespace std;
void drawPattern(int size, char start, char next)
{
for (int i = 0; i <= size; i++)
for (int j = 0; j <= size; j++)
{
if ((i / size) % 3 == 0)
if ((j / size3) % 3 == 0)
cout << '4';
else
cout << 'Y';
else
if ((j / size) % 3 == 0)
cout << '+';
else
cout << '4';
}
}
int main ()
{
int size;
char start, next;
cout << "Please enter number ( 4 ) for the size of the pattern : ";
cin >> size;
cout << " Now enter leter ( Y ) to start the pattern: ";
cin >> start;
cout << "Lastly enter the ( + ) for the other pattern: ";
cin >> size;
cout << " This is the output pattern: " << endl;
drawPattern(size, start, next);
return 0;
}
It looks like you are hard coding your output in the drawPattern function and ignoring the actual input from the user. I think you should probably replace the 'Y' and '+' with the corresponding argument passed to the function, since I'm pretty sure the professor would not be happy about hard coded values.
At line 11, you have a typo. It says size3 where it should say size.
You are also making a logical mistake.
This code
if ((i / size) % 3 == 0)
is wrong in concept. At least as the code is written now. Normally you would write like this:
if (i % 3 == 0)
This if statement will be true every third row. The % (modulu) calculates the remainder of the integer (whole number) division firstnumber / secondnumber. If you have a sequence of i going from 0 to 10, this is what i % 3 outputs
i: 0 1 2 3 4 5 6 7 8 9 10
i%3: 0 1 2 0 1 2 0 1 2 0 1
As you can see, i % 3 == 0 is true when i is divisible by 3.
Your code does something different. Let's say size = 10. Then you calculate the (integer) division i / size. Lastly you calculate (i / size) % 3. However i is always less than size, except at the last turn of the loop. Let's look at the values again:
i: 0 1 2 3 4 5 6 7 8 9 10
size: 10 10 10 10 10 10 10 10 10 10 10
i/size: 0 0 0 0 0 0 0 0 0 0 1
Since the value of i / size only changes once, the calculation (i / size) % 3 is meaningless.