Simple array not stepping through - c++

int i;
int b = 0;
int a[20];
for (i = 0; i < 20; i++){
a[i] = b+1;
cout << a[i];}
}
//I know this is a simple program but it is not giving the expected output and does not step through the program or print out the result

Your loop keeps assigning a[i] without changing b. Since b stays at zero, all as are going to be 1 (because b is zero, b+1 is 1).
If you would like to assign sequential values, either use the loop index i, or change b in the body of the loop:
for (i = 0; i < 20; i++) {
a[i] = i+1;
}
or
for (i = 0; i < 20; i++) {
a[i] = ++b; // Adds 1 to b, and changes b for the next iteration.
}

You are printing out the wrong variable. This should work:
int i;
int a[20];
for (i = 0; i < 20; i++){
a[i] = i+1;
cout << a[i];}

You can do it like this if you want it assign through b :
int i;
int b = 1;
int a[20];
for (i = 0; i < 20; i++){
a[i] = b;
cout << a[i];
b++;}

Related

Revers went wrong and returns the same number

I think i cant understand something in the logic of my cycles, cant u match my mistake?
We need to reverse the number.
My code:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
char b;
cin >> a;
for (int i = 0; i < a.size(); i++){
for (int j = a.size(); j > 0; j--){
b = a[i];
a[i] = a[j];
a[j] = b;
break;
}
}
cout << a;
}
The problem is your nested loop do the swap operation too many times(n*n times).
You just need a single loop to achieve that.
And also remind you the j should be a.size() - 1 and j >= 0, because the array index is start with 0.
#include <iostream>
int main()
{
std::string a;
char b;
std::cin >> a;
for(std::string::size_type i = 0; i < a.size() / 2; ++i)
{
b = a[i];
a[i] = a[a.size() - 1 - i];
a[a.size() - 1 - i] = b;
}
std::cout << a << "\n";
}
You can consider a even more readable one.
#include <iostream>
#include <algorithm>
int main()
{
std::string a;
std::cin >> a;
std::reverse(std::begin(a), std::end(a));
std::cout << a << "\n";
}
These nested for loops
for (int i = 0; i < a.size(); i++){
for (int j = a.size(); j > 0; j--){
b = a[i];
a[i] = a[j];
a[j] = b;
break;
}
}
do not make sense.
For example the inner for loop has only one iteration due to the break statement within it. And this assignment
a[j] = b;
invokes undefined behavior because it is equivalent to
a[a.size()] = b;
It is enough to use only one for loop as for example
for ( std::string::size_type i = 0, n = a.size(); i < n / 2; i++ )
{
std::swap( a[i], a[n-i-1] );
}
If you do not know yet the standard function std::swap then you can rewrite the body of the for loop the following way
for ( std::string::size_type i = 0, n = a.size(); i < n / 2; i++ )
{
auto c = a[i];
a[i] = a[n-i-1];
a[n-i-1] = c;
}

"cout<<count<<endl;" isn't printing anything

cout<<count<<endl; sould provide an output according to the conditions , but it isn't printing anything, what is the fault/error/defects in the code that are causing such results ?
it is my first question , sorry if i am not completely understandable.
i used the following code , i can't understand whats happening here.this is a simple input output question. the output provides us info about matching two team's uniform.
#include <stdio.h>
#include <iostream>
using namespace std;
main(){
int a;
cin>>a;
int **b;
b=new int*[a];
for (int i = 0; i < a; i++)
{
b[i]=new int[2];
for (int j = 0; j <2 ; j++)
{
cin>>b[i][j];
}
}
int count=0;
for (int i = 0; i < a*(a-1); i++)
{ for (int j = 0; j < a; j++)
if (b[i][0]==b[j][1])
count=count+1;
}
cout<<count<<endl;
for (size_t i = 0; i < a; i++)
{
delete b[i];
}
delete b;
}
input:
3
1 2
2 4
3 4
output does not contain anything
You use the array out of bounds and delete when you should delete[]. Comments in code:
#include <iostream> // use the correct headers
#include <cstddef>
// not recommended: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
using namespace std;
int main() { // main must return int
size_t a; // better type for an array size
cin >> a;
int** b;
b = new int*[a];
for(size_t i = 0; i < a; i++) {
b[i] = new int[2];
for(size_t j = 0; j < 2; j++) {
cin >> b[i][j];
}
}
int count = 0;
std::cout << a * (a - 1) << "\n"; // will print 6 for the given input
for(size_t i = 0; i < a * (a - 1); i++) {
// i will be in the range [0, 5]
for(size_t j = 0; j < a; j++)
if(b[i][0] == b[j][1]) count = count + 1;
// ^ undefined behaviour
}
cout << count << endl;
for(size_t i = 0; i < a; i++) {
delete[] b[i]; // use delete[] when you've used new[]
}
delete[] b; // use delete[] when you've used new[]
}

