Adak 419 Nearly a Posting Virtuoso

You don't seem to have the malloc or the passing array part of the logic, just right. Post enough of the code that we can get an example that is meaningful to correct for you.

Those errors have to be studied - post them up with your expanded example. Minimum to show is the array declaration, and the function call, and the function that is being called.

The above snippets aren't enough info (for me at least).

Adak 419 Nearly a Posting Virtuoso

Without seeing the code, it's hard to make decent suggestions on how to optimize it. Can you post it, and be more detailed about the +/- error that is acceptable?

I'm not clear about what has you stumped either, about creating a look up table. It's a 2D array (frequently). Your program can get precomputed/preloaded values by just referring to the right array element's value. Nothing esoteric, really.

Imagine for a moment that you are in a library. Everything you need for reference, is in the library. When you need a piece of info, you can go to the card catalog, and then to the right row of shelves, and eventually locate the book with the right info -- OR you could just look at a little pad next to you at the table, with the info you need. That's a look up table.

Adak 419 Nearly a Posting Virtuoso

The key is in the file names themselves: data-01.txt, data-02.txt... to data-20.txt.

Use a char array fname[MAX] to construct each of your filenames:

char fname[12] = {"data-"}; //leave for for the end of string char: '\0'
char num[3] = {"00";
char ext[5][".txt"};
int fnumber;

then use a for loop, and strcat() to add on the next number: 
for fnumber = 1 to 20
  num = itoa(fnumber);
  printf num
  if(num[0] == 0) {
    num[0] = num[1];
    num[1] = '\0'; //end of string char
  end if
  strcat num onto the end of fname
  strcat ext onto the end of fname
  print fname to check it's doing it right
  open the file and process as normal here
end for

This approach works, but the above may not be as polished as I'd like. Post back if that pseudo code doesn't spark any flashes of light for you.

Adak 419 Nearly a Posting Virtuoso

Yes, exactly,

however: ;)

It's a bit complicated, because in Linux/Unix/and all binary files, '\n' is the newline, and that's that - simple.

In text mode however, *sometimes* you'll see a newline as a TWO char combination: CR (carriage return), and LF (line feed). So if you see an obvious problem with '\n' somehow being ascii 10 followed next by ascii 13, then you'll know why that is, and can move to handle it.

That happens because text file handlers "expand" a newline, into CR/LF combo's, which usually your C program will handle as one char OK, but always -- well, no.

Always is such a long time, eh? ;)

Adak 419 Nearly a Posting Virtuoso

When you scanf() for a number, whitespace char's are passed over. That's one of the advantages of getting input as a stream of char's, btw.

What you can do is change your fscanf() from %d to %d%c, format. Assign a char to %c, like normal &ch.

Now %c will put all the spaces AND the newline (when it reaches the end of the row), into that ch variable, and you can test it, and use that, for your end of row test

Adak 419 Nearly a Posting Virtuoso

You can always change a while loop into a for loop, but you need to include the right check for a stop condition - which you don't show at all.

Adak 419 Nearly a Posting Virtuoso

If you had a discount array, where every day was represented by the number of the row, and every column represented the hour of the day:

Sunday (row 0): 0 (midnight) 1 (0100) 2 (0200) 3 (0300), etc.
Monday (row 1): 0            1        2        3

Then each element could hold the discount applicable to that day and time.

Sunday (row 0): 0 (midnight) 1 (0100) 2 (0200) 3 (0300), etc.
Monday (row 1): 0 0.10 (10%) 1  0.08  2  0.05  3 0.04  , etc.

The key is the tie between day of the week and the row number, and hour of the day (after midnight) and the column number.

And Welcome to the forum, Steve! ;)

Adak 419 Nearly a Posting Virtuoso

In pseudo code, for six numbers, this will do it. Change define C to whatever number of numbers per row you need.

include stdio.h

define R 2
define C 6

