multi-nested for loop C++ not finishing [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I currently have a small assignment for my c++ college course. I'm currently running into an error where it runs the first two loops but then freezes and does not finishes the rest of the loops. the whole point is to printout a * diamond
an example would look like this if you entered the number 7:
*
***
*****
*******
*****
***
*
this is what the code looks like currently:
#include <iostream>
using namespace std;
int main(){
cout<<"How many lines do you want?";
int num_rows;
cin>>num_rows;
int row_average = (num_rows/2)+1;
for(int count=0; count<num_rows; ++count){
int midpoint = row_average - count;
int absolute = abs(midpoint);
int spaces = absolute;
for (int count_a = 0; count_a<spaces; ++count_a){
cout<<" ";
}
for (int count_b = row_average; count_b<num_rows; ++count){
int stars = count_b - spaces;
for(int count_c = 0; count_c = stars; ++count_c){
cout<<"*";
}
}
}
}
Any answers or help would be appreciated!
Thanks!

Is this below a typo?
for (int count_b = row_average; count_b<num_rows; ++count){
---------------------------------------------^^^^^
Shouldn't it be ++count_b?
Also you're not outputting any newline character?

A few things:
1) In the second nested for loop you should increment count_b. So
for(int count_b = row_average; count_b < num_rows; ++count_b) {
2) In the last nested for loop you need to make the condition count_c less than stars, not equal to it. So
for(int count_c = 0; count_c < stars; ++count_c) {
3) Finally, you need a newline character or else all these stars will print on the same line

Related

How to reverse the string in C++? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 hours ago.
Improve this question
This is my problem. My task is to code the function void:
void process(char input[], char output[]){
}
And the given:
int main(){
const int MAX_SIZE = 100;
char input[] = "this is a beautiful day" ;
char output[MAX_SIZE];
process(input, output);
cout << output;
return 0;
}
Note: I just can use and for this question.
This is my work:
void process(char input[], char output[]){
int n = strlen(input);
for (int i = 0; i > n; i++){
output[i] = input[i];
input[i] = input[n - i + 1];
input[n - i + 1] = output[i];
}
}
But it doesn't work. How should I fix it?
there's a logical error with your code.
for (int i = 0; i > n; i++){
output[i] = input[i];
input[i] = input[n - i + 1];
input[n - i + 1] = output[i];
In your looping statement, you've initialised i=0 and given the condition i>n. This will result in the loop statement not executing.
Secondly, I have simplified your code further, and it should provide the required input.
for (int i = 0; i<=n; i++){
output[i] = input[n - i]; //1
cout<<output[i];
}
So essentially, a string is an array of characters, so to simplify, since the index in the array output is running from 0 to n, simultaneously, the array input indexes are being accessed from n to 0, in the line //1 .
As mentioned, since a string is an array of characters, within the same loop, i'm displaying each element in the output string. Providing the answer.
My test case was : This is a test
Output: tset a si sihT
Hope this helps! Let me know if you need any further explanation.

C++ concatenate from two arrays to one dynamic erray that are initialized from 2 input text files using filestream [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to concatenate two arrays that were initialized from file input into one dynamic array and returning it to an output file but while testing I found out that the returned dynamic array is initialized with random numbers. I'm sorry for my lack of experience as I am a beginner.. These are my input text files
Input1.txt
1
2
3
Input2.txt
4
5
6
and this is my code ..
#include <iostream>
#include <fstream>
using namespace std;
int * concatenate(int *a1,int *a2,int size);
int main() {
int size = 3;
int arr1[size];
int arr2[size];
ifstream fin;
ofstream fout;
fin.open("input1.txt");
for(int i = 0; i < size; i++) {
int value;
fin>>arr1[i];
cout<<arr1[i]<<endl;
}
fin.close();
fin.open("input2.txt");
for(int j = 0; j < size; j++) {
fin>>arr2[j];
cout<<arr2[j]<<endl;
}
int *arr3 = concatenate(arr1,arr2,size);
cout<<arr3[1];
return 0;
}
int * concatenate(int *a1,int *a2,int size) {
int * r = new int[size*2];
for(int i = 0; i > size*2; i++) {
if(i < size)
r[i] = a1[i];
else
r[i] = a2[i-size];
}
return r;
}
If you're using c++ you should consider using vectors instead of arrays.
They make operations like these way easier.
Here's for reference:
https://en.cppreference.com/w/cpp/container/vector
https://www.geeksforgeeks.org/vector-in-cpp-stl/
You can referer to this post to see how to concatenate two vectors. Concatenating two std::vectors
If you want to stick to your method there's an error in your concatenate function.
You never actually enter the for-loop since your condition for stopping is wrong. The condition in your loop is continue iterating while i > size * 2 but, with i = 0 at the start, that will never be true thus you will never enter the loop. You can fix this just by inverting the comparaison like so i < size * 2.
To avoid this kind of errors you can try to setup a debugger and go through your code line by line seeing the values of variables and what lines are actually executed. This method will help you catch a lot of small mistakes like these.
As for the random values in your return array it's because C and C++ don't clean the memory being allocated by your program when creating a new array or calling malloc for example.
you seem to have a small typo in your code in the last for loop,
for(int i = 0; i > size*2; i++)
i think you ment (watch the comparison sign)
for (int i = 0; i < size*2; i++)
you can try to cout values from the code you think doesn't work, or even better, use an IDE like Visual studio to debug your code when it fails for no apparent reason, which allows you to see your code executing line by line in the future.

unable out figure out error in below program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I was solving a problem https://codeforces.com/contest/489/problem/B
Its a simple brute force approach,In my terminal when i am giving input
#include<bits/stdc++.h>
using namespace std;
vector <int> b;
vector <int> g;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
b.push_back(a);
}
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int a;
cin >> a;
g.push_back(a);
}
sort(b.begin(), b.end());
sort(g.begin(), g.end());
int ans = 0;
bool visited[10000];
memset(visited, sizeof(visited), false);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(!visited[j])
if (abs(b[i] - g[j]) <= 1) {
visited[j] = true;
ans++;
break;
}
}
}
cout << ans;
}
4
1 4 6 2
5
5 1 5 7 9
I am getting correct output as 3 , This is the very first test case on codeforces also and codeforces showing output as 2 and as showing as wrong answer.
Please see here Proof ,I never faced such kind of problem in competitive
programming .
accepted solution solution
There was also announcement related to this ques read below here
This is a case of undefined behavior: if(!visited[j]) is undefined. visited is not initialized because the call memset(visited, sizeof(visited), false); is wrong. You are reading uninitialized variables.
The declaration of memset is
void *memset( void *dest, int ch, size_t count );
You are writting 0 times the value 10000 into visited. On your machine this memory was filled with zeros. But on other machines there can be different values.

