This commit is contained in:
Miloslav Ciz 2024-08-31 14:44:45 +02:00
parent 124b9d1e7c
commit 3f374a4713
85 changed files with 2281 additions and 2272 deletions

View file

@ -70,7 +70,7 @@ Open your text editor and paste this code:
int main(void)
{
puts("It works.");
return 0;
}
```
@ -115,7 +115,7 @@ To sum up let's see a general structure of a typical C program. You can just cop
int main(void)
{
// write commands here
return 0; // always the last command
}
```
@ -138,13 +138,13 @@ Let's see an example.
int main(void)
{
int myVariable;
myVariable = 5;
printf("%d\n",myVariable);
myVariable = 8;
printf("%d\n",myVariable);
}
```
@ -247,7 +247,7 @@ The **while** loop is used when we want to repeat something without knowing in a
```
while (x > y) // as long as x is greater than y
{
printf("%d %d\n",x,y); // prints x and y
printf("%d %d\n",x,y); // prints x and y
x = x - 1; // decrease x by 1
y = y * 2; // double y
@ -296,10 +296,10 @@ Any loop can be exited at any time with a special command called `break`. This i
while (1) // infinite loop
{
x = x - 1;
if (x == 0)
break; // this exits the loop!
y = y / x;
}
```
@ -320,36 +320,36 @@ With what we've learned so far we can already make a simple [game](game.md): gue
int main(void)
{
srand(clock()); // random seed
while (1) // infinite loop
{
int randomNumber = rand() % 10;
puts("I think a number. What is it?");
int guess;
scanf("%d",&guess); // read the guess
getchar();
if (guess == randomNumber)
puts("You guessed it!");
else
printf("Wrong. The number was %d.\n",randomNumber);
puts("Play on? [y/n]");
char answer;
scanf("%c",&answer); // read the answer
if (answer == 'n')
break;
}
puts("Bye.");
return 0; // return success, always here
}
```
@ -431,10 +431,10 @@ Let's see another function:
int power(int x, int n)
{
int result = 1;
for (int i = 0; i < n; ++i) // repeat n times
result = result * x;
return result;
}
@ -479,7 +479,7 @@ These is the most basic knowledge to have about C functions. Let's see one more
void writeFactors(int x) // writes divisors of x
{
printf("factors of %d:\n",x);
while (x > 1) // keep dividing x by its factors
{
for (int i = 2; i <= x; ++i) // search for a factor
@ -495,10 +495,10 @@ void writeFactors(int x) // writes divisors of x
int readNumber(void)
{
int number;
puts("Please enter a number to factor (0 to quit).");
scanf("%d",&number);
return number;
}
@ -510,10 +510,10 @@ int main(void)
if (number == 0) // 0 means quit
break;
writeFactors(number); // <- function call
}
return 0;
}
```
@ -588,9 +588,9 @@ void printMoney(void)
void playLottery(void)
{
puts("I'm playing lottery.");
money -= 10; // price of lottery ticket
if (rand() % 5) // 1 in 5 chance
{
money += 100;
@ -605,7 +605,7 @@ void playLottery(void)
void work(void)
{
puts("I'm going to work :(");
money += 200; // salary
printMoney();
@ -617,7 +617,7 @@ int main()
playLottery();
work();
playLottery();
return 0;
}
```
@ -652,22 +652,22 @@ int main(void)
{
char c;
float f;
puts("Enter character.");
c = getchar(); // read character
puts("Enter float.");
scanf("%f",&f);
printf("Your character is :%c.\n",c);
printf("Your float is %lf\n",f);
float fSquared = f * f;
int wholePart = f; // this can be done
printf("It's square is %lf.\n",fSquared);
printf("It's whole part is %d.\n",wholePart);
return 0;
}
```
@ -684,24 +684,24 @@ void printDecorated2(int x, int fancy); // forward declaration
void printDecorated1(int x, int fancy)
{
putchar('~');
if (fancy)
printDecorated2(x,0); // would be error without f. decl.
else
printf("%d",x);
putchar('~');
}
void printDecorated2(int x, int fancy)
{
putchar('>');
if (fancy)
printDecorated1(x,0);
else
printf("%d",x);
putchar('<');
}
@ -879,14 +879,14 @@ int bmi(Human human)
int main(void)
{
Human carl;
carl.initial = 'C';
carl.weightKg = 100;
carl.heightCm = 180;
if (bmi(carl) > 25)
puts("Carl is fat.");
return 0;
}
```
@ -906,30 +906,30 @@ Another extremely important compound type is **[array](array.md)** -- a sequence
int main(void)
{
float vector[5];
vector[0] = 1;
vector[1] = 2.5;
vector[2] = 0;
vector[3] = 1.1;
vector[4] = -405.054;
puts("The vector is:");
for (int i = 0; i < 5; ++i)
printf("%lf ",vector[i]);
putchar('\n'); // newline
/* compute vector length with
pythagoren theorem: */
float sum = 0;
for (int i = 0; i < 5; ++i)
sum += vector[i] * vector[i];
printf("Vector length is: %lf\n",sqrt(sum));
return 0;
}
```
@ -976,14 +976,14 @@ int main(void)
{
int array10[10];
int array20[20];
fillArrayN(array10,10);
fillArrayN(array20,20);
printArray10(array10);
putchar('\n');
printArrayN(array20,20);
return 0;
}
```
@ -1004,14 +1004,14 @@ The [syntax](syntax.md) that allows us to create strings with double quotes (`"`
int main(void)
{
char alphabet[27]; // 26 places for letters + 1 for temrinating 0
for (int i = 0; i < 26; ++i)
alphabet[i] = 'A' + i;
alphabet[26] = 0; // terminate the string
puts(alphabet);
return 0;
}
```
@ -1049,11 +1049,11 @@ void printCreature(Creature c)
int main(void)
{
// generate random creatures:
for (int i = 0; i < 100; ++i)
{
Creature c;
c.name[0] = 'A' + (rand() % 26);
c.name[1] = 'a' + (rand() % 26);
c.name[2] = 'a' + (rand() % 26);
@ -1064,12 +1064,12 @@ int main(void)
creatures[i] = c;
}
// print the creatures:
for (int i = 0; i < 100; ++i)
printCreature(creatures[i]);
return 0;
}
```
@ -1140,9 +1140,9 @@ Macros can optionally take parameters similarly to functions. There are no data
int main()
{
int n = MEAN3(10,20,25);
printf("%d\n",n);
return 0;
}
```
@ -1167,7 +1167,7 @@ void printNumber(int x)
"The number is:"
#endif
);
printf("%d\n",x);
}
@ -1175,11 +1175,11 @@ int main()
{
printNumber(3);
printNumber(100);
#if RUDE
puts("Bye bitch.");
#endif
return 0;
}
```
@ -1251,16 +1251,16 @@ int main(void)
{
int normalVariable = 10;
int *pointer;
pointer = &normalVariable;
printf("address in pointer: %p\n",pointer);
printf("value at this address: %d\n",*pointer);
*pointer = *pointer + 10;
printf("normalVariable: %d\n",normalVariable);
return 0;
}
```
@ -1308,13 +1308,13 @@ void buyGas(void)
int main(void)
{
// let Jose pay first
payingAccount = &bankAccountJose;
payBills();
buyFood();
buyGas();
// that's enough, now let Monica pay
payingAccount = &bankAccountMonica;
@ -1323,20 +1323,20 @@ int main(void)
buyGas();
buyFood();
buyFood();
// now it's Bob's turn
payingAccount = &bankAccountBob;
payBills();
buyFood();
buyFood();
buyGas();
printf("Monika has $%d left.\n",bankAccountMonica);
printf("Jose has $%d left.\n",bankAccountJose);
printf("Bob has $%d left.\n",bankAccountBob);
return 0;
}
```
@ -1361,12 +1361,12 @@ int main(void)
for (int i = 0; i < 8; ++i)
{
float pointX, pointY;
getUnitCirclePoint(i * 0.125 * 2 * PI,&pointX,&pointY);
printf("%lf %lf\n",pointX,pointY);
}
return 0;
}
```
@ -1390,13 +1390,13 @@ SomeStruct *sPointer;
int main(void)
{
sPointer = &s;
(*sPointer).a = 10; // without arrow
sPointer->b = 20; // same as (*sPointer).b = 20
printf("%d\n",s.a);
printf("%d\n",s.b);
return 0;
}
```
@ -1418,7 +1418,7 @@ This may be a lot information to digest. Let's provide an example to show all th
void printString(char *s)
{
int position = 0;
while (s[position] != 0)
{
putchar(s[position]);
@ -1430,26 +1430,26 @@ void printString(char *s)
int stringLength(char *s)
{
int length = 0;
while (*s != 0) // count until terminating 0
{
length += 1;
s += 1; // shift the pointer one character to right
}
return length;
}
int main(void)
{
char testString[] = "catdog";
printString("The string '");
printString(testString);
printString("' has length ");
int l = stringLength(testString);
printf("%d.",l);
return 0;
@ -1471,6 +1471,8 @@ Now that know about pointers, we can finally completely explain the functions fr
- `int getchar(void)`: Reads a single text character from the input and returns it. Why does the function return `int` and not `char`? Because the function can return additional special values such as `EOF` (end of file) which couldn't be stored in plain `char`.
- `int scanf(char *format, ...)`: Function for reading various data types from the input. Like `printf` it takes a variable number of parameters. The first one is a string that specifies which data type(s) to read -- this is a bit complicated but "%d" reads an `int`, "%f" `float`, "%c" `char` and "%s" string. The following arguments are **pointers** to expected data types, so e.g. if we've provided the format string "%d", a pointer to `int` has to follow. Through this parameter the value that's been read will be returned (in the same way we've seen in one example above).
[Nigger](nigger.md).
## Files
Now we'll take a look at how we can read and write from/to files on the computer disk which enables us to store information permanently or potentially process data such as images or audio. Files aren't so difficult.
@ -1547,7 +1549,7 @@ int main(void)
255,255,255, 0, 0, 0, 255,255,255, 0, 0, 0, 255,255,255,
255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255,
0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 0, 0, 0,
255,255,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,255,255
255,255,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,255,255
};
FILE *binFile = fopen("image.ppm","wb");
@ -1620,13 +1622,13 @@ unsigned int factorialRecursive(unsigned int x)
unsigned int factorialIterative(unsigned int x)
{
unsigned int result = 1;
while (x > 1)
{
result *= x;
x--;
x--;
}
return result;
}
@ -1675,21 +1677,21 @@ int main(void)
{
inputChars = // we need more space, resize the array
realloc(inputChars,(charsRead / ALLOCATION_CHUNK + 1) * ALLOCATION_CHUNK * sizeof(char));
resized++;
}
inputChars[charsRead - 1] = c;
if (c == '\n')
{
charsRead--; // don't count the last newline character
break;
}
}
puts("The string you entered backwards:");
while (charsRead > 0)
{
putchar(inputChars[charsRead - 1]);
@ -1697,10 +1699,10 @@ int main(void)
}
free(inputChars); // important!
putchar('\n');
printf("I had to resize the input buffer %d times.",resized);
return 0;
}
```
@ -1855,7 +1857,7 @@ int main(int argc, char **argv)
case 'w':
if (fileOffset >= COLS)
fileOffset -= COLS;
break;
case 'a':