Help me add parameters to a function that draws a pattern - c++

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.

Related

Having trouble printing a series

Here's the problem statement for what I'm supposed to do:
Write a program to print the following series up to the term input by user.
0, 1, 1, 2, 3, 5, 8, 13, ….
Where 0 is 1st term and 13 is 8th term.
Hint: 0, 1
0+1 = 1
0, 1, 1
1+1 = 2
0, 1, 1, 2
And here's my code:
int prev_i = 0;
cout << "Enter a number: " << endl;
cin >> number;
for (i = 0; i <= number; i++)
{
cout << prev_i + i << " ,";
prev_i = i;
}
I do get what is wrong with my code though. It adds i to prev_i then prev_i is set to i. So in the next iteration when i is 1 thats i + prev_i = 1 so now prev_i = 1 and here's the problem i is 2 now so i + prev_i = 3. And I really can't seem to figure out how to get 1 instead of 3 as the output here and so on.
Oh and don't worry about i not declared properly. I just didn't copy that part.
pls help!
You're trying to generate a fibonacci sequence (starts with two terms (0,1), and each subsequent term is the addition of the prior two). Therefore, i should not be part of the calculation; it is only there to control looping.
A simple generation of the first ten numbers in the sequence is simply this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=0, b=1;
for (int i=0; i<10; ++i)
{
printf("%d ", a);
int c = a+b;
a = b;
b = c;
}
fputc('\n', stdout);
return EXIT_SUCCESS;
}
That's it. The code above will generate the following:
0 1 1 2 3 5 8 13 21 34
I leave applying the above logic to generate whatever your final requirements are up to you, but that's how the sequence is iteratively generated.
PS: Apologies in advance for writing C code. I totally spaced the language tag, but nonetheless the algorithm is the same.
The shown series is the fibonacci sequence.
Look at its definition and find out: Which numbers do you need to compute the current one?
In your current code, you only have one previous number available.
If that's not enough, what else might you need?
Here are my three cents.:)
#include <iostream>
#include <utility>
int main()
{
while (true)
{
std::cout << "Enter a non-negative number (0 - exit): ";
unsigned int n;
if (!( std::cin >> n ) || ( n == 0 )) break;
unsigned long long int first = 0;
unsigned long long int second = 1;
std::cout << '\n';
for (unsigned int i = 0; i < n; i++)
{
if (i != 0) std::cout << ' ';
std::cout << first;
second += std::exchange( first, second );
}
std::cout << "\n\n";
}
}
The program output might look like
Enter a non-negative number (0 - exit): 1
0
Enter a non-negative number (0 - exit): 2
0 1
Enter a non-negative number (0 - exit): 3
0 1 1
Enter a non-negative number (0 - exit): 4
0 1 1 2
Enter a non-negative number (0 - exit): 5
0 1 1 2 3
Enter a non-negative number (0 - exit): 6
0 1 1 2 3 5
Enter a non-negative number (0 - exit): 7
0 1 1 2 3 5 8
Enter a non-negative number (0 - exit): 8
0 1 1 2 3 5 8 13
Enter a non-negative number (0 - exit): 0
Fibonacci numbers grow very quickly. So in general you need to check whether an overflow can occur in the for loop or not.
Your code is printing the sum of current and just previous element. But the above question asks for the Fibonacci number which is define as:
Fib[i] = Fib[i - 1] + Fib[i - 2]; Fib[0] = 0, Fib[1] = 1
Now it can be solved through recursion or 1D DP.
But a simple solution can be constructed by knowing the above relation. We can define the current Fibonacci number is the sum of just previous and previous of just previous.
The code is:
int prev1 = 0; // Fib[0]
int prev2 = 1; // Fib[1]
int curr;
cout << prev1 << ' ' << prev2 << ' ';
for (int i = 2; i <= n; i++)
{
// Fib[i] = Fib[i - 1] + Fib[i - 2];
curr = prev2 + prev1;
cout << curr << ' ';
prev1 = prev2;
prev2 = curr;
}

Pattern Printing-Where am I going wrong in this C++ code?

I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}

