Nested for loop filling an array - c++

I am trying to create a nested for loop that fills in values in an array from 1 to 20.
IE) array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
int array[20];
for(int i = 0; i<21; i++)
{
for(int j =1; j<21; j++)
{
array[i] = j;
cout<< array[i];
}
}
Supposedly, The array index should count up with "i", and should be equated to "j" which is also counting up. The array element is printed to the console as it is filled.
I expected 1 -20 to be printed out once, but when I run the code, 1-20 prints out multiple times. Can someone tell me the problem? Thanks!

Your outer for loop runs 21 times, your inner for loop runs 20 times each of the outer for loop iterations, so you have a total of 21 * 20 = 420 print statements.
You can simply do
for(int i = 0 ; i < array.length ; i++)
{
array[i] = i + 1;
cout << array[i] << endl;
}

If you look at your array when you're done, it will also be just a series of 20s. The first loop is saying "do this 20 times" and then the second loop is saying "set and print the value of that array element 20 times." What you need to do is include a check for whether you're assigning the correct j value to the correct array[i] value, and only set the value in that case. Something like:
if (j == i + 1) array[i] = j;

Why do you need a nested loop?
for(int i = 0; i<20; i++)
{
array[i] = i + 1;
cout<< array[i];
}

yes, you have two loops when you only need one:
for(int i = 0; i<21; i++)
{
array[i] = i + 1;
cout<< array[i];
}

In order to fill the array and to print the result you just need two simple for loops
for(int i = 0; i<20; i++)
{
array[i] = j;
}
for(int j =0; j<20; j++)
{
cout<< array[i];
}
The nested loop that you created above will do exactly what you described.
For each loop of the outer for loop it will execute the full 20 loops of the inner loop.
so in total you will execute it 21 * 20 times.
Also be careful with your index. You want to start with int i = 0 to i < 20 which loops exactly 20 times.

I don't know why you are attempting to print a single element in you array, but it isn't necessary to use nested loops here; in fact, a loop isn't required at all:
// vector version
std::vector<int> vec(20);
std::iota(vec.begin(), vec.end(), 1);
// array version
int arr[20];
std::iota(std::begin(arr), std::end(arr), 1);
If you want to print out the whole array after you've initialized it:
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));

I see a lot of people answered about this question, so I will not repeat them, I'll just mention that you are writing outside the array size.
if you have int array[20], you should loop
for(int i = 0; i<20; i++)
the last index is 19

The outer loop 21 times repeats the inner loop
for(int i = 0; i<21; i++)
{
for(int j =1; j<21; j++)
{
array[i] = j;
cout<< array[i];
}
}
The inner loop does the same operation that is assigns elements of the array sequantial numbers. Moreover your code has a bug because due to the outer loop youare trying to access element array[20] that does not exist, because if the array was defined as
int arrat[20];
then the valid indicies are 0 - 19.
That do not bother about writing correctly required loop or loops you could use standard algorithm std::iota
For example
#include <iostream>
#include <numeric>
#include <iterator>
#include <algorithm>
int main()
{
const size_t N = 20;
int array[N];
std::iota( std::begin( array ), std::end( array ), 1 );
std::copy( std::begin( array ), std::end( array ), std::ostream_iterator<int>( std::cout, " " ) );
}
Or instead of the algorithms you could use the range based for statement. For example
#include <iostream>
int main()
{
const size_t N = 20;
int array[N];
int i = 1;
for ( int &x : array )
{
x = i++;
std::cout << x << ' ';
}
}

If you really want to use nested solution, (for example game board coordinates) then this is my solution.
// nesting arrays for example game board coordinates
#include <iostream>
int main(){
int x = 20;
int y = 40;
int array[x][y];
// initialize array of variable-sized.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
array[i][j] = 0; // or something like i + j + (i * (y-1)) if you wish
// and send it to cout
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
//notice, that when sent to cout like this, x and y flips on screen, but
//logics of coordinates is ok
// and then do something usefull with it
return EXIT_SUCCESS;
}

int size = 20;
for (int i = 0; i < size; i++)
{ int array[i];
array[i] = i + 1;
cout << array[i]<< " ";
}
You could populate your array with 1 for loop, and gauge the size of your array like stated above.

Related

execution order for cout in C++