begin main() 
  declare:
  =========
  ints i,j, r,c, ok 
  char ch
  int a[R][C]  //R=Rows, C=Columns
  FILE * fp
  //end declarations
  //begin processing
  print("\n\n")
  fp = fopen("input.txt", "r")
  if(fp==NULL) 
    printf("\nError opening file\n")
    return 1
  end if

  set r and c to 0
  set ok to 1
  while((ok=fscanf(fp, "%d%*c", &a[r][c])) > 0) {
    if(ok less than 1)
      break
    print("%d ", a[r][c])
    ++c
    if(c equals C)
      set c to 0
      ++r
      putchar('\n')
    end if
  end while loop
  print("\n\n\n")
  fclose(fp)
  printf("\n\n\t\t\t     press enter when ready");

  (void) getchar() 
  return 0
end program

If input text has this input:
1 2 3 4 5 6
6 5 4 3 2 1

That is what the program prints up, and assigns to array a[r][c].

I left this in semi-pseudo code, because I see that you want to learn, and there's no better way to learn, imo, than taking pseudo code that works, and making it into a program.

Adak 419 Nearly a Posting Virtuoso

You have to declare your variables, before you can use them. Generally, it's best to declare them, right at the top of the function they are used in.

Adak 419 Nearly a Posting Virtuoso

Are there always 6 numbers in a line, or are there sometimes less or more than six numbers?

Adak 419 Nearly a Posting Virtuoso

So make it describe what it's doing, the way you want it. It's 4 a.m. here, and I wanted something more descriptive. ;)

Adak 419 Nearly a Posting Virtuoso

Getline is a function to make it a bit easier to get a line of text. In some languages, it's standard, but not in C. fgets() is not as simple as gets() (which is absolutely simple as pie), but gets() is NOT safe - all the hackers know how to use it's weakness to create havoc.

Like most things that you want to do, there's more than one way to do this. You want to use fscanf() for this?

Is the input.txt numbers, formatted like this?
1 2 3 4 5 6

(six numbers, each separated from the next by one space)

Adak 419 Nearly a Posting Virtuoso

* ALWAYS * use code tags on code forums. Forum software turns your code into html junk, otherwise - very hard to study.

#include<stdio.h>
int main (){
  int counter;
  int x;
  int product;

  counter=0;
  x=1;
  product=1;

  while (counter<5){
    counter++; //this is C!
    product*=x;
    printf("x:%d *= product is: %d\n",x, product);
    x+=2;

  }

  printf("Product>%d",product);
  (void) getchar();
  return 0;
}

See what that adds up to - I haven't run this.

Adak 419 Nearly a Posting Virtuoso

If I print out int's, then the file will have int's in it. When you print out strings of char's, then the file will have char's in it. EVEN if the char is a digit, it will still be a char digit, and not a true int.

The beauty of what the code I posted it, it doesn't matter whether the original data was a char string with digits, or real int's.

It takes them all in as char's, and THEN it transfers them into true int's.

Works either way. ;)

Adak 419 Nearly a Posting Virtuoso

The code you posted, is writing out strings of char's, not ints:

fprintf(ExistingFile, "1 0 0 1 1\n");

See those double quotation marks around your string of digits? That's a sure sign it's a string, in C.

Adak 419 Nearly a Posting Virtuoso

This is one way:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int i,j; 
  char a[]={"1 22 33 444 5555 5 4 3 2 1"};
  int n[10];
  
  for(i=0,j=0;i<10;i++) {
    n[i] = atoi(a+j);
    while(a[++j]!=' ');
    printf("\n %d: %d", i, n[i]);
  }
  printf("\n\n\t\t\t     press enter when ready");

  (void) getchar(); 
  return 0;
}

Don't expect a safety net with atoi(). You won't get anything except a 0 on error.

Check your compiler and see if it has the safer strtoi() (string to int).

I've had good weather and fair winds with atoi(), personally.

Adak 419 Nearly a Posting Virtuoso

You can do this with just one pair of nested loops, but I like using two to simplify it.

The first pair of nested loops fills the char array a[][] with the correct values. The second pair of nested loops, prints them out.


Clear out the array, to just spaces:

char a[R][C];

//zero it out:
for(r=0;r<R;r++) 
  for(c=0;c<C;c++)
    a[r][c] = ' ';  //a space

Now the real loops in pseudo code:

for each col 
  for each row  //like turning the array 90 degrees counter clockwise
    if row < value in your occurrences array for col's value
      a[row][col] = '|'
    else if row == value in your occurrences arrary
      a[row][col = '^'
  end of for each row
end of for each col     

Now you're ready to print, but it has to be from the top down, so it will display with the higher values being higher up on the screen.

for r=R; r> -1; r--
  for c=0; c < C;c++ //still going upward on c, so it reads left to right
    print a[r][c];
  end of for c=0...
  putchar('\n'); //end of a row
end of for r=R...

And there you go. Add your footer lines, and anything you need along the vertical on the far left or right hand side, for the scale.

;)

Adak 419 Nearly a Posting Virtuoso

For your sorting functions, look at Wikipedia and search for Sorting algorithms.

