Use C++ to Print a Floyd triangle - c++

I'm trying to build a program which will accept numbers from user and create Floyd triangle.
I tried using the logic of Floyd triangle, but its printing as a line.
Example:
Enter total numbers: 5
Enter the numbers: 3,8,2,4,9
O/p:
3
82
249
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i;
cout << "Enter total numbers: ";
cin >> totalnos;
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
for (i = 1; i <= totalnos; i++)
{
for (j = 1; j <= 1; j++)
{
cout << numbers[i];
}
}
}

You have a problem with the kind of loops shown below. I don't know wether this kind of solution is due to you coming from the Pascal world, or because you've seen it elsewhere. Anyway, you should not make loops start in 1 and go to i, or at least, you should take into account that in the C-like world (C, C++, Java, C#, and many others), arrays start at index 0, and end at index n - 1, being n the size of the array.
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
The problem is actually not what indexes you use for loops, but that you must always use 0..n-1 when accessing arrays. So you can change your loop to just access the array correctly:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[ i - 1 ];
}
Or you can do as all programmers in the C-like world, and directly start your indexes at 0:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 0; i < totalnos; i++)
{
cin >> numbers[i];
}
Instead of going from 1 to totalnos, now you go from 0 to totalnos - 1 (notice the i < totalnos instead of the i <= totalnos, that's a sutil change).
You were accessing memory past the limit of the array, which means that your program will show undefined behaviour (this means that it will probably crash, though under some conditions, nothing seems to happen, which is even more dangerous).
Now the algorithm itself. I haven't heard about the Floyd triangle. It seems that it is built with the natural numbers starting from 1. However, you are asking for totalnos numbers. You will need more than totalnos numbers in order to build a Floyd triangle with totalnos rows. That's why you need to adjust the position of the number being shown taking into account the number of columns for each row (numPos starts with 0).
cout << endl;
for (i = 0; i < totalnos; i++)
{
if ( ( totalnos - i ) < numPos ) {
numPos = totalnos - i;
}
for (j = 0; j < i; j++)
{
cout << numbers[numPos] << ' ';
++numPos;
}
cout << endl;
}
You can find the whole code here: http://ideone.com/HhjFpz
Hope this helps.

Internal loop can be modified as below :
for (i=0; i < 3; i++)
{
for (j=0; j<=i; j++)
{
cout << numbers[i+j];
}
cout<<" ";
}
Hard coded value "3" can be replaced with the "number of rows of Floyd triangle .
I think this will do the trick .

In inner loop you made mistake with j <= 1; should be j <= i;
And you missed '\n' char for new line.
Here is fix:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i, k = 0;
cout << "Enter total numbers: ";
cin >> totalnos;
//int numbers[totalnos];
//cout << "Enter the numbers: ";
// for (i = 1; i <= totalnos; i++)
// {
// cin >> numbers[i];
// }
for (i = 1; i <= totalnos; i++)
{
// your code for (j = 1; j <= 1; j++)
for(j=1; j<=i; ++j) // fixed
cout << k+j << ' ';
++k;
cout << endl; // fix
}
}

Related

Right angle triangle star pattern in C++ using while loops

