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 8 days ago.
Improve this question
I'm trying to create an array of 13 numbers and fill it in a loop with even numbers descending, starting from 48. I can't tell exactly what to do with my code to make it work.
#include <iostream>
using namespace std;
int main() {
const int size = 13;
int arr[size] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
int a = 50;
while (a > 0){
a-=2;
cout << a << " " << endl;
for (int i = 0; i < size; i++)
{
arr[i] = a;
cout << i << " " << arr[i] << endl;
}
}
}
It's giving bunch of nonsense which i don't understand.
A no loop solution, using iterator and algorithms
using namespace std;
int main(int argc, char * argv[])
{
constexpr int N= 13;
array<int, N> t;
iota(t.begin(), t.end(),0);
transform(t.begin(), t.end(), t.begin(), [](int x) { return 48-2*x;});
copy(t.begin(), t.end(), ostream_iterator<int>(cout, " "));
return 0;
}
I do not know why you do have the Outer loop, but it seems you are New to Coding all in all, So I Won't give you anything that you wouldn't understand at this point. But I'll explain why you are getting "a bunch of nonsense which you don't understand."
while (a > 0){
a-=2;
cout << a << " " << endl;
this will run while a is greater than 0, but every time the Loops restart. it does this.
for (int i = 0; i < size; i++)
{
arr[i] = a;
cout << i << " " << arr[i] << endl;
}
Hence a lot of numbers will show up, you aren't really "inserting" a number into the array, you are "REPLACING" the whole array every loop. Have a look at this, I inserted a few outputs which would show what is happening in your code.
Without changing too much of your code, here is one way to do it in that is still in your depth. Instead of doing a while(a > 0), simply loop through the Array with a for loop, then decrement a by 2 each loop, since your goal is only to fill the array with a size of 13 and don't need to wait until a is exhausted of positive numbers.
int main() {
const int size = 13;
int arr[size] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
int a = 50;
for (int i = 0; i < size; i++)
{
a-=2;
arr[i] = a;
cout << i << " " << arr[i] << endl;
}
}
Lastly, Please indent your code properly next time, it makes it much easier to understand your code, not only for us but for you as well.
It is enough to use two range-based for loops. For example
const int size = 13;
int arr[size];
int value = 48;
for ( auto &item : arr )
{
item = value;
value -= 2;
}
for ( const auto &item : arr )
{
std::cout << item << ' ';
}
std::cout << '\n';
If you want to fill the array with even numbers in the descending range [48, 0) then the array needs to have 24 elements instead of 13 elements.
Here is a demonstration program where instead of the range-based for loop there are used standard algorithms (of course you may use the range-based for loops shown above).
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
const int N = 48;
int arr[N / 2];
int value = N + 2;
std::generate( std::begin( arr ), std::end( arr ),
[&value] { return value -= 2; } );
std::copy( std::begin( arr ), std::end( arr ),
std::ostream_iterator<int>( std::cout, " " ));
std::cout << '\n';
}
The program output is
48 46 44 42 40 38 36 34 32 30 28 26 24 22 20 18 16 14 12 10 8 6 4 2
Again if you need an array with only 13 elements then declare it explicitly like
int arr[13];
As for your code when within the outer while loop are are outputting anew the array in the inner for loop setting its all elements to the current value of a.
while (a > 0){
a-=2;
cout << a << " " << endl;
for (int i = 0; i < size; i++)
{
arr[i] = a;
cout << i << " " << arr[i] << endl;
}
}
that does not make sense.
Related
im trying to print the first 10 and the last 10 elements of an array. My attempt below returns the following in an infinite loop
Word: Count 0
void printarrayString(std::string arr[], int size)
{
int i;
int j;
std::cout << "***first 10 elements***" << std::endl;
for (i = 10; i < size; i++)//print first 10 elements
std::cout << "Word: " << wordArr[i] << " " << "Occurs: " << countArr[i] << std::endl;
std::cout << std::endl;
std::cout << "***last 10 elements***" << std::endl;
for(j = 10; j < size-10; j-- ) //print last 10 elements
std::cout << "Word: " << wordArr[i] << " " << "Occurs: " << countArr[i] << std::endl;
std::cout << std::endl;
}
How can i fix the loops so loop 1 prints the first 10 elements of wordArr and countArr and loop 2 prints the last 10 elements? Thankyou
You have got the indices wrong. In C++ (and even in most programming languages) the base, or first element is located at index 0 (ever wonder why?). So, to print the first n elements, you need to iterate from i = 0 to i = n - 1, aka for(int i = 0; i < n; i++) and to print the previous n elements, you need to iterate from i = n - 1 to i = 0, aka for(int i = n - 1; i >=0; i--).
PS: 0 based indexing => no extra calculations to find the first element after locating the base ;)
As above, in C++, array indices are zero-based. Also, you should check whether you actually have 10 elements. And 'wordArr' and 'countArr' are undefined, perhaps declared elsewhere. Here's my guess at what you want to achieve. The std::min() function comes from the algorithm std library.
#include <algorithm>
#include <iostream>
using namespace std;
void printarrayString(string arr[], int size)
{
//Check we have 10 elements. If not, use fewer
int nElementsToPrint = min(10,size);
//First 10 (if possible) elements
for(int i =0; i < nElementsToPrint; i++)
{
cout << "Word: " << arr[i] << " Occurs: " << i;
}
cout << endl;
//etc etc
}
You can do the last 10 elements in the same way, though you haven't said if you want them in the same order as in the string (starting at (size-nElementsToPrint) and forwards with i++), or the last element first (starting at (size-1) and backwards with i--).
Im a bit new to programming , Trying to get the idea of Algorithm so i started by Sorting Algorithms.So ive read a lot about it and tried to understand its idea then started by Bubble Sort,But im having a problem in my code , Can someone tell me if im thinking over this correctly ? Im not sure that im still on the right way for this.
EDIT: I want to have the user insert a certain amount of numbers in an array , Then these unarranged numbers to be swapped using the Bubble-Sort.
so here's the code :
#include <iostream>
using namespace std;
int main(){
int arr[6];
int temp;
cout << "Enter an unarranged amount of numbers(6) \n";
for(int i=0;i<6;i++){
cin>>arr[i];
}
cout << "Normal List : ";
for(int i=0;i<6;i++){
cout << arr[i] << " ";
}
//Sorting
for(int i=0;i<6;i++){
for(int x=0;x=i+1;x++){
if(arr[i]>arr[x]){
temp=arr[x];
arr[x]=arr[i];
arr[i]=temp;
}
}
cout << arr[i] << " ";
}
return 0;
}
This loop
for(int x=0;x=i+1;x++){
is an infinite loop because in the condition of the loop there is used the assignment
x=i+1
So the value of x that is the value of the condition is never will be equal to 0.
And the bubble sort algorithm compares and swaps adjacent elements of an array.
Also you could use the standard function std::swap to swap elements of the array.
The loops that implement the bubble sort can look for example the following way as it is shown in the demonstrative program below
#include <iostream>
#include <utility>
int main()
{
const size_t N = 6;
int arr[N];
std::cout << "Enter an unarranged amount of " << N << " numbers: ";
for ( auto &item : arr ) std::cin >> item;
std::cout << "Before sorting: ";
for ( const auto &item : arr ) std::cout << item << ' ';
std::cout << '\n';
for ( size_t n = N, last = n; !( n < 2 ); n = last )
{
for ( size_t i = last = 1; i < n; i++ )
{
if ( arr[i] < arr[i-1] )
{
std::swap( arr[i], arr[i-1] );
last = i;
}
}
}
std::cout << "After sorting: ";
for ( const auto &item : arr ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
Its output might look for example like
Enter an unarranged amount of 6 numbers: 6 3 1 2 4 5
Before sorting: 6 3 1 2 4 5
After sorting: 1 2 3 4 5 6
As for your code then the inner loop should look at least like
for(int x = 1; x < 6; x++ ){
if ( arr[x-1] > arr[x] ){
temp=arr[x];
arr[x]=arr[x-1];
arr[x-1]=temp;
}
}
and remove this statement after the loop
cout << arr[i] << " ";
#include <iostream>
using namespace std;
/* This code is not working as it does not insert the value of item in the
array instead the value of item is zero. But i have troubleshooted this
problem and figured out that the code works fine if i define "int item" as
constant variable or use int i as global variable instead of defining in the
for loop. so my question is what is the reason behind this malfunctioning or
is there any programming secret i haven't aware of yet*/
int main()
{
int LA[] = {1, 3, 64, 98, 54};
int k = 3;
int n = 5;
int item = 46;
int j = n;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
n++;
for( ; j >= k; j-- )
{
LA[j+1] = LA[j];
}
LA[k] = item;
cout << endl << "After insertion" << endl << endl;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
return 0;
}
LA has a fixed size. It is a static array, and you cannot change the size in c or c++. Currently j will be 5 and you will attempt to access LA[5] which is outside the bounds of the array and Undefined Behaviour.
You have 3 options:
Reserve enough space in your static array to hold everything you need: LA[10] = {...
Use dynamic memory and resize: int *LA = new int[10]; (Look this method up)
The best, use a std::vector<int>.
If you wanna insert item as k'th element of array, You should know that the LA array has not 6th index (LA[6]). So before the second loop, initialize j with n-1.
Also if you wanna have all the values, You should use std::vector which can add the values and indexes, dynamically.
For further studies about vectors see this link: Here
I'm trying to show a ranking list of my array qt, which contains 5 numbers.
int i, j;
int qt[5] = {10,20,10,50,20};
int tempqt;
for (i=0; i<5; i++)
{
for(j=(i+1); j<5; j++)
{
if (qt[i] >= qt[j])
{
tempqt = qt[i];
qt[i] = qt[j];
qt[j] = tempqt;
}
}
}
for(i=0; i<5; i++)
{
cout << i+1 << ".number: " << qt[i] << endl;
}
normally, the 2 for-loops sort my array and the last for-loop displays my array ordered, so it looks like this:
1.number: 10
2.number: 10
3.number: 20
4.number: 20
5.number: 50
But I want to display the numbers with the same value as the same ranking position, so like this:
1.number: 10
1.number: 10
2.number: 20
2.number: 20
3.number: 50
The idea is to increase rank counter when meet different value in qt array.
i = 0;
int rank = 1, val = qt[i];
cout << rank << ".number: " << qt[i] << endl;
for(i=1; i<5; i++)
{
if (qt[i] != val) {
++rank;
val = qt[i];
}
cout << rank << ".number: " << qt[i] << endl;
}
Use std::sort to sort the array -- you won't get anywhere until the array is sorted.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int qt[5] = { 10, 20, 10, 50, 20 };
sort(qt, qt + 5);
int count = 1;
for (int i = 0; i < 5; ++i)
{
if (i > 0)
{
if (qt[i] != qt[i - 1])
++count;
}
cout << count << ".number: " << qt[i] << endl;
}
}
Here is another solution using a map. This is more "lazy" in that there is no real "check if number already seen" logic involved. Just add numbers to a map, and print out the results in a loop.
If there are no memory constraints (you will need to create a map of the numbers, of course), and/or you need the array to remain stable (not sorted), then this could be an alternative.
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int qt[5] = { 10, 20, 10, 50, 20 };
std::map<int, int> IntMap;
// add entries to map, adding to a counter each time
for (int i = 0; i < 5; ++i)
IntMap[qt[i]]++;
// output the results.
int count = 1;
for (auto it = IntMap.begin(); it != IntMap.end(); ++it, ++count)
{
for (int i = 0; i < it->second; ++i)
cout << count << ".number: " << it->first << endl;
}
}
The map already sorts, so that's taken care of. Then the map is set up to count the number of times each number shows up, so that's taken care of. The only thing left is to write a loop that just goes through the map and prints the information.
See it here: http://ideone.com/q08SeX
I'd rather use a do while loop:
int p = 1, x = 0;
do
{
cout << p << ".number: " << qt[x++] << endl;
if (x < 5 && qt[x] != qt[x-1])
p++;
} while (x < 5);
I am trying to understand sorting algorithms, so based on googled examples/explanations I wrote the below code. Code works 80% of the time. Every once in a while it doesn't sort properly and I can not see why.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void setArray( int *, const int & );
void selectionSorting( int *, const int & );
int main()
{
int numOfElem;
cout << "Num of array elements: ";
cin >> numOfElem;
cout << '\n';
int array[numOfElem];
setArray(array, numOfElem);
selectionSorting(array, numOfElem);
cout << '\n';
return 0;
}
void setArray( int *array, const int & numOfElem ){
srand(time(0));
cout << "Original array: " << '\n';
for (int i=0; i<numOfElem; i++){
array[i] = rand()%30;
cout << array[i] << ' ';
}
cout << '\n';
}
void selectionSorting( int *array, const int &numOfElem ){
int eff_size, swap;
int maxpos = 0;
for (eff_size = numOfElem; eff_size>1; eff_size--){
// loop searching for a position of largest number in the array
for (int i=0; i<eff_size; i++){
maxpos = array[i] > array[maxpos] ? i : maxpos;
}
swap = array[maxpos];
array[maxpos] = array[eff_size-1];
array[eff_size-1] = swap;
}
cout << "Selection Sorting: " << '\n';
for (int i=0; i<numOfElem; i++){
cout << array[i] << ' ';
}
}
Example output:
Num of array elements: 5
Original array:
7 17 1 12 25
Selection Sorting:
1 7 17 25 12
I can't see any pattern to the sorting failing - it fails in different places, weather there are repeated numbers, regardless of how many numbers I provide etc...
On each iteration of the outer loop(over eff_size) you should re-set maxpos to 0. Otherwise you have the chance that maxpos goes out of the effective portion being sorted(this happens if the maximum element is last in the effective portion i.e. if maxpos==effsize).