In general, if the function just goes through the data, one time, that would be your 0(n), complexity. Since obviously the complexity is directly a product of the number of items being handled, and nothing else.

If it uses nested two nested loops, you have something more - maybe up to (n*n).

If it's nutty like Bogo sort, then it's still worse, of course. ;)

The best general sorters like Quicksort, are n(log n), all others (like your selections sort), are worse, (have higher big O values).

While you're over at Wikipedia, give a read on Big O (oh, not zero), notation. Then try and figure out what's what in your assignment.

When you post code, put tags around it [/CODE ]. Just highlight your code, and click on the code tag icon in the editing window.[CODE ] tags around it [/CODE ]. Just highlight your code, and click on the code tag icon in the editing window.

Adak 419 Nearly a Posting Virtuoso

Add:

#include <limits.h>

Either use a

#define SIZE 12

macro, or get size this way:
size=sizeof(a)/sizeof(a[0];

You'll need that size of the array, I'll show you why.


This is NOT refined code - I believe this is best done recursively, but recursion
is hard to follow, without some experience with it.

for(i=0;i<size;i++) {
  //your main loop
  j=i+1;
  n=a[i];
  compress=0;
  while(a[j]==n && j<size) {
    compress++;
    a[j] = INT_MIN;
    ++j;
  }
  /*if you have a compression here
  increment i and set a[i] to compress+1
  and you need to shuffle the digits, down
  */
     //meet shuffle time ;)
    for(j=i+1;j<size;j++) {
      if(a[j] == INT_MIN) {  //found an element that needs to be overwritten 
        --size;              //reducing the effective size of the array by 1   
        for(k=j;k<size;k++) { //copying down the digits
          a[k] = a[k+1];
        }
        --j;                  //yup, tinkering
          
         //printf("\n Size = %d\n", size);
         //for(m=0;m<size;m++)
           //printf("a[%d]=%d ", m, a[m]);
      }
    }
  }//end if 

}//end for

Work with something along those lines, Joey.

Joey_Brown commented: gr8 guy !! +1
Adak 419 Nearly a Posting Virtuoso

Be definition, you don't need code to add zeroes to the array - you are compressing it, not adding to it's length.

Think along these lines:

for i=0, j=0; i< SIZE of array;
  assign a[j] to num1
  set compress = 0
  while j < SIZE
    if a[j] == num1
      ++compress
  if compress > 0
    a[i+1] = compress
   for(k=i to j)
    mark each array element with a unique value (not zero)  
   (maybe INT_MIN?)  
  j+= compress
end for loop

ais where the compressed digit indicator goes. a[j] is where the next digit to be looked at, is located.

Adak 419 Nearly a Posting Virtuoso
# include <stdio.h>

void show(int (*)[3],int,int);

int main()
{
  int a[3][3]={1,2,3,
	       4,5,6,
	       7,8,9};

/* I would prefer the explicit:
  int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
note the doubled braces
*/
                

  show(a,3,3);
  return(0);
}
void show(int (*p)[3],int row,int col)
/*I would use:
void show(int p[3][3]) 
using the call 
show(a);

Which emphasizes at a glance (to me anyway), that it's a true 2D array
that is being referred to, here.
*/

{
  int i,j;
  printf("\n\n\n");
  for(i=0;i<row;i++)
   {
     for(j=0;j<col;j++)
	printf("\t %d",p[i][j]);
     printf("\n");
   }
}

Is it right way??

Always test it with YOUR compiler and system. If it's always accurate - and you get no warnings (of note), or crashes, or errors in the output - then you can say "I didn't find any bugs, at all!" ;)

Because you can never prove that a program of any complexity, has no bugs. You can only prove that it had no bugs that were found, in your tests.

vinitmittal2008 commented: Detailed and Usefull Information +1
Adak 419 Nearly a Posting Virtuoso

Your code doesn't show any closure for the file you created. That can cause a problem.

Add:

fclose(ofp);

when your program is done writing data to the file. That will flush out any data that hasn't been written yet to the file, that is being held by a buffer.

My bet is that is your problem. Most hard drives are set up for buffered writing (for efficiency), and you haven't put much data into the file buffer, yet. Then you didn't close the file, so the data may not have been written out.

;)

Adak 419 Nearly a Posting Virtuoso

Well, two reasons:

1) he has an array, already, but no linked list. More efficient here, to just use what he has.


2) Does he know how to use a linked list? I don't know. My guess is no, he doesn't. If you don't know how to find the minimum value in an array, you probably don't know how to work with a linked list yet, either.

