Jump to content

Any good advice on arrays/or webpages

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
19 replies to this topic

#1
Sparty2009

Sparty2009

    Newbie

  • Members
  • PipPip
  • 13 posts
I am trying to write a program for my freshman level computer science class, I am not asking for anyone to write it so please dont take it that way. Are there any good webpages related to arrays? My book, I dont think is very good. I need additional help.

If anyone wants to look at my code so far and give me any pointers, that would be awesome!

Here is what I have to do:

Write a program that does the following:
1. The program will create an array of 100 integers.
2. It will initialize the elements at index 0 and 1 to 0, and all other elements to 1.
3. The program will print the index of every element of the array that has the value 1.
4. Write a function initialize_array that accepts two arguments, an array of integers and an
integer that is the size of the array. This function will be called from main to assign values to
the array.
5. Write a function print_array that accepts two arguments, an array of integers and an integer
that is the size of the array. This function will be called from main to print the index of all
elements that do not have the value 0.

This is how I started, I am trying to look at examples in the book and see if I can figure it out that way.


#include <stdio.h>

#include "csc1325.h"

#define SIZE 100




int initialize_array(int a[], int size);


int print_array(int b[], int size);



int main (int argc, char * argv[]) {

   int c[SIZE] =

      { 0,0,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1,

        1,1,1,1,1,1,1,1,1,1, };

   return 0;

}


#2
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
This is much shorter and easier to read.

int c[SIZE];

c[0] = 0;
c[1] = 0;
for(int i = 2; i < SIZE; ++i)
    c[i] = 1;

sudo rm -rf /

#3
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
I must admit I'm slightly confused - what part of this exactly are you having trouble understanding? I can write an example that meets all of those conditions if you'd like.

#4
Sparty2009

Sparty2009

    Newbie

  • Members
  • PipPip
  • 13 posts
I get what arrays are, at least what the are. Calling them and using their data is confusing me

I found a tutorial on arrays in C and C++ hoping I can find a small example.

I am a mechanical engineer major and need this intro to programming, but it is kicking my butt.

Could you do a small example? That would be awesome, if you didnt mind.

#5
Master Jake

Master Jake

    Newbie

  • Members
  • Pip
  • 6 posts

Sparty2009 said:

I get what arrays are, at least what the are. Calling them and using their data is confusing me

I found a tutorial on arrays in C and C++ hoping I can find a small example.

I am a mechanical engineer major and need this intro to programming, but it is kicking my butt.

Could you do a small example? That would be awesome, if you didnt mind.

To initialize an array, you create a variable as normal (with a datatype and name). The only thing you change is add square brackets with a number in them. That number is how many elements the array will contain.

For example:

datatype name[elements] = value;


You don't have to assign a value to the variable in the declaration if you do not wish. If you do wish to, you need to put the values in curly brackets { } and separate each value by commas. So, if we use 5 for the number of elements, we need to declare 5 values in the curly brackets.

Example:

int myVar[5] = {20, 3, 19, 8, 4};


Notice 5 integers separated by commas. You can create arrays from any datatype. Here's an array of characters.


char myChars[5] = {'H', 'e', 'l', 'l', 'o'};


Notice the chars have single quotes around them. String literals would have double quotes around them.

Example:

char *myStrings[5] = {"These", "are", "my", "awesome", "strings!"};


Arrays are accessed by the name of the array followed by the unique index number of the element you wish to access in brackets. Arrays start at 0, however, so keep that in mind.

Example:

int myVar[5] = {20, 3, 19, 8, 4};

printf("%d", myVar[0]);


The above code prints the value at index 0 of the array myVar to the screen. Index 0 happens to represent the first element in the array which we can see is "20." To access the last element we would use myVar[4].

You can also assign and overwrite values at a specific index in the array.

Example:

int myVar[2];

myVar[0] = 5;

myVar[1] = 8;


You can see, you assign values to arrays the same way you do any other variable. The only difference is the index number in the brackets.

A nifty thing about the index of arrays is that they can be taken advantage of very easily through the use of loops (specifically the for loop which is most commonly used in this situation).

Let's create an array of 100 integers. We won't assign any values to them so all 100 integers will be set to 0 by default. Next, we will use a for loop to increment through each element and assign it to it's respective value:


int myVar[100];

int x;

for (x = 0; x < 100; x++)

{

     myVar[x] = (x + 1);

}


The above code will set every element in the array equal to its own index number plus one. That means, myVar[0] will be equal to 1, myVar[1] will equal to 2, etc.

In a bit more advanced topic, arrays are really just pointers and can be accessed in different ways. I won't get into that, however, unless you specifically ask me to go into detail.

I hope this little rundown was helpful.

#6
Sparty2009

Sparty2009

    Newbie

  • Members
  • PipPip
  • 13 posts
Been hammering away at it, this is what I have thus far



#include <stdio.h>

#include "csc1325.h"

#define SIZE 100



int initialize_array(int a[], int size)  {

   int i=0;

   a[0] = 0;

   a[1] = 0;

   for(int i = 2; i < SIZE; ++i)

      a[i] = 1;

   return 0;

}


