Array Indexing Error

My this piece of code is giving error while compilation..
 
  int Array[4]={2,1,4,3,7};

why is this so ?
if Array elements Indexes from 0, then according to my knowledge it should be correct
like this;

1
2
3
4
5
Array[0]=2;
Array[1]=1;
Array[2]=4;
Array[3]=3;
Array[4]=7;
Last edited on
Thats not exactly how it works buddy.

int Array[4]={2,1,4,3,7} That cant be done. [4] Means you have 4 elements inside your array, not 5.

If you want to reach those 4 elements, they are between 0-3.

1
2
3
4
Array[0]=2;
Array[1]=1;
Array[2]=4;
Array[3]=3;


https://www.youtube.com/playlist?list=PLkyoHqr6pb7v8sehaCL5W23VIi93fBIWc

Bucky has lots of great tutorials on the basics. Look up the one on array its very helpful :)
Last edited on
Thanks @TarikNeaj mate :)
After fighting for 2 hours with my program..
Sorting error just nearly injured my brain
I'm still unable to find logical error.. this program runs fine but does not outputs in incorrect sorted order
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <Windows.h>
#include <time.h>
using namespace std;
int main ()
{
	int Array[60];

	time_t t; time (&t);
	
	srand((unsigned int) t);	// seed srand() function with system time
	
	cout<<"Array elements in original generated order: "<<endl<<endl;
	for (int k=0; k<60; k++)
	{
		Array[k]=rand()%100;
		cout<<Array[k]<<" ";
	}


	int temp;	// temporary variable to hold Array element while sorting

	for (int k=0; k<59; k++)
	{
		if (Array[k]>Array[k+1])
		{
			temp=Array[k+1];
			Array[k+1]=Array[k];
			Array[k]=temp;
		}
	}

	cout<<"\n\nArray elements in ascending order: "<<endl<<endl;
	for (int k=0; k<60; k++)
	{
		cout<<Array[k]<<" ";
	}

	cin.get();

	return 0;
}
Thats because you're not sorting things quite the right way. It looks like you're trying to use the Bubble sort. This is how you should do it -

1
2
3
4
5
6
7
8
9
10
11
12
13
for (int i = 0; i < 60; i++)
	{
		for (int k = 0; k <60 - 1; k++)
		{
			if (Array[k]>Array[k + 1])
			{
				temp = Array[k];
				Array[k] = Array[k+1];
				Array[k+1] = temp;
			}
		}

	}


If you want to learn how it works in detail, watch this video - https://www.youtube.com/watch?v=TVL5_1NWviA&ab_channel=CodingMadeEasy

Goodluck :)
Thanks you TarikNeaj..

Stay Blessed Dear
Topic archived. No new replies allowed.