I want a pattern in which for n=4 in 1st row it has 4 stars and in 2nd row I has 1 space & 3 stars and in 3rd row, it has 2 spaces and 2 stars and so on.
****
***
**
*
The code, I tried to solve this.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
//Printing Spaces
int space = i - 1;
while (space)
{
cout << " ";
space++;
}
//Printing Stars
int j = 1;
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
In your while (space) loop you aren't comparing space to anything, so it assumes that the expression is always true.
Here's a simplified way to do it:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
// print i-1 spaces
for (int j = i-1; j >= 1; j--)
{
cout << " ";
}
// print n-i+1 stars
for (int j = n; j >= i; j--){
cout << "*";
}
cout << endl;
i++;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
int space = i - 1;
while (space>=1) // change 1.1
{
cout << " ";
space--; // change 1.2
}
int j = i; // change2
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
I made only 2 changes in your code so it can work.
1st one
while (space>=1)
what you are doing is you are trying to add space in output so you add space variable in while() loop but that's not going to work because you have to decide first how many spaces you have to print according to that you have to put condition in while() loop. To achieve this space--; added .
For ex. line 4 i=4; space want 3, so space=3; while(space>=1); space--; so while loop runs 3 time and print 3 gaps/spaces.
2nd one
int j = i;
while (j <= n)
if you put j=1; then your gaps print properly but all stars print 4 times as loop runs 4 times always. Due to this condition for i=1; But if you make j=i;
loop runs 4 times for 1st line, 3 times for 2nd line,.....

Rotating an array:Segmentation Fault (SIGSEGV)