But it could be done with a linked list! ;)

Adak 419 Nearly a Posting Virtuoso

The alignment for all rows is perfect, on my screen.

What input for total days and first day are you seeing this problem with?

Adak 419 Nearly a Posting Virtuoso

Your code will stay formatted properly, only if you click on the [CODE ] icon in the editing window, and paste your code right between the code tags that the editor gives you:

[CODE ]
<YOUR CODE GOES HERE>
[/CODE ]

Take a look at this. I couldn't quite grasp the logic that was involved in your program.

#include<stdio.h>

#define p printf
#define s scanf

int main()
{
  int totalDays,day,i, j, r, c, firstDay;

  //clrscr();
  printf("\n\n\n");
  p("Input Number of days in a month:");
  s("%d",&totalDays);
  p("Input the first day of the month:");
  s("%d",&firstDay);

  p(" Sun  Mon  Tues  Wed  Thurs  Fri  Sat\n");

  for(r=0,day=0;r<5;r++)
  {
    if(r==0) {     //printing the first row only
      for(j=0;j<7;j++) {
        if(j==2 || j==4 || j==5) //handles days with 4 letters, etc.
          putchar(' ');          //I don't like using tabs
        if(j<firstDay) 
          printf("     ");      //as you can tell ;)
        else
          printf(" %2d  ", ++day);
      }
      putchar('\n');
    }
    for(c=0;c<7;c++) {    //prints all the other rows
      if(++day>totalDays)
        break;
      if(c==2||c==4 ||c==5)
        putchar(' ');     //about the same as the first row
      printf(" %2d  ", day); 
    }
    printf("\n");          
  } 
  getch();
  return 0;
} 
Adak 419 Nearly a Posting Virtuoso

This is the C forum. Do you believe that we don't deal with C problems? ;)

One look around the place should have enlightened you on that point. Post your code, and describe what the problem is - tell us what it is that has you stumped.

Adak 419 Nearly a Posting Virtuoso

It looks like you're doing this in the upper code:

j=((pow(rad,i))/q;

but doing this in the lower code:

j=(pow(rad,i)/q);

I'm not sure if they're equivalent, or not.

That was a common punishment for an architect's failure, in the Ancient world. Kept the guys on their toes. ;)

Adak 419 Nearly a Posting Virtuoso

How would YOU find the lowest price item?

Perhaps, in a loop, you'd compare each item, and if it was the lowest priced item so far, set that value to be the lowPrice varible's value?

Adak 419 Nearly a Posting Virtuoso

What is the range of shorts on your system? My old compiler has a SHRT_MAX in the header file <limits.h>, that won't go to 360.

If you make a habit of using the absolute minimal data type for your variables, you WILL get bitten by the "overflow" bug, a great deal. Engineers never build a structure to withstand a certain stress - it's always a certain stress PLUS a safety margin.

I think they started doing that about the time that architects/builders were killed if their buildings collapsed. ;)

Adak 419 Nearly a Posting Virtuoso

Yes, malloc() returns NULL if the allocation failed. Did you include stdlib.h? Your cast of the pointer from malloc, is unnecessary in C, and will prevent the compiler from issuing an error regarding this oversight with stdlib.h.

I don't believe 1000 char's is too much, but check the other variable values to ensure that the buffer is not being freed, etc.

You want to check the pointer address at 307, not at 306, in your debugger. It will still be NULL until AFTER malloc returns the proper address, at the end of line 306, not at the start.

Adak 419 Nearly a Posting Virtuoso

Strings in C are compared, using the include file string.h, and the strcmp() function. Here's how it works:

The value returned by strcmp() tells whether the strings are:

0: means they are equal
>0: means string1 is > than string2
<0: means string1 is < string2

int variable = strcmp(string1, string2);

or

if((strcmp(string1, string2)) > 0) {
   //string1 was > string2 (see how the >'s match up)
}

BTW, example 9 is going to be at the top of your list, if it's sorted in descending order.

Do you have some sorting code? If not, post up your code, and let's get you sorting. ;)

Adak 419 Nearly a Posting Virtuoso

Dude, you don't need to "open" argv - it's there, just waiting for you, courtesy of the C compiler.

C automatically opens stdin, stdout, stderr, and creates argc and argv, when your program starts. (May not be an exhaustive list)

Adak 419 Nearly a Posting Virtuoso

Strings are not compared with the == sign in C. Use strcmp(). When it returns 0, then the strings are equal.

Adak 419 Nearly a Posting Virtuoso