Linear Recursion reverse the array

Can not figure out why my recursion function does not work?
#include <iostream>
using namespace std;
int ReverseArray(int* A, int i, int j);
int main()
{
int j = 10;
int i = 0;
int *b = new int[j];
for (int i = 0; i <= 10; i++)
b[i] = i;
for (int i = 0; i <= 10; i++) //just to compare the old and new array
cout << b[i] << endl; //just to compare the
for(int i = 0; i <= j; i++)
cout << ReverseArray(b,i,j) << endl;
system("pause");
return 0;
}
int ReverseArray(int* A, int i, int j)
{
if (i <= j)
{
swap(A[i], A[j]);
ReverseArray(A, i + 1, j - 1);
}
return A[i];
This should return
10,9,8....
but it returns
10,0,9,1...
I don't get why its happening
You have a double loop, once here:
for(int i = 0; i <= j; i++)
cout << ReverseArray(b,i,j) << endl;
and once here:
ReverseArray(A, i + 1, j - 1);
Calling a function recursively is equivalent to looping over it. To reverse a list, you only need to loop over it once, and what you've done is the equivalent of a doubly-nested loop. So let's get rid of
for(int i = 0; i <= j; i++)
and change
cout << ReverseArray(b,i,j) << endl;
to just
ReverseArray(b,i,j);
Then you are only reversing b, nothing else. To print, just loop from 0 to 10 and print each element.
Also, unrelated, but keep in mind that the code as you have it right now touches memory that has not been allocated to the heap.
int *b = new int[j];
creates j (here, 10) ints, at the physical memory locations b, b + 1, b + 2, ..., b + 9. b[i] then gets the memory held at b + i, that is, it gets *(b + i). Several of your loops try to do things with b[10], and there has not been enough memory allocated for it. This will result in undefined behaviour (i.e. many different things can happen depending on your compiler and the state of your computer). With 'system("pause");' removed (which shouldn't affect code execution) on my machine, this gave me a memory allocation for that reason.
Solution here is to either have
int *b = new int[j+1];
or replace all your <= signs with <.

multidimensional array function outputting garbage?

I have this function meant to initialize a multidimensional 2d (6x6) array to zero. I call the function in main using cout to test it and it outputs garbage. Please help. Thanks!
int** initializeArray(void)
{
typedef int* rollArray; //this line is actually outside of the function in my
//program
int i, j;
rollArray *m = new rollArray[6];
for (i = 0; i < 6; i++)
m[i] = new int[6];
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
m[i][j] = 0;
return m;
}
If the value 6 is known at compile-time, I would suggest using std::array in a nested fashion. For example:
#include <array>
#include <iostream>
int main()
{
std::array<std::array<int,6>,6> a = {0};
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
std::cout << a[i][j] << std::endl; // Prints 0.
}
}
return 0;
}
In fact, you won't even need to create a function to initialize your array. Declare your nested array and you are good to go. (If you don't know the dimension at compile-time, you could use std::vector in a similar fashion.)
The problem is with your test.
How can you mess up such a simple test? Just use:
int ** a = initializeArray();
int i,j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}

Position 2D array bug as parameter causes memory dumps

