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 2 years ago.
Improve this question
I'm trying to reverse a vector using functions but whenever I run the program it terminates and outputs nothing. Can anyone please tell me what I am doing wrong?
#include <iostream>
#include <vector>
using namespace std;
void reverseavector(vector<int>& vec)
{
for (int i = vec.size() - 1; i >= 0; --i) {
cout << vec[i];
}
}
int main()
{
int input;
vector<int> vect;
cout << "Enter values to reverse the vector" << endl;
cin >> input;
for (int i = 0; i < vect.size(); ++i) {
vect.push_back(input);
}
reverseavector(vect);
return 0;
}
In your code, you declared the following statement:
vector<int> vect;
This statement means that a vector of integers named vect get created, but you didn't specify a size for it, therefore when the following loop is reached:
for (int i = 0; i < vect.size(); ++i){
vect.push_back(input);
}
vect.size() return 0 because you didn't specify a size for vect, therefore the loop never gets executed. Because the condition is false.
I made some changes to the code you have. Take a look:
#include <iostream>
#include <vector>
using namespace std;
void reverseavector(vector<int>& vec)
{
for (int i = vec.size() - 1; i >= 0; --i) {
cout << vec[i];
}
}
int main()
{
int input;
vector<int> vect;
bool stop = false; // This bool will keep allow the while loop to keep prompting the user to enter a number until the input is -1
while (stop == false)
{
cout << "Enter a value to the vector to be reversed, or -1 to stop entering values" << endl;
cin >> input;
vect.push_back(input);
if (input == -1)
{
stop = true;
}
}
reverseavector(vect);
return 0;
}
The main thing about your code is that you needed a way to loop taking values into input. There are other ways to do this, but this was the first one I came up with.
When you run
vector<int> vect;
cout << "Enter values to reverse the vector" << endl;
cin >> input;
for (int i = 0; i < vect.size(); ++i)
vect.size() remains at 0, because the vector is empty. So, i < vect.size() remains false, and the loop doesn't enter.
So, reverseavector gets an empty vector and outputs nothing.
Related
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;
}
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 2 years ago.
Improve this question
This is my simple while (true) loop:
while (true)
{
int i = 0;
++i;
cout << i << endl;
if (i == 5) {
break;
}
}
}
So break; isn't quitting the loop and the output is an infinite 1.
See this for Why use a for loop instead of a while loop?.
Now, coming to your question:
You are initializing i variable in each iteration of your while loop. Move the definition of i outside the while loop so that it's value can be updated.
Try this:
#include <iostream>
int main(void)
{
int i = 0;
while (true)
{
++i;
std::cout << i << std::endl;
if (i == 5)
break;
}
return 0;
}
Output:
1
2
3
4
5
Suggestion:
You can also use for loop as it is more appropriate to print a range of numbers.
#include <iostream>
int main(void)
{
for (int i = 1; i <= 5; i++)
std::cout << i << std::endl;
return 0;
}
The i is always initialized to 0 on each iteration. You should use this outside of the loop.
You are creating a new variable i in every run of the loop.
It is initalized to zero, then you increase it by one.
So after
int i = 0;
++i;
the variable i is always 1.
Solution:
int i = 0;
while (true) {
{
++i;
cout << i << endl;
if (i == 5) {
break;
}
}
}
or you can just use a simple for-loop:
for (int i = 0; i <= 5; i++)
{
cout << i << endl;
}
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 3 years ago.
Improve this question
I'm trying to write a function that reads a 2D array of integers where the user is the one who enters the size of the array (it shouldn't be defined before ) . I tried this but it's not working.
I appreciate your help!
line 6 is the declaration of the function
this is my code:
#include <iostream>
using namespace std;
void Fill_table(int mat[][], int s) {
for (int i = 0; i<s; i++) {
for (int j = 0; j<s; j++) {
cout << "mat[" << i << "][" << j << "]:" << endl;
cin >> mat[i][j];
}
}
}
int main()
{
int n;
cout << "Enter the size: ";
cin >> n;
int a[n][n];
Fill_table(a, n);
return 0;
}
Just to give you a simple alternative. Instead of declaring a 2D array with [][], you could use [n*n] and then subscript with i*s + j. The code would be
#include <iostream>
using namespace std;
void Fill_table(int* mat, int s) {
for (int i = 0; i<s; i++) {
for (int j = 0; j<s; j++) {
cout << "mat[" << i << "][" << j << "]:" << endl;
cin >> mat[i*s+j];
}
}
}
int main()
{
int n;
cout << "Enter the size: ";
cin >> n;
int a[n * n];
Fill_table(a, n);
return 0;
}
1D arrays can be passed as a pointer to a function. You also need to pass the size (as you did). For 2D arrays, you need to know the size at compile time.
You cannot set the size of a multidimensional array at runtime.
The error
error: declaration of ‘mat’ as multidimensional array must have bounds for all dimensions except the first
void Fill_table(int mat[][], int s)
tells you exactly that.
Consider using C++ data structure instead, in this case vector<vector<int>>, you have a somewhat simple how-to guide in Creating a Matrix using 2D vector in C++ – Vector of Vectors.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have to write a program in which integer value is entered from user and the string has to be displayed that many times. But I am getting errors.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
cout << string(N, "Well Done");
return 0;
}
Note: I am not permitted to use a loop in this assignment.
If you may not use a loop, you may use goto to get around the restriction:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
{
int i = 0;
goto test;
begin:
cout << "Well Done";
++i;
test:
if (i < N)
goto begin;
}
return 0;
}
Note that goto is widely considered bad practice.
EDIT2: IN THE ORIGINAL ASKER's COMMENTS, LOOPS OF ANY KIND ARE PROHIBITED IN THIS ASSIGNMENT.
Use recursion.
void printN(int n, string s) {
if (n <= 0) return;
cout << s << endl;
printN(n-1, s);
}
Then you can call this from your main program as follows:
printN(userInput, "Hi my name is ricky bobby");
EDIT: just saw you haven't learned recursion yet. Look up this term, and familiarize yourself with it. This is a way to do iteration without looping (this is the most simplistic way I can describe it)
std::string does not have a constructor that repeats a string N times (it does have one for repeating a single character N times, though). What you need is a loop instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
for (int i = 0; i < N; ++i)
cout << "Well Done";
return 0;
}
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 4 years ago.
Improve this question
I seem to be looping through my array wrong, I've got it set up to prompt the user for a list of numbers and I am supposed to be comparing it to another number that the user sets.
#include <iostream>
using namespace std;
bool chk = true;
int main() {
/*
Write a program that asks the user to type 10 integers of an array and an integer s.
Then search the value s from the array and display the value of s if it is found in
the array otherwise print sorry not found..
*/
int userArray[10], i, greater = 0;
int s;
cout << "Enter a check number: \n";
cin >> s;
if (chk = true) {
//prompt for array list
for (i = 0; i < 9; i++) {
if (i == 0) {
cout << "Enter ten numbers: " << "\n";
cin >> userArray[i];
}
else {
cin >> userArray[i];
}
chk = false;
}
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
//I was just using this to pause the console and let me inspect result
cin >> greater;
return 0;
}
}
}
I assume the following code is where the problem lies. The idea is i set s = 2 enter in a list of numbers and then compare to s and print s if there is a match if not I print No match found. When I enter in a number that i know matches s it seems to print the first number in the array, but i thought since I loop through the numbers one by one in the for loop that it should display when it reaches the right number not when it stops. Thanks in advance
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
You are using a single equals sign. This is setting s to userArray[i] so it always evaluates to true. For comparisons, use double equal signs, like this:
if (s == userArray[i]) {...}
Also, your return statement is inside your loop (credit to #UnholySheep).
you are comparing with a single assignment operator = you should be using the equal operator instead ==
if (s = userArray[i]) with in the for loop is one example.
you also doing the same mistake in
if (chk = true)