You've got a pointer to a pointer - and you've set aside no memory for it, at all.

The algorithm may be OK, but it's not one I'd recommend you use. Strive for clarity and simplicity in your code.

adding two matrices into a third matrix which is NOT a part of a struct, is very much the way I'd suggest.

Adak 419 Nearly a Posting Virtuoso

Edit:
=====
The first problem I found with your code was the assignment of low and high to a[0] and a[9]. Low and high, should be index numbers, not values. On your first call, since nothing has been partitioned yet, the low and high should be 0 and array size -1.

I changed a bunch of other variables, simply to save time.

#include<stdio.h>

//int low,high,mid; These should be local, not global variables

void partition(int a[],int low,int high);
void merge(int a[],int low,int high,int mid);

int main()
{
    int a[10];
    int count;
    for(count=0; count<10; count++)
    {
        printf("Enter element number %d\n",count+1);
        scanf("%d" , &a[count]);
    }
    partition(a,0,9);

    for(count=0; count<10; count++)
    {
        printf("%d\n" ,a[count]);
    }
    return 0;
}

/*high is array[SIZE]-1 */
void merge(int a[],int low,int mid,int high)
{
  int i,j,k,l,b[20];
  l=low;
  i=low;
  j=mid+1;
  while((l<=mid)&&(j<=high))
  {
    if(a[l]<=a[j])
    {
      b[i]=a[l];
      l++;
    }
    else
    {
      b[i]=a[j];
      j++;
    }
    i++;
  }
  if(l>mid)
  {
    for(k=j;k<=high;k++)
    {
      b[i]=a[k];
      i++;
    }
  }
  else
  {
    for(k=l;k<=mid;k++)
    {
      b[i]=a[k];
      i++;
    }
  }
  for(k=low;k<=high;k++)
  {
    a[k]=b[k];
  }
}

void partition(int a[],int low,int high)
{
  int mid;
  if(low<high)
  {
    mid=(low+high)/2;
    partition(a,low,mid);
    partition(a,mid+1,high);
    merge(a,low,mid,high);
  }
}
Adak 419 Nearly a Posting Virtuoso

First, Welcome to the Forum, Kanokan! ;)

Second - it's a real pain to study code that isn't looking like code, because you didn't surround it with code tags (the code icon in the editor window gives you what you need to put your code between).

Just because code will compile, doesn't mean it will run and not crash. Being able to compile the code, is just the start.

I'll look at your code -- back after awhile.

Adak 419 Nearly a Posting Virtuoso

There's no real wrong way to do it, if you get accurate results. The run-time is just not a big deal, and is irrelevant if the result isn't accurate.

It's a package deal on the design - absolutely. Shorts might be as small (in range), as a char, depending on your system. That may cause overflow, all depending on your algorithm.

Adak 419 Nearly a Posting Virtuoso

It's easier if you do your addition and subtraction on these long arrays, just as you were taught to do them, in school.

Some people like to flip the numbers around, but I like just using char's, and starting with the highest element and decrementing the loop counter, as I go.

The main thing is to keep it *simple*, so you always know exactly where your carry is, if you have a carry or not, etc. Simple is fast, (enough), and simple is bug free.

Adak 419 Nearly a Posting Virtuoso

This:

if (value=0)

should be:

if (value==0)

Adak 419 Nearly a Posting Virtuoso

When you don't accurately and unambiguously define the assignment, the answers you get back are not going to be all correct.

Congrats to Martin B. He was able to decipher and define the assignment, correctly.

Adak 419 Nearly a Posting Virtuoso

Array indeces in C begin with zero, not one.

If Brendon has any problems tweaking the program I posted, to affect that logic, he'll let me know.

Thanks for the explanation.

Adak 419 Nearly a Posting Virtuoso

This is my take on your program. It has some subtleties in it, that are hard to explain, in text. Especially, the part where numbers are moved over to the b[] array.

I put in notes for what I found wrong, as much as possible. Some things, I just had to change, rather than tweak.

/********************************************/
/* Programmer: Brendon O'Connell            */
/*                                          */
/* Program 61: Number Puzzle                */
/*                                          */
/* Approximate Completion Time: x minutes   */
/********************************************/

#include <stdio.h>
#include <stdlib.h>


void swap( int *b, int i, int j ) {
  int temp = b[i];
  b[i] = b[j];
  b[j] = temp ;
}