This is my program in C++, which accepts an 2D array a[m][n]. If an element a[i][j] is zero, then set all the ith row and jth column elements to zero.
This is code sample:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class SetZero{
public:
static void setZero(int **, int , int);
};
void SetZero::setZero(int ** a, int m, int n){
int i, j, k;
int ** b = new int *[m]; //flags to identify whether set to zero or not.
for(i = 0; i < m; i++){
b[i] = new int[n];
for(j = 0; j < n; j++)
b[i][j] = 1;
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(a[i][j] == 0 && b[i][j]){//DUMP here. If I change it to (a+i)[j], then works.
for (k = 0; k < n; k++){
a[i][k] = 0;//but there is NO dump here. Weird!
b[i][k] = 0;
}
for(k = 0; k < m; k++){
a[k][j] = 0;
b[k][j] = 0;
}
j = n;//break. next row loop.
}
for(int i = 0; i < m; i++)
delete[] b[i];
delete[] b;
}
int main(){
int a[4][5];
srand(time(NULL));
for(int i = 0; i < 4; i++){//create an 2D array
for(int j = 0; j < 5; j++){
a[i][j] = rand() % 100;
cout << a[i][j] << " ";
}
cout << endl;
}
SetZero::setZero((int **)a, 4, 5);//type cast.
cout << endl;
for(int i = 0; i < 4; i++){//print result
for(int j = 0; j < 5; j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Environment: WIN8 Visual Studio 2012.
Edit:
The program can compile but cannot execute normally. It will stop when it reaches if(a[i][j] == 0 && b[i][j]){
The error message is:
Unhandled exception at 0x012875DD in CCLC.exe: 0xC0000005: Access
violation reading location 0x0000004B.
SetZero::setZero((int **)a, 4, 5)
a is not an array of pointers, it is simply a 2 dimensional array.
notice how the access violation is reading address 0x0000004B? that's 75, a number between 0 and 99 :) because you are treating a 2 dimensional array (which is just a one dimensional array with a neat way of accessing it) as an array of arrays, it is taking one of the values in your array (75) to be the address of a sub array, then trying to read the non existent array at address 75 (or 0x0000004B)
I suggest that you 'flatten' your arrays and work with them as one dimensional arrays, which I find simpler:
void SetZero::setZero(int * a, int m, int n){
int i, j, k;
int * b = new int [m*n]; //flags to identify whether set to zero or not.
for(i = 0; i < m; i++){
b[i] = new int[n];
for(j = 0; j < n; j++)
b[i*n+j] = 1;
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(a[i*n+j] == 0 && b[i*n+j]){//DUMP here. If I change it to (a+i)[j], then works.
for (k = 0; k < n; k++){
a[i*n+k] = 0;//but there is NO dump here. Weird!
b[i*n+k] = 0;
}
for(k = 0; k < m; k++){
a[k*n+j] = 0;
b[k*n+j] = 0;
}
j = n;//break. next row loop.
}
delete[] b;
}
int main(){
int a[4*5];
srand(time(NULL));
for(int i = 0; i < 4; i++){//create an 2D array
for(int j = 0; j < 5; j++){
a[i*5+j] = rand() % 100;
cout << a[i*5+j] << " ";
}
cout << endl;
}
SetZero::setZero(a, 4, 5);//type cast.
cout << endl;
for(int i = 0; i < 4; i++){//print result
for(int j = 0; j < 5; j++)
cout << a[i*5+j] << " ";
cout << endl;
}
return 0;
}
One suggestion about the SetZero(). There is a function called memset() which allows you to set all bytes to a specific value given a starting pointer and the range. This function could make your SetZero() function more cleaner:
void * memset ( void * ptr, int value, size_t num );
Fill block of memory. Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
Parameters
ptr: Pointer to the block of memory to fill.
value: Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num: Number of bytes to be set to the value, size_t is an unsigned integral type.
For example, the following code block from your program:
for (k = 0; k < n; k++){
a[i][k] = 0;//but there is NO dump here. Weird!
b[i][k] = 0;
}
can be achieved by memset in a cleaner way:
memset(a[i], 0, n * sizeof(int));
memset(b[i], 0, n * sizeof(int));