c++
When printing to console, if function execution is sequential it would seem logical the ordered array would be printed after calling insertionSort, however order list does not print until next loop. Any help would be appreciated.
#include <stdio.h>
#include <iostream>
#include <array>
using namespace std;
void insertionSort(int* array, int size) {
for (int i = 1; i < size; i++) {
int key = i - 1;
while (i > 0 && array[key] > array[i] ) {
int tmp = array[i];
array[i] = array[key];
array[key] = tmp;
i -= 1;
key -= 1;
}
}
}
const int ARRAY_MAXSIZE = 5;
int main(void) {
int *array = (int*)calloc(ARRAY_MAXSIZE, sizeof(int));
int input;
cout << "Enter 5 digits\n";
for (int size=0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
insertionSort(array, size);
for (int j=0; j <= size; j++) {
cout << array[j];
}
cout << '\n';
}
}
Console Entry
This is a classic off-by-one error. Your insertionSort expects you to pass the number of elements to sort via the parameter size. But your main loop is always holding a value that is one less than the size immediately after adding an element.
I want to say that bugs like this are easily discovered by stepping through your program's execution with a debugger. If you don't know how to use a debugger, start learning now. It is one of the most important tools used by developers.
Anyway, the quick fix is to change your function call to:
insertionSort(array, size + 1);
However, as Paul McKenzie pointed out in comments, it's a bit crazy to do this every time you add a new element because your function sorts an entire unsorted array. Your array is always nearly sorted except for the last element. You only need to call that function once after your input loop is done:
// Read unsorted data
for (int size = 0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
}
// Sort everything
insertionSort(array, ARRAY_MAXSIZE);
// Output
for (int j = 0; j < ARRAY_MAXSIZE; j++) {
cout << array[j];
}
cout << '\n';
But if you want every insertion to result in a sorted array, you can "slide" each new value into place after inserting it. It's similar to a single iteration of your insertion-sort:
// Sort the last element into the correct position
for (int i = size; i >= 1 && array[i] > array[i - 1]; i--)
{
std::swap(array[i], array[i - 1]);
}
Even better, you don't need to swap all those values. You simply read the value, then shuffle the array contents over to make room, then stick it in the right spot:
// Read next value
cin >> input;
// Shuffle elements to make room for new value
int newPos = size;
while (newPos > 0 && array[newPos - 1] > input) {
array[newPos] - array[newPos - 1];
newPos--;
}
// Add the new value
array[newPos] = input;

comparing one array element with the next element to find what is the biggest element

I'm trying to find a way to iterating while comparing the element with the next element to find what is the biggest element in the array. But, the output i want keep repeating as much as the loop run.
int main(){
int array[4];
for ( int i = 0; i < 4; i++){
cin >> array[i];
}
for (int i:array){
for (int j = 1; j < 4; j++){
if (i < array[j]){
break;
}
if (i > array[j] ){
cout << i;
}
}
}
}
You can use the following program to find the biggest element in the array. Note that there is no need to use two for loops as you did in your code snippet.
#include <iostream>
int main()
{
int array[4] = {1,10, 13, 2};
int arraySize = sizeof(array)/sizeof(int);//note that you can also use std::size() with C++17
int startingValue = array[0];
for(int i = 1; i < arraySize; ++i)//start from 1 instead of 0 since we already have array[0]
{
if(array[i] > startingValue)
{
startingValue = array[i];
}
}
//print out the biggest value
std::cout<<"the biggest element in the array is: "<<startingValue<<std::endl;
return 0;
}
Your program is reapeating output because you have the cout inside the if which is satisfied multiple times(depending upon how big the array is and what elements it contains). For example, if you try your example on the array int array[] = {23,2,13,6,52,9,3,78}; then the output of your program will be 2323231313652525293787878 . So the output is reapeating more than 2 times. You can instead use the version i gave that uses only 1 for loop and prints the correct biggest element only once.
Note that you can also use std::size with C++17 while sizeof(array)/sizeof(int) works with all C++ versions.

Looking for solution to array and cout interaction in C++

