I was wondering if anyone would be so kind as to look at this code I've written for practice. Besides a little php, c if my first language and I'm trying to teach myself. so pretty much, what am I doing wrong, where can I optimize, anything.
What this code does is (in terminal) draw a bunch of random 1's and 0's, but I added an effect kinda like a lattice. the bulk of this I got help on here.
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main (int argc, char *argv[]){ //check for whitch effect to print
switch(*argv[1]){
case '1': lattus();break;
case '2': normal();break;
default: printf("1 = lattus effect | 2 = static effect\n");break;
}
}
char *randstring (char *buffer, int length){ //genertate a random number
int i = length;
while(--i >= 0) {
buffer[i] = (rand() % 2) ? '1' : '0';
}
buffer[length] = 0;
return buffer;
}
int normal(){ // normal drawing of 1's and 0's
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int width = w.ws_col;
int height = w.ws_row; //get terminal width and height
char buffer[width*height + 1]; //create a buffer big enough to hold one draw to the screen
int i = 25;
while(i-- >= 0) {
printf("%s\n", randstring(buffer, width*height)); //draw to screen
usleep(90000);
}
system("clear"); //clear screen
}
int lattus (void){
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int width = w.ws_col; //get the terminal width
char buffer1[width + 1]; //create 3 buffers for each segment
char buffer2[width + 1]; //each big enough to hold the width of the terminal
char buffer3[width + 1];
int first = 1; //how many before the space
int second = width - 8; //how many in the middle of the space
int third = 1; //how many at the end of the space
int i = 1000; //draw 1000 lines
int on = 0; //switch for growing and shrinking
while(i-- >= 0){
usleep(9000);
if(first == 1 && third == 1 && second == width - 8 | second == width - 9){ //is it at min?
if(second % 2 == 0){ //is it an even number (had problems with buffer if it was odd)
second = second - 2;
}else{
second = second - 3;
}
first ++;
third ++;
on = 0; //keep growing
}else if(first == (width - 8) / 2 && third == (width - 8) / 2 && second == 2){ //untill it gets to max
if(second % 2 == 0){
second = second + 2;
}else{
second = second + 1;
}
third --;
first --;
on = 1; //start shrinking
}else if(on == 0){ //else if suppost to grow, grow
second = second - 2;
third ++;
first ++;
}else if(on == 1){ //else if suppost to shrink shrink
second = second + 2;
third --;
first --;
}else{
break;
}
printf("%s %s %s\n", randstring(buffer1, first), randstring(buffer2, second), randstring(buffer3, third)); //print it out
}
system("clear"); //clear screen
}