Problem with the validation for hangman game [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I'm working on a hangman game for a college asignment and i aleady have most of the work done but for some reason this part here is not working. Is there a problem with my logic? It seems to be incredibly simple.
bool second_check(char user_input) {
char u[3]={'a','r','i'};
for (int i = 0; i <= 3; i++) {
if (user_input==u[i]){
return true;
};
};
return false;
}
int main(){
char o;
cout<<"enter"<<endl;
cin>>o;
if (second_check(o)==true) {
cout << "Correct!" << endl;
}
else
cout << "Wrong! \n Strike one!" << endl;
return 0;
}
The for loop will loop 4 times even though you have 3 elements, causing it to try and access an undefined location in memory, to fix this replace the 'i <=3' with 'i<3'
so the for loop should like this in the end:
for (int i = 0; i < 3; i++) {
if (user_input==u[i]){
return true;
};
};
Answer
Since char u[3]={'a','r','i'}; contains only 3 characters, your for loop will be:
for (int i = 0; i <= 2; i++) or
for (int i = 0; i < 3; i++).
Explanation
This is because, in C/C++ and most of the programming language, the array count starts from 0. Therefore the first element will be array[0] and last will array[n-1] where n is the size of the array used at initialization. (Above, n=3)
So it would be helpful to the community if you state clearly what the problem is (i.e expected vs. actual output).
That said, a couple problems I can see...
for (int i = 0; i <= 3; i++)
if (user_input==u[i]){
Since u is of size 3 (char user[3]), you need to change your for loop to be i < 3 since arrays are 0 based, valid indices are 0,1,2 and you will go out of bounds of the array. I.e. user[3] is not a valid index.
You are not comparing an index of user_input which I suspect you want to. i.e. user_input[i].

Sum of the first 5 even numbers from the array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So, I need to get the sum of the first 5 even numbers from my array, this is the code that I've got so far, have no clue what to do next. It runs, but the result is incorrect
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int niz[10];
cout << "Unesi 10 brojeva:";
for (int i = 0; i < 10; i++) {
cin >> niz[i];
}
int suma = 0;
int parni[5];
int j = 0;
for (int i = 0; i < 10; i++) {
if (niz[i] % 2 == 0) {
niz[i] == parni[j];
j++;
if (j == 5) {
break;
}
}
}
for (int i = 0; i < 5; i++) {
suma = parni[i] + suma;
}
cout << suma;
system("PAUSE");
return 0;
}
This line:
niz[i] == parni[j];
does nothing. (It tests if niz[i] happens to be equal to the current, uninitialized value of parni[j], and throws away the result of the comparison.)
You want to store niz[i] in parni[j], so do this:
parni[j] = niz[i];
Incidentally, there is a problem if there are fewer than 5 even numbers in the niz array. In that case, you still sum up all five entries of the parni array, using uninitialized values, which is Bad. One way to avoid this is to just sum up the even entries as you find them, without using a secondary array.
IE, do suma += niz[i] at the line in question, and get rid of parni altogether.
Unless you're really required to use arrays here, vectors will work much more nicely.
You can also use a couple of standard algorithms to make your life easier (especially std::copy_if and std::accumulate).
// for the moment I'll ignore the code to read the input from the user:
auto input = read_input();
auto pos = std::remove_if(input.begin(), input.end(),
[](int i) { return i % 2 != 0; });
// assume that `input` always contains at least 5 elements
pos = std::min(pos, input.begin() + 5);
sum = std::accumulate(input.begin(), pos, 0);