I want a function or loop to run through the array and print each element out until it has printed 10 elements. In which case, a new line is started and the printing continues. eg. 1 2 3 4 5
6 7 8 9 10
This is for a program that works an array like a 50's housewife performing many calculations and alterations to said array.
This is my current attack on the logic behind my issue.
int main()
{
test = new int[100];
for (int i = 0; i < 100; i++){
//Set array to rand
test[i] = rand() % 44 + 55;
}
printf("original List\n");
for (int i = 0; i < 100; i++){
// print original order
printf("%d\n", test[i]);
}
sortArr;
// function call sort array ascend
printf("\Sorted List\n");
for (int i = 0;i < 100;i++) {
// print sorted order
printf("%d , ", test[i]);
int temp;
//temp counter for width of printout
for (temp = 0;temp < 10;temp++) cout<< "\n" << endl;
sum += test[i];
}
Expected is a block of output consisting of 100 array elements in a grid with a width of 10 elements per line.
Actual result is a mess of new line loops and further headache to me.
Pretty common issue just use a modulus based on the index i:
for (int i = 0;i < 100;i++) {
printf("%d , ", test[i]);
if ((i + 1) % 10 == 0) {
printf("\n");
}
}
If you want nicely formatted output however you'll need:
#include <iomanip>
and
std::cout << std::setw(/*max_len*/) << test[i];
The simplest solution would be to print the delimiter (i%10 == 0) ? "\n" : ", ". You correctly recognized that taking the remainder on every iteration of the loop is inefficient, and wanted to write one that would print ten elements followed by a newline.
The trick there is to write an inner loop that increments a second counter, j, do all your output within the inner loop, and then update i at the bottom of the outer loop. A simplified example:
#include <array>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using std::cout;
int main()
{
constexpr size_t ARRAY_LEN = 100;
std::array<int, ARRAY_LEN> test;
{
// Quick and dirty initialization of the random seed to the lowest 30
// or so bits of the system clock, which probably does not really have
// nanosecond precision. It’ll do for this purpose.
timespec current_time;
timespec_get( &current_time, TIME_UTC );
srand(current_time.tv_nsec);
}
for (int i = 0; i < test.size(); i++){
//Set array to rand
test[i] = rand() % 44 + 55;
}
for ( int i = 0, j = 0;
i < test.size();
i += j ) {
for ( j = 0; j < 10 && i + j < test.size(); ++j ) {
cout << test[i + j] << ' ';
}
cout << '\n';
}
return EXIT_SUCCESS;
}
Note that the version you wrote does not initialize the standard library’s random seed, so you get the same (poorly-distributed) random numbers. You could write a version that uses the much superior STL random-number generators and perhaps <chrono>, instead of the C versions, but that’s a bit outside the scope of your question.

how can I work with the last element of iterations

for(int t(0); t < 10;++t) { cout<<t<<endl;}
I'm just biginer in C++, and want to know how can I take the last elemnt of my "cout...."; in this case my laste element is 9
thx for help ;)
int c = 0;
for(int t = 0; t<10; t++)
{
c = t;
}
cout<<c;
This might be what you are looking for I am not sure I understand your question properly though.The variable c should hold the last element of t when the loop ends.
You can extract int t from the for loop :
int t;
for (t = 0; t < 10; ++t)
{
cout << t << endl;
}
int t = 9;
cout << t << endl;
Now you have the last element, #9.
ghagha, in C++ the ranges are run from 0 to n-1, in your example you have a range of 0 to < 10 hence 0 to 9, therefore your last element is 9. But as I said you can do any range as n-1 for the last element, provided that it follows normal conventions (it is possible to have a range from 1 to n if you code it that way)
It is not clear what you want but in any case your loop contains a bug. Instead of
for(int t(0); t < 10; t) { cout<<t<<endl;}
should be
for(int t(0); t < 10; t++) { cout<<t<<endl;}
that is variable t has to be incremented.
One simple way -
int t = 0;
for (; t < 10; ++t)
cout << t << ;
Tough the correct way to do it will be (one variable should not have two meanings, i.e 1. last element, 2. iterator context) -
int last_element;
for (int t = 0; t < 10; ++t;
{
cout << t << ;
last_element = t;
}

C++: Number Arranging Program Not Working Properly

I have tried making a program to sort numbers of an array.
I have done my best but there is this problem: Although I do a loop to swap the numbers and arrange them, when I output the array, nothing changes and the array remains the same.
The code will make everything clearer
This is the main function:
int main(){
int arr[10];
//For loop to get from user numbers to be put into the array
for ( int i = 0; i<10; i++){
cout << "Enter the number to be recorded: ";
cin >> arr[i];
cout << endl;
}
// Set counter n to 0 ( counts numbes of number swaps)
int n = 0;
do {
//re sets counter to 0
n=0;
//Check the entire loop if arr[i] bigger than arr[i+1] and swaps their values if true then adds 1 to n
for ( int i = 0; i>9; i++){
if(arr[i]>arr[i+1]){
swap(&arr[i], &arr[i+1]);//swaps by sending the addresses of the two array elements the pointers in the swap function
n++;
}
}
}while(n>0); // if counter = 0 then end (therefore the numbers are arranged correctly since no swapping happened)
cout << "The numbers ordered are:\n\n";
// Loop to output the arranged array
for (int i =0; i<10; i++){
cout << arr[i] << ", ";
}
cout<<endl;
system("PAUSE");
return 0;}
This is the swap function:
void swap ( int *p, int *t){
int temp;
temp = *p;
*p = *t;
*t = temp;}
I hope you guys can help me with my problem here and tell me what's wrong with this code
Thank you all
Look closely at your for loop...its contents will never be executed.
for ( int i = 0; i>9; i++){ ... }
The condition i>9 should be i<9.
for ( int i = 0; i>9; i++){
^^^
here is your problem
you have initialized the i to the 0 and checking the condition is that if i is greater than 9 which is not never true so the condition of the for loop is false and so it will be terminated
it should be
for( int i = 0; i<9; i++) than the
result
i=0 condition i<9 true { come in the function body}
i=1 condition i<9 true { come in the function body}
.
.
.
i=8 condition i<9 true { come in the function body}
i=9 condition i<9 false { }