int main( int argc, char *argv[] ) {
  FILE* fin ;
  int i, j, k, N, temp ;
  int *a, *b ;

  strcpy(argv[1], "brendon.txt"); //change as needed. Done for my convenience
  fin = fopen( argv[1], "r" ) ;
  
  //don't ask the user to enter something, and then 
  //have that something, read from a file
  fscanf( fin, "%d" , &N ) ;

  /* calloc sets the array values to all 0's - malloc doesn't */
  a = calloc ( sizeof( int ) * N, 10 ) ;  //no cast is needed in C
  b = calloc ( sizeof( int ) * N, 10 ) ;

  printf( "\n\n\n\n Reading %d integers.", N ) ;
  for( i = 0 ; i < N ; i++ ) {     //<N, not <=N
    fscanf( fin, "%d", &a[i] ) ;  //not fin2
  }

  //check the input
  printf("\n\n Original input a[]: …
Adak 419 Nearly a Posting Virtuoso

Right off, <=N is a fault, overrunning the boundary of the array. Just < N.

fclose(fin) goes before the return 0 ;)

From your description in post #1, it seems your output should:

1 2 5 7 8 20 9

That brings all numbers less than == 7, into sorted order, and leaves the numbers greater than 7, in their original order.

Please clarify.

Adak 419 Nearly a Posting Virtuoso

No, they don't need to be all in one array to be printed correctly. This is your world (the data, the structures you choose, etc), and you can set it up as you wish.

Make it accurate, efficient and clear.

Adak 419 Nearly a Posting Virtuoso

I'll be the contrarian, and go with

read in pivot number

if(number <= pivot) {
  deal with it
}
else {
  deal with it
}

If you want to sort - then sort, but only sort the numbers that should be sorted - so having two arrays (one for not sorting, and one for sorting), is a good idea.

Adak 419 Nearly a Posting Virtuoso

http://en.wikipedia.org/wiki/Fast_Fourier_transform

Way too big a topic to be covered in a post. Enjoy! ;)

Adak 419 Nearly a Posting Virtuoso

It depends on the data. If there were a lot of values < say 1000, and lots of values > 1 Million, with nothing in between, then it might make sense to have two arrays for Counting sort to work through. One for low and one for higher values.

Another way to do it - very common, is to simply sort the values. Now all the duplicate values will be right next to each other, and easily removed.

There are a wide variety of tricks with other data structures that can do the same thing. I haven't used them, but hash tables are one such. If the number hashes out to the same value, it will get tested for equality.

The general purpose being to get rid of any duplicate values, as far "upstream" in your processing of the data, as possible.

I'm always reminded of an old R:Base Relational Database, that SO EASILY would duplicate every record in the table you were working in. That was one of the first BASIC programs I wrote for work - remove duplicate records from our table in R:Base. (quite an adventure on a 286 cpu) ;)

Adak 419 Nearly a Posting Virtuoso

That's C++, not C, so I can't help you. Obviously, you're not allocating the memory you need.

When you can put in ten int's or so before the program crashes - that's an allocation that never worked.

You should be able to test and see if the call to allocate the memory, succeeded or not.

Adak 419 Nearly a Posting Virtuoso

That's a great way to do it, (called "Counting Sort", sometimes), IF the range of the numbers, is not too large.

Run time is O(n), and you can't beat that, as long as the range is suitable.

Adak 419 Nearly a Posting Virtuoso

Trying to debug that program is not simple - he has set in his logic using very specific values including "magic" numbers. His book doesn't show a diagram of what the circle should look like? Weird!

When I ran it, I also got an ugly red square with barely rounded corners. I believe he was trying to print out several nearby pixels, after calculating for only one, but something went awry. ;)

What he wants to do is to set up something like this, but I'll use a simpler text console mode:

Remember your Pythagorean theorem: A² + B² = C². Where A = height length, B = base length, and C = hypotenuse of a right angle triangle.

The hypotenuse gives us the distance from the center of the circle, to the point on the screen (or element of the array), being considered at the moment.

#include <stdio.h>

int main(void) {
  int i, j;

  printf("\n\n");

  for(i=-10;i<11;i++) {
    for(j=-10;j<11;j++) {
      if((i*i)+(j*j) > 60) {
         putchar('$');
      }
      else
         putchar(' ');
    }
    putchar('\n');
  }
  printf("\n\n\t\t\t    press enter when ready");
  (void) getchar();
  return 0;
}

Which may well print up something that looks like a football oval (), instead of a circle. That depends on the relative height and width of your text window font. You can get a better circle, even concentric circles, but you have to use a more sophisticated program.


If you want to draw circles, and for some reason you don't …