Basic Array in C


#1

I’m doing a basic array because I am learning C, and I keep getting an error even though it seems everything is correct. Can someone help?


#2
#include <stdio.h>

#define MAX 10

int a;
int rand_seed=10;

int rand()
{
    rand_seed = rand_seed * 1103515245 +12345;
    return (unsigned int)(rand_seed / 65536) % 32768;
    
}
int main()
{
    int i,t,x,y;
    for (i=0; i < MAX; i++)
    {
        a=rand();
        printf("%d\n", a);
    }
   for (x=0; x < MAX-1; x++)
        for (y=0; y < MAX-x-1; y++)
            if (a > a[y+1])
            {
                t=a;
                a=a[a+1];
                a[a+1]=t;
            }
    printf("-----------------\n");
    for (i=0; i < MAX; i++)
    printf("%d\n", a);
    return 0;
}

#3

He meant

#include<stdlib>
#define MAX 10
int a;
int rand_seed=10;

int rand()
{
rand_seed = rand_seed * 1103515245 +12345;
return (unsigned int)(rand_seed / 65536) % 32768;

}
int main()
{
int i,t,x,y;
for (i=0; i < MAX; i++)
{
a=rand();
printf("%d\n", a);
}
for (x=0; x < MAX-1; x++)
for (y=0; y < MAX-x-1; y++)
if (a > a[y+1])
{
t=a;
a=a[a+1];
a[a+1]=t;
}
printf("-----------------\n");
for (i=0; i < MAX; i++)
printf("%d\n", a);
return 0;
}


Sorry i cant help you since i do C++… ima do C Later. But im preety sure(at least it is for C++), you cant access preceptor directives by normal… “functions”


#4

thanks for fixing that for me


#5

Idk if you saw but … in C++ Preproccecor Directives cant be accesed by normal functions… maybe thats how it goes in C Im not sure… for example:

#include<iostream>
#include<string>
#define MAX = 3;
using std::cout;
using std::endl;
using std::string;

int randomNumGen(){
 return rand()+MAX;//This will give you error... since its a preproccecor directive
}


#6

I see many issues in your code, I will try to point out what I noticed.

  1. To use printf you must #include <stdio.h>
  2. Your rand() function will return the same “random” number each run. I recommend using the standard random number generator. Read this if you like.
  3. Your second for loop needs to have {} because its body is more than one line long.
  4. You created a variable int a but using it as its an array. To declare an array you must use the following syntax: int array[MAX]; Quick C arrays tutorial.