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 { }
Related
as the title says I'm attempting to compare elements in an array. My intent is to have the user enter 3 integers into the program, thereafter it should increment through this array comparing the the 1st number to the 2nd, and so forth and swapping the element's from order of lowest to highest.
My issue currently is that it will swap the first and second elements but the third causes an integer overflow due to me comparing and assigning an integer in an index higher than the initialized array can hold.
I'm currently drawing a blank as to how I could still compare these numbers in this manner without causing it to overflow.
A hint or perhaps a whole different perspective would be appreciated.
#include "E:/My Documents/Visual Studio 2017/std_lib_facilities.h"
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
//This should swap the elements from smallest to greatest
for (int i = 0; i = 3; i++)
{
if (numbersArray[i] > numbersArray[i+1])
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
//swap(numbersArray[i], numbersArray[++i]);
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
keep_window_open();
return 0;
}
You will need to modify this to suit your needs, but this should get you on the right track. One important thing to investigate is how you decided to sort the elements. Your sorting needs to be looped, otherwise, you won't necessarily sort the entire array (depending on your inputs).
#include <iostream>
using namespace std;
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
for(int loop = 0; loop <3; loop++){
//This should swap the elements from smallest to greatest
for (int i = 0; i < 2; i++)
{
if (numbersArray[i] > numbersArray[i+1]){
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
}
//swap(numbersArray[i], numbersArray[++i]);
}
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
return 0;
}
I want to make a program that lets the user insert some numbers to the array and the print it out afterwards. Problem is when I try to do that (lets say the size of my array is 100) then:
What it should do: Inserted- 1,2,3,4,5 -> should print 1,2,3,4,5
But instead it prints -> 1,2,3,4,5,0,0,0,0,0,0, .... up to the size of my array.
Is there any way I can get rid of those zeros?
Code:
int SIZE = 100;
int main()
{
int *numbers;
numbers = new int[SIZE];
int numOfElements = 0;
int i = 0;
cout << "Insert some numbers (! to end): ";
while((numbers[i] != '!') && (i < SIZE)){
cin >> numbers[i];
numOfElements++;
i++;
}
for(int i = 0; i < numOfElements; i++){
cout << numbers[i] << " ";
}
delete [] numbers;
return 0;
}
You increase numOfElements no matter what the user types. Simply do this instead:
if(isdigit(numbers[i]))
{
numOfElements++;
}
This will count digits, not characters. It may of course still be too crude if you want the user to input numbers with multiple digits.
Get numOfElements entered from user beforehand. For example
int main() {
int n;
cin >> n;
int * a = new int[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
for (int i = 0; i < n; ++i)
cout << a[i] << endl;
delete[] a;
}
Input
4
10 20 30 40
Output
10 20 30 40
Since you declared array size, all indices will be zeros.
User input changes only the first x indices from zero to the value entered (left to right).
All other indices remains 0.
If you want to output only integers different from 0 (user input) you can do something like that:
for(auto x : numbers){
if(x!=0)cout<<x<<" ";
}
You can use vector and push_back the values from user input to get exactly the
size you need without zeros, then you can use this simple code:
for(auto x : vectorName)cout<<x<<" ";
Previous solutions using a counter is fine.
otherwise you can (in a while... or similar)
read values in a "temp" var
add if temp non zero
exit loop if counter >= SIZE-1 (you reach max slots)
increment counter
when You will print, form 0 to counter, you will get only non zero values.
I am attempting to fill an array backwards from 20 to 0 but whenever I print it out it still prints out forwards. For instance I want to put in 1,2,3,4,5 and have it come out as 5,4,3,2,1.
I have attempted to do a for loop that counts backwards from 20 to 0 but when i print it it is still coming out incorrect. Any help?
int temp;
for (int i = 20; i > 0; i--)
{
cout << "Please enter the next number. Use a -1 to indicate you are done: ";
cin >> temp;
while(temp > 9 || temp < -2)
{
cout << "You may only put numbers in 0 - 9 or -1 to exit. Please enter another number: ";
cin >> temp;
}
arr1[i] = temp;
cout << arr1[i];
}
for (int i = 21; i > 0; i--)
{
cout << arr1[i];
What's the size of your array?
Assume that the size is 21 (indexes from 0 to 20).
First of all please note that your first loop will never populate the array at index 0 (something like this arr1[0] = temp will never be executed inside your first loop).
If you want to avoid this behavior you should write your first for loop like this:
for (int i = 20; i >= 0; i--){...}.
The second for loop has some issues:
You are traversing the array backwards while you want to do the opposite.
The loop starts from an index out of bound (21).
The loop may print some undefined values (You should remember the index of the last added value).
I suggest you to use other data structures like a Stack but if you want to use an array you can edit your code as follows:
int i;
for (i = 20; i >= 0; i--){...}
for (i; i <= 20; ++i) { cout << arr1[i]; }
If you don't want to declare int i; outside of the loop you can do something like that:
int lastAdded;
for (int i = 20; i >= 0; i--){
...
lastAdded = i;
}
for (int i = lastAdded; i <= 20; i++) { cout << arr1[i]; }
Edit: Note that neither your code nor mine stops asking for a new value after the insertion of a -1.
If you want to achieve this behavior you should use a while loop instead of the first for loop and check for the exit condition.
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.
I'm using bubble sort to sort numbers in an array in order from lowest to highest. But there are some numbers which are the same, but I don't need them to be printed twice. So how do I check whether it was already printed and not to repeat the action?
The Bubble sort:
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(m[i]>m[j]){
temp=m[i];
m[i]=m[j];
m[j]=temp;
}
}
}
Since number are already sorted when you are printing it, you can store the last printed number and compare against this before printing.
Something like:
std::cout << m[0] << std::endl;
int last_print = m[0];
for(int i = 1; i < n; ++i)
{
if(m[i] != last_print)
{
std::cout << m[i] << std::endl;
last_print = m[i];
}
}
filter duplicate out when printing (assuming m being int[])
int last = 0;
for(int i=0;i<n;i++){
int num = m[i];
if (i == 0 || last != num) {
// print num;
}
last = num;
}
or this way if you don't like too much vars
for(int i=0;i<n;i++){
if (i == 0 || m[i - 1] != [i]) {
// print m[i];
}
}
Alternatively you could remove duplicates on sort
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;){
if (m[i]==m[j]) { // remove
m [j] = m [n - 1]; // replace with last
n --; // cut last
} else {
if(m[i]>m[j]){
temp=m[i];
m[i]=m[j];
m[j]=temp;
}
j ++;
}
}
}
You can add the number to a std::set as soon as you print it, and check all numbers if they are in the set before printing them.
EDIT: I missed the restriction that the numbers are sorted. In that case, a set is overkill and less efficient than just keeping track of the last number printed, and only printing numbers that are different from it afterwards.