Given an array of N size. The task is to rotate array by d
elements where d is less than or equal to N.
Constraints: 1 ≤ T ≤ 200 1 ≤ N ≤ 200 1 ≤ A[i] ≤ 1000
Example input:
1
5
1 2 3 4 5
2
Output
3 4 5 1 2
The program I wrote seems legit but when I tried to run it is giving me segment fault. I even ran the above example I'm getting the correct output.
The source is GeeksforGeeks: Rotating and Array.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cin >> test_case;
while (test_case--) {
cin >> numb;
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cin >> from;
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
What are the changes which my code needs? What can I do to avoid such errors in the future?click_to_see_segment_fault
Just submitted your exact code on Rotating an Array | Geek for Geeks (site given in the question) . It works perfectly , and no run time error was encountered .
Run the following input and will see weird results. The problem is when the from is greater than the number of elements itself. Basically you need to do a check to see whether the from itself is more than the number of elements or not numb.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cout<<"\nEnter number of test cases:";
cin >> test_case;
cout<<"Test cases = "<<test_case<<endl;
while (test_case--) {
cout<<"Enter count of elements:";
cin >> numb;
cout<<"Count= "<<numb<<endl;
cout<<"Enter the elements:";
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cout<<"Entered elements are :";
for (int i = 0; i < numb; i++) {
cout << arr[i]<<" ";
}
cout<<"\nHow many times to rotated? :";
cin >> from;
cout<<"\nRotate it "<<from<<" times:\n";
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
Lets provide the input as follows:
Enter number of test cases:1
Test cases = 1
Enter count of elements:1
Count= 1
Enter the elements:2
Entered elements are :2
How many times to rotated? :2
Rotate it 2 times:
2 32666
You see the mistake? The location where 32666 is a problem here. It could crash too in your case.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cout<< "Enter the numbe of test cases"<<endl;
cin >> test_case;
if(test_case > 200)
{
cout<<"Number of test cases above limit";
return 0;
}
while (test_case--) {
cout<<"START TEST CASE"<<test_case<<endl;
cout<<"Enter the number of elements in the array"<<endl;
cin >> numb;
if(numb > 200)
{
cout<<"Array size more than expected skipping testcase"<<endl;
continue;
}
cout<<"Enter the elements of array"<<endl;
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cout<<"Enter the number of rotations"<<endl;
cin >> from;
if(from > numb || from < 0)
{
cout <<"rotation index out of range skipping testcase"<<endl;
continue;
}
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
Extending #Charlie's answer,
The program checks for numbs ranges and from's range.

Difference of 2 sets retained in arrays - C++

Consider two sets retained in two arrays. Find the union, intersection and difference (relative complement) of the two sets.
I managed to solve the union and the intersection, but the difference is giving me a hard time. Any hints? And if possible, keep it as simple as possible, without functions or more complex aspects, because I'm a beginner and I still have a lot to learn.
Thank you in advance!
#include <iostream>
using namespace std;
int main()
{
int v1[100], v2[100], u[200], intersection[100], d[100];
unsigned int v1_length, v2_length, i, j, OK = 0, union_length;
cout << "Enter the number of elements of the first array:" << " ";
cin >> v1_length;
cout << "Enter the elements of the first array:" << '\n';
for (i = 0; i < v1_length; i++)
cin >> v1[i];
cout << "Enter the number of elements of the second array:" << " ";
cin >> v2_length;
cout << "Enter the elements of the second array:" << '\n';
for (i = 0; i < v2_length; i++)
cin >> v2[i];
//Union
union_length = v1_length;
for (i = 0; i < v1_length; i++)
u[i] = v1[i];
for (i = 0; i < v2_length; i++)
{
int ok = 0;
for (j = 0; !ok && j < v1_length; j++)
if (v1[j] == v2[i])
ok = 1;
if (!ok)
{
u[union_length] = v2[i];
union_length++;
}
}
cout << "The union of the two sets contained in the arrays is: ";
for (i = 0; i < union_length; i++)
cout << u[i] << " ";
cout << '\n';
//Intersection
unsigned int k = 0;
cout << "The intersection of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++)
if (v1[i] == v2[j])
{
intersection[k] = v1[i];
k++;
}
for (i = 0; i < k; i++)
cout << intersection[i] << " ";
cout << '\n';
//Difference
unsigned int l = 0, OK2 = 0;
cout << "The difference of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
{
for (j = 0; j < v2_length; j++)
{
if (v1[i] == v2[j])
OK2 = 1;
if (!OK2)
{
d[l] = v1[i];
l++;
}
}
}
for (i = 0; i < l; i++)
cout << d[i] << " ";
cout << '\n';
return 0;
}
It seems that the intersection is the best place to start. You want the items that only in appear in one of the two arrays, right?
So, for the inner loop, you need to compare all the elements. Then, if no match was found, you have the a unique element.
You need to add the curly braces {} to the for loop. I know that curly braces are distracting at times, but over time, you will probably find it safer to almost always include them to avoid confusion.
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++) {
if (v1[i] == v2[j]){
break; // this item is not unique
} else if(j == v2_length - 1){
d[l] = v1[i]; // This is the unique one, add it to the answer array
l++;
}
}
for (i = 0; i < l; i++)
cout << intersection[l] << " ";
cout << '\n';
You're on the right track!
You're doing a few things wrong. Here are some fixes you can try:
Only set OK2 to 0 once per inner-loop
Reset OK2 to 0 at the end of the inner-loop
Only do the insertion into d after the inner-loop has completed
As an optimization, consider breaking after you set OK2 to 1, as you know at that point it can never be set to 0 for the current value pointed to by the outer-loop.

Program that receives 2 arrays and checks how many times 1 is included in the other

I need to write a program that receives 2 arrays and checks how many times 1 is included in the other...
But I cant find what is wrong with my program! tx!!
#include <iostream>
using namespace std;
int main()
{
int vector1[500];
int vector2[100];
int a = 0, b = 0, count = 0, k = 0;
cout << "enter size of first array:" << endl;
cin >> a;
cout << " enter first array values:" << endl;
for (int i = 0; i < a; i++)
cin >> vector1[i];
cout << "enter size of second array:" << endl;
cin >> b;
cout << "enter secound array values:" << endl;
for (int i = 0; i < b; i++)
cin >> vector2[i];
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i + k] == vector1[j])
{
count++;
k++;
}
else
k = 0;
cout << count << endl;
system("pause");
return 0;
}
Why at all do you need k? The problem is about all inclusions of all elements right? If O(n^2) complexity is fine, then...
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i] == vector1[j])
count++;
One obvious disadvantage of the code above is that you'll get the total sum of all occurences of elements from vector1 in vector2. The key idea remains the same in case you need to know, which elements exactly appeared in another array and how many times, you'll just have to use map or other vector.

How to count how many times each number has been encountered?

I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}