Creating number pattern (triangle numbers) in c++ with minimum loops - c++

We were asked to make a triangular no. pattern in c++ with min. loops. The triangle pattern is as follows:
____1_____
___2__3____
__4__5__6__
7__8__9__10
My code:
#include <iostream>
using namespace std;
int main() {
int n=0, r=0, i=0;
cout << "No. of rows: ";
cin >> r;
for( n=1; n<=r; n++) {
for( i=1; i<=r-n; i++) {
cout << " ";
}
for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
if( i<10 )
cout << " " << i << " ";
else
cout << i << " ";
}
cout << "\n";
}
return 0;
}
OUTPUT
QUESTIONS
1) Is it wise to use pattern generating formulas? for eg, for putting value of i in last loop, i used the formula for the pattern 1,2,4,7 .. as (n*(n-1)/2)+1. Is it more efficient this way? what could be an iterative approach? and what could be a possible recursive one?
2) Is it possible to reduce no. of loops? is it better to reduce variables or reduce loops?
THANK YOU!

Its a simple incremental number pyramid that dose not require any special formula. Formula's increases the complexity of the program because more calculations are involved. Try to keep the code simple.
Simplest way to do this is :
int main() {
int num,i=1;
cout<<"Enter Number of Rows";
cin>>num;
for(int r=1; r<=num; r++)
{
for(int space=1; space<=num-r; space++){
cout<<" ";
}
for(int c=1; c<=r; c++,i++){
cout<<" "<<i;
}
cout<<"\n";
}
return 0;
}

This is a completely personal opinion, but I think that using formulae is really not going to affect the efficiency, since you are anyways printing the elements one at a time. So the total time is dependent on your length of input which is r(r+1)/2.
I wrote this and it seems to work good too, though the logic in this code is to just keep printing the elements in order and breaking the line when required. It uses only one inner loop to print the spaces at the beginning of each line. Here is the Ideone link.
int r;
cin>>r; //number of rows
int spaces = r-1, rowcount = 1;
int curcount = 0;
for(int i=1; i<=(r*(r+1))>>1;i++) {
if(curcount == 0) {
for(int j=0; j<spaces; j++)
cout<<" ";
spaces--;
}
cout<<(i<10?" ":"")<<i<<" ";
if(++curcount == rowcount) {
rowcount++;
curcount=0;
cout<<endl;
}
}

Related

why am I getting runtime error for the following code and how to fix that? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I was solving this problem on Codeforces B. Ania and Minimizing and I got runtime error on test 9. I am new to c++ and I did not understand why this happened. Could someone help me fix this error? Thanks :)
Here is my code:
#include <iostream>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, k;
string num;
cin >> n >> k;
cin >> num;
if(n==1){
cout << 0 << endl;
return 0;
}
if(k==0){
cout << num << endl;
return 0;
}
if(num[0]!='1'){
num[0]='1';
}
else{
k=k+1;
}
for(int i=1; i<k; i++){
if(num[i]!='0'){
num[i]='0';
}
else{
k=k+1;
}
}
cout << num << endl;
return 0;
}
Here you can check the runtime error details:
https://codeforces.com/submissions/iwrestledthebeartwice at submission number: 85825935
If k is larger then the size of num (which could happen because you are incrementing it at line 37) you will get an "access out of bonds" Error at num[i]='0'.
For example you have the following inputs:
5 5
12345
This will cause line 33 to access memory past the size of num. now it depends if this memory is 0, then your code will work. But if it is not zero you try to write a zero which is not permitted.
Your code makes out of bounds string accesses on some inputs, for instance given n=2 k=1 S=10 you access num[2] which does not exist. This will cause the runtime error that you see.
Your problem:
for(int i=1; i<k; i++){
if(num[i]!='0'){
num[i]='0';
}
else{
k=k+1;
}
}
You are reading and writing past the end of the buffer (buffer overrun). Supoose n = 3, and k=3. and the number is 1000. You will find 0 in all positions and your k will be incremented on every iteration, making it 6 by the end. While the string was just 4 chars long. You read and wrote to a location which you are not allowed to. That is undefined behaviour.
To fix, you need to make sure you don't change k while you are looping as that is totally unnecessary. Also, make sure you read and understand the problem statement completely before attempting to solve the problem.
Let's remove the k = k + 1 from both places and make sure we are always less than n. i needs to do at least k iterations
if(num[0]!='1'){
num[0]='1';
}
for(int i=1; i <= k && i < n; i++){
if(num[i]!='0'){
num[i]='0';
}
}
Additionally, if our first digit is '1', we have one less 0 to replace, so we will decrement k by 1 in that case:
if(num[0]!='1'){
num[0]='1';
k--;
}
This will solve the issue and you will get correct output. You still need to place additional checks to make sure num.size() == n always and that k < n always.
Note that this might not be the most efficient or best solution, it only attempts to fix the issues you had with the logic you used.
As all of you guys pointed out I fixed my code. I was dumb and making the loop go out of bounds.
Here is the code:
#include <iostream>
using namespace std;
int main(){
int n, k;
string num;
cin >> n >> k;
cin >> num;
if(k==0){
cout << num << endl;
return 0;
}
if(num.size()!=n){
return 0;
}
if(n==1){
cout << 0 << endl;
return 0;
}
if(k==0){
cout << num << endl;
return 0;
}
if(k>num.size()){
cout << num << endl;
return 0;
}
if(k>n){
cout << num << endl;
}
if(num[0]!='1'){
num[0]='1';
k--;
}
for(int i=1; i<=k and i<n; ++i){
if(num[i]!='0'){
num[i]='0';
}
else{
k=k+1;
}
}
cout << num << endl;
return 0;
}

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