int print_array(int a[], int size)  {

   int i=0;

    for(i = 0; i < SIZE; ++i)

      if (a[i] == 1)

       printf("%d",i);

   return 0;

}


int main(int argc, char * argv[])  {

   int c[SIZE];

   int a=0, b=0;

   a=initialize_array(c,SIZE);

   b=print_array(c,SIZE);

   return 0;

}


#7
Master Jake

Master Jake

    Newbie

  • Members
  • Pip
  • 6 posts
Based on the assignment description you gave us, you are done and that program is successful so good job.

Just going to point some stuff out here:

a=initialize_array(c,SIZE);
b=print_array(c,SIZE);

I don't understand why you are assigning these 2 function's to variables. Both functions will always return 0 so the variables will never change. What exactly would be the point? :)

Here's my version of it. I did things just slightly different. I also used pointer math instead of array indexing since it is faster.

// Include libraries
#include <stdio.h>
#define ARRSIZE 100

// Function declaration prototypes
void initArray(int *alterArray, int arraySize);
void printIndex(int *alterArray, int arraySize);

int main()
{
	// Create a new array
	int mainArray[ARRSIZE];
	
	// Init its elements
	initArray(mainArray, ARRSIZE);
	
	// Print the indexes that are non-zero
	printIndex(mainArray, ARRSIZE);
	
	return 0;	
}

// Init array elements 0 and 1 to 0, all others to 1
void initArray(int *alterArray, int arraySize)
{
	int i;
	for (i = 0; i < arraySize; i++)
	{
		if (i < 2)
			*(alterArray + i) = 0;
		else
			*(alterArray + i) = 1;
	}	
}

// Print index of all elements that are non-zero
void printIndex(int *alterArray, int arraySize)
{
	int i;
	for (i = 0; i < arraySize; i++)
	{
		if (*(alterArray + i) != 0)
			printf("%d\n", i, *(alterArray + i));
	}
}


#8
Sparty2009

Sparty2009

    Newbie

  • Members
  • PipPip
  • 13 posts
Thanks Master Jake
Yeah yours is a lot shorter, but we havent really done anything with pointer math.

Thanks for looking it over, I really appreciate it.

#9
Master Jake

Master Jake

    Newbie

  • Members
  • Pip
  • 6 posts
No problem. You'll like pointer math because it's fast and powerful =)

#10
JCoder

JCoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 245 posts

Quote

You'll like pointer math because it's fast and powerful =)

Oh, really? Fast? Please give me at least one example showing that using pointer arithmetic yields better performance than accessing arrays the standard way with [].

Pointer arithmetic and pointer aliasing is what actually makes C and C++ programs SLOWER than needed.
It forces compilers to make additional memory stores which in many cases can be replaced by register allocation.
It also makes loop vectorization nearly impossible.

Example
for (int i = 0; i < SIZE; i++)
   array[i] = some_value;

is often much faster than:
for (int* a = array; a < array + SIZE;)
   *a++ = some_value;

Compile with SSE2 flags and see the results by yourself.
Avoid pointer arithmetic whenever you can.


BTW:
*(alterArray + i) = 1;

BAD STYLE. Should be:
alterArray[i] = 1;


#11
Master Jake

Master Jake

    Newbie

  • Members
  • Pip
  • 6 posts
Took this from another post:

Quote

The question is, what means a[i] actually in low level machine code? It means

1. Take the address of a in memory.

2. Add i times the size of a single item of a to that address (int usually is 4 byte).

3. Fetch the value from that address.

So each time you fetch a value from a, the base address of a is added to the result of the multiplication of i by 4. If you just dereference a pointer, step 1. and 2. don't need to be performed, only step 3.


#12
JCoder

JCoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 245 posts
Perfect example how today's PRACTICE does not match 20-years-ago THEORY. What you are writing was true about 20 years ago, when microprocessors didn't have parallel pipelines and vector units. Using xor to zero registers was perceived as a super clever hack then.

And now the analysis of the example with the index in the view of totay's theory and practice:
1. Any modern compiler will automatically change the multiplication of the index into simple one addition per loop. This is one of the basic optimizations, because "for (int i = 0; i < something; i++)" is a very often used idiom. Thus in the worst case both versions produce EXACTLY THE SAME MACHINE CODE.

2. Before performing 1, however, clever compilers will:
a) Unroll the loop.
b) Detect iterations are independent from each other.
c) Remove repeated increments from the inside of the loop with one larger increment, e.g. 4 ints in one loop.
d) Use offset addressing and SSE registers.
e) The processor will do the rest executing typically 2 or 4 dereferences in one CPU cycle.

Finally the loop will run about 2-4 time faster than your clever pointer arithmetic optimization, which block the whole prcess because iterations are not independent and it is much harder to guess, what the code is doing. Don't try to be more clever than the compiler if you really don't know what you are doing.

If you don't believe, try it. Either C++ version of my code compiled with SSE flags, or an equivalent Java version run 2-4 times faster than your code. At least on AMD Athlon in 32 bit mode.