Using char arrays to add together large numbers

I have an assignment in which I am supposed to
1.) Read in 2 char arrays of numbers
2.) add together the arrays, performing carry addition, carrying the tens place
3.) print out the newly added array.
I am also supposed to print an error if I need to carry on the last digit of the array (overflow)
so something like 99999999999999999999 +
1 =
________________________
ERROR
That's the part I'm having trouble with.
The above outputs something like "99999999999999999:0" so I have no idea what's going wrong.
I'll post my code, but please be nice :( I know it certainly isn't the most efficient, but I'm just trying to lay things out in a way that is easy for my brain to understand right now.
And yes, I HAVE to use char arrays. I guess it's to help us understand the ascii table.
#include <iostream>
using namespace std;
void InitNumber(char[]);
int AddArrays(char first[], char second[], char combined[]);
void OutputNumber (char[]);
const int LENGTH = 20; // global variable
int main()
{
char set1[LENGTH];
char set2[LENGTH];
char sum[LENGTH];
InitNumber (set1);
InitNumber (set2);
if(AddArrays (set1, set2, sum)) {
cout << "overflow!" << endl;
}
OutputNumber(sum);
}
void InitNumber (char list[])
{
int numberOfDigits;
cout << "Please enter the number of digits in the number: ";
cin >> numberOfDigits;
cout << "Please enter the digits in the number with the LEAST significant first: ";
for (int i = 0; i < numberOfDigits; i++) {
cin >> list [i];
}
for (int l=(numberOfDigits); l < LENGTH; l++) {
list [l] = '0';
}
}
int AddArrays(char first[], char second[], char combined[])
{
for (int h = 0; h < LENGTH; h++)
combined[h]= '0';
int overflow = 0;
for (int i = 0; i < LENGTH; i++) {
int currentSum = (first[i]-'0' + second[i]-'0');
cout << "currentSum = " << currentSum << endl;
if(currentSum / 10 == 0 )
combined[i] += currentSum;
else if (currentSum/10 !=0) {
if (i == LENGTH-1 && currentSum/10 !=0){
overflow = 1;
}
else{
combined [i] += currentSum%10;
cout << "current i: " << combined[i] << endl;
combined [i+1] += currentSum/10;
cout << "current i+1: " << combined[i+1] << endl;
}
}
}
return overflow;
}
void OutputNumber(char arrayOut[])
{
for (int l=LENGTH - 1; l >= 0; l--)
cout << arrayOut[l];
}
working input
input
6
1 2 3 4 5 6
7
1 2 3 4 5 6 7
output
00000000000008308642
Not-working output
input
20
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
1
1
output
999999999999999999:0
I'm going to reproduce small parts of your inner loop where you are carrying out the addition, in order to explain why your overflow detection is broken.
for (int i = 0; i < LENGTH; i++) {
int currentSum = (first[i]-'0' + second[i]-'0');
if(currentSum / 10 == 0 )
combined[i] += currentSum;
Here you're adding the corresponding pair of digits from the two numbers you're adding, and checking (in your particular style) if they overflowed. Try to remember this part, it's important. In order to check for overflow, you're only checking the result of adding the pair of digits from the two large numbers you're adding.
else if (currentSum/10 !=0) {
This is a completely useless check. You can only get here if the division is known to produce a non-zero result. This if() can be removed completely. Now, the relevant part of your code is
combined [i] += currentSum%10;
combined [i+1] += currentSum/10;
Do you see the problem yet?
Your approach is, once overflow is detected, is to increment the next higher order digit in the result.
Unfortunately, on the next loop iteration, in order to check for carry over, you're just checking the sum of the next corresponding digit pair, from the two large numbers you're adding. The carry-over you're saving here is going to get completely ignored.
Say your numbers are two digits long max, rather than 20, and you entered the numbers 99 and 1.
On the first iteration, you'll add 9 and 1, save 0 as the first digit, and add 1 to the second digit in the sum.
On the second iteration, you'll add 9 and 0, and, given your logic above, conclude that nothing overflowed.

Iterated Difference

This is an spoj problem. It works, but It's too slow.
Here is the question:
Iterated Difference
You are given a list of N non-negative integers a(1), a(2), ... ,
a(N). You replace the given list by a new list: the k-th entry of the
new list is the absolute value of a(k) - a(k+1), wrapping around at
the end of the list (the k-th entry of the new list is the absolute
value of a(N) - a(1)). How many iterations of this replacement are
needed to arrive at a list in which every entry is the same integer?
For example, let N = 4 and start with the list (0 2 5 11). The successive iterations are:
2 3 6 11
1 3 5 9
2 2 4 8
0 2 4 6
2 2 2 6
0 0 4 4
0 4 0 4
4 4 4 4
Thus, 8 iterations are needed in this example.
Input
The input will contain data for a number of test cases. For each case,
there will be two lines of input. The first line will contain the
integer N (2 <= N <= 20), the number of entries in the list. The
second line will contain the list of integers, separated by one blank
space. End of input will be indicated by N = 0.
Output
For each case, there will be one line of output, specifying the case
number and the number of iterations, in the format shown in the sample
output. If the list does not attain the desired form after 1000
iterations, print 'not attained'.
Sample Input
4
0 2 5 11
5
0 2 5 11 3
4
300 8600 9000 4000
16
12 20 3 7 8 10 44 50 12 200 300 7 8 10 44 50
3
1 1 1
4
0 4 0 4
0
Sample Output
Case 1: 8 iterations
Case 2: not attained
Case 3: 3 iterations
Case 4: 50 iterations
Case 5: 0 iterations
Case 6: 1 iterations
I'm not sure of what to do to make it faster. I tried using arrays, but I get all sorts of problems trying to allocate the memory and set one array to another.
How can I make it faster? Here's my code:
#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <string>
using namespace std;
bool checker(vector<int>& nums2) {
int n = nums2[0];
for (int i = 1; i < nums2.size(); i++)
{
if (n != nums2[i])
return false;
}
return true;
}
vector<int> iterate(vector<int>& nums, int& iter, bool& attained) {
if (iter == 1000) {
attained = false;
return nums;
}
vector<int> nums2;
for (int i = 0; i < nums.size(); i++) {
if (i == nums.size() - 1)
nums2.push_back((int)abs((double)nums[i] - (double)nums[0]));
else
nums2.push_back((int)abs((double)nums[i] - (double)nums[i + 1]));
}
iter++;
return nums2;
}
int main()
{
int N = -1, count = 1;
while (1) {
int num = 0;
vector<int> nums;
string List = "";
stringstream ss;
cin >> N;
if (N == 0)
break;
cin.ignore();
cin.clear();
getline(cin, List);
ss << List;
while (ss >> num) {
nums.push_back(num);
}
int iterations = 0;
bool attained = true;
while (!checker(nums)) {
nums = iterate(nums, iterations, attained);
}
if (!attained)
cout << "case " << count << ": not attained";
else
cout << "case " << count << ": " << iterations << " iterations" << endl;
count++;
}
}
I fixed it. It was a problem with the while loop in the main function. The condition was:
while (!checker(nums)) { ... }
It would stay in the loop and repeatedly call the iterate function because if it is not attainable, then the checker will always be false. So changing the condition to:
while (!checker(nums) && attained) { ... }
would break the loop if it was not attainable.
Basically, it was just getting stuck on doing the same thing over and over; it wasn't actually slow.
Thanks, xan, for your answer.
If you want it to be a little faster you should work on debugging your array variation to avoid the vector allocations. If you want it to be a lot faster you need to do some analysis of the problem to find a better algorithm. For instance, if you see the same list twice you're in a loop and will exceed 1000 iterations. And the result will be the same if you rotate the list, which you can consider when checking for a repeated list.
Your implementation executes 1000 iterations in 25ms on my mainstream lapton. Fixed one, because there's a bug and case 2 will execute forever.
To do faster you can reuse the same vector and modify it in place, your iterator() function signature would look like:
void iterate(vector<int>& nums);
This version takes 7ms on my machine, because it doesn't allocate memory in loop.

Number triangle using while loops

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