Is there a way in C++ to only return the the last instance of a for loop?

Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}

How to fix a "runtime error" that doesn't affect performance?

Submitted a problem to an online judging platform. Code works perfectly with the provided samples, but judge outputs "runtime error", nothing more.
Code is supposed to calculate resulting fractions from inputs
Sample inputs:
27 12
2460000 98400
3 4000
Line containing 0 0 will follow the last input. First number is the numerator, second is the denominator.
Current code:
#include <iostream>
using namespace std;
int main(){
int num[500], den[500], ent[500];
for (int i = 0; i < 500; i++) {
num[i] = 0;
den[i] = 0;
ent[i] = 0;
}
int i=1;
num[0]=1; den[0]=1;
while((num[i-1]!=0)&&(den[i-1]!=0)){
cin >> num[i] >> den[i];
i++;
} i--;
for(int j=1; j<i; j++){
ent[j]=num[j]/den[j];
num[j]=num[j]%den[j];
}
for(int j=1; j<i; j++){
cout << ent[j] << " " << num[j] << " / " << den[j] << endl;
}
return 0;
}
My psychic debugging skills tell me that the input they give you has more than 499 lines causing your program to run off the end of its hardcoded arrays.
Have you considered std::vector or an approach that doesn't cache all the input before processing?

Compare 3 arrays c++ [like graph]

can any one help me about this
#include <iostream>
#include <stdio.h>
using namespace std;
int main () {
int A[100] , B[100] , C[100];
int i=0 ,j=0, h=0;
int connctive=0 ;
cout << "THE PROGRAM TAKE 3 GRAGHS ONLY\n";
cout << "\n enter the Graph 1 \n";
cin >> A[i];
cout << "\n enter the Graph 2 \n";
cin >> B[j];
cout << "\n enter the Graph 3 \n";
cin >> C[h];
for(i=0;i<=100;i++ ){
for (j=0;j<=100;j++){
for(h=0;h<=100;h++){
if (A[i]==B[j]) {
connctive = connctive +1;}
if (A[i]==C[h]){
connctive = connctive +1;}
if (B[j]==C[h]){
connctive = connctive +1;
} else
{ if (A[i]!=B[j]!=C[h])
cout << "non of graphs is connective" <<endl;}}}
}
cout << connctive <<"connctive " <<endl;
return 0;
}
i'm working to solve this program i want to Compare 3 arrays and print out the Union numbers with name connective or not Can someone please explain to me why the output from the following code is saying that arrays are not connective all the time :( ?? even when i entered different numbers
As chris said, your loops
for(i=0;i<=100;i++ )
Should almost definitely be
for(i=0;i<100;i++ )
It may not completely solve your issue, but it's a start.
I will make no assumption about what problem your code is supposed to cope with. But there is at least three problems in your code.
First, you better check your array bounds because your have a buffer overflow which always leads to troubles. In C/C++, array are zero-indexed, therefore when you declare A[100] you have 100 elements ranging from A[0] to A[99]. Your three loops are wrongs, stop condition must be i<100 instead of i<=100.
Second, your last check is not what you think it is. You are not comparing three integers together. You are comparing a mix of integer and boolean promoted to integer, since the first == will return a boolean and it will be promoted to resolve the next ==. You must write (A[i]!=B[j])&&(B[j]!=C[h]) instead.
Third, you are not filling all vectors but only the first element of each. You must check the content of your data before you process it.
You are making some very basic mistakes like not even taking the iput correctly ,not checking runtime errors like the one by accessing an array element out of bounds.
I suggest that you should debug your code properly before you post here.
As far as the answer to your code is concerned, this is gonna be the algo..
*******************LOGIC*************************
First of all sort all the three arrays.
Secondly pick up the first element of any array (say C), and compare it the second one (say B) until you find a number in B which is greater than or equal to C[0].If they are equal start finding the number in A (if you find any such number it is connctive) else take the next element of C.
******************LOGIC ENDS*****************
******************CODE***************************
#include <iostream>
using namespace std;
void sort_array(int * X);
int main()
{
int A[5] , B[5] , C[5];
int i=0,j,h;
cout << "THE PROGRAM TAKES 3 GRAGHS ONLY\n";
cout << "\n enter the Graph 1 \n";
for (i=0 ; i<5 ; i++)
cin >> A[i];
cout << "\n enter the Graph 2 \n";
for (i=0 ; i<5 ; i++)
cin >> B[i];
cout << "\n enter the Graph 1 \n";
for (i=0 ; i<5 ; i++)
cin >> C[i];
sort_array(A);
sort_array(B);
sort_array(C);
i=0;
for (j=0;j<5;j++)
{
for(h=0;h<5;h++)
{
if (C[j]<=B[h])
{
break;
}
}
if (C[j]==B[h])
{
for(; i<5 ;i++)
{
if(A[i]>=C[j])
{
break;
}
}
if(A[i]==C[j])
{
cout<<"\n "<<A[i]<<" connective\n";
}
}
}
return 0;
}
void sort_array(int * X)
{
for( int i=0; i<4 ; i++)
{
for( int j=0; j<5-i ; j++)
{
if(X[i]>X[i+1])
{
swap(X[i],X[i+1]);
}
}
}
}
******************************CODE ENDS**************************************