Everything Basics of C Flashcards

(86 cards)

1
Q

If you don’t want others (or yourself) to change existing variable values, you can use the keyword.

This will declare the variable as “constant”, which means unchangeable and read-only

A

const

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When you declare a constant variable, it must be assigned with a value

A

const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable ‘myNum’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

In C, the bool type is not a built-in data type, like int or char.

It was introduced in C99, and you must import the following header file to use it:

A

include <stdbool.h></stdbool.h>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Use the if statement to specify a block of code to be executed if a condition is true

A

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Short hand if else

A

variable = (condition) ? expressionTrue : expressionFalse
int time = 20;
(time < 18) ? printf(“Good day.”) : printf(“Good evening.”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Instead of writing many if..else statements, you can use the .

The switch statement selects one of many code blocks to be executed

A

Switch Statements
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The … statement breaks out of the switch block and stops the execution
The … statement is optional, and specifies some code to run if there is no case match

A

Break
default

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

The … loop loops through a block of code as long as a specified condition is true

A

while
while (condition) {
// code block to be executed
}
int i = 0;

while (i < 5) {
printf(“%d\n”, i);
i++;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

The … loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true

A

do/while
do {
// code block to be executed
}
while (condition);
int i = 0;

do {
printf(“%d\n”, i);
i++;
}
while (i < 5);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

for (expression 1; expression 2; expression 3) {
// code block to be executed
}

A

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

It is also possible to place a loop inside another loop. This is called a nested loop.

The “inner loop” will be executed one time for each iteration of the “outer loop”

A

int i, j;

// Outer loop
for (i = 1; i <= 2; ++i) {
printf(“Outer: %d\n”, i); // Executes 2 times

// Inner loop
for (j = 1; j <= 3; ++j) {
printf(“ Inner: %d\n”, j); // Executes 6 times (2 * 3)
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop

A

int i;

for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf(“%d\n”, i);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

You can also use break and continue in while loops

A

int i = 0;

while (i < 10) {
if (i == 4) {
break;
}
printf(“%d\n”, i);
i++;
}
Continue Example
int i = 0;

while (i < 10) {
if (i == 4) {
i++;
continue;
}
printf(“%d\n”, i);
i++;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array, define the data type (like int) and specify the name of the array followed by square brackets []

A

Arrays

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf(“%d”, myNumbers[0]);

A

Change an array element

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {
printf(“%d\n”, myNumbers[i]);
}

A

You can loop through the array elements with the for loop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

int myNumbers[] = {10, 25, 50, 75, 100};
printf(“%lu”, sizeof(myNumbers)); // Prints 20

A

Get Array Size or Length

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

It is because the sizeof operator returns the size of a type in bytes

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

A 2D array is also known as a … (a table of rows and columns)

A

matrix

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

A

A 2D array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf(“%d”, matrix[0][2]); // Outputs 2

A

Access the Elements of a 2D Array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf(“%d\n”, matrix[i][j]);
}
}

A

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf(“%d\n”, matrix[i][j]);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf(“%d”, matrix[0][0]);

A

Change Elements in a 2D Array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

char greetings[] = “Hello World

A

Strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
char greetings[] = "Hello World!"; printf("%c", greetings[0])
Access Strings Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets []
24
char greetings[] = "Hello World!"; greetings[0] = 'J'; printf("%s", greetings);
Modify Strings
25
char carName[] = "Volvo"; int i; for (i = 0; i < 5; ++i) { printf("%c\n", carName[i]); }
Loop Through a String
26
char carName[] = "Volvo"; int length = sizeof(carName) / sizeof(carName[0]); int i; for (i = 0; i < length; ++i) { printf("%c\n", carName[i]); }
Loop Through a String
27
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'}; char greetings2[] = "Hello World!"; printf("%lu\n", sizeof(greetings)); // Outputs 13 printf("%lu\n", sizeof(greetings2));
28
Escape character Result Description \' ' Single quote \" " Double quote \\ \ Backslash
29
The sequence ... inserts a single quote in a string
\' char txt[] = "It\'s alright."
30
The sequence ... inserts a single backslash in a string
\\ char txt[] = "The character \\ is called backslash.";
31
Escape Character Result \n New Line \t Tab \0 Null
32
C also has many useful string functions, which can be used to perform certain operations on strings. To use them, you must include the ... header file in your program:
33
For example, to get the length of a string, you can use the ... function
strlen() char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; printf("%d", strlen(alphabet));
34
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; printf("%d", strlen(alphabet)); // 26 printf("%d", sizeof(alphabet)); // 27
In the Strings chapter, we used sizeof to get the size of a string/array. Note that sizeof and strlen behaves differently, as sizeof also includes the \0 character when counting:
35
It is also important that you know that sizeof will always return the ... , and not the actual string length
memory size (in bytes)
36
char str1[20] = "Hello "; char str2[] = "World!"; // Concatenate str2 to str1 (result is stored in str1) strcat(str1, str2); // Print str1 printf("%s", str1);
Concatenate Strings
37
To concatenate (combine) two strings, you can use the ... function
strcat()
38
To copy the value of one string to another, you can use the .. function
strcpy()
39
char str1[20] = "Hello World!"; char str2[20]; // Copy str1 to str2 strcpy(str2, str1); // Print str2 printf("%s", str2);
o copy the value of one string to another, you can use the strcpy() function
40
To compare two strings, you can use the function. It returns 0 if the two strings are equal, otherwise a value that is not 0
strcmp()
41
char str1[] = "Hello"; char str2[] = "Hello"; char str3[] = "Hi"; // Compare str1 and str2, and print the result printf("%d\n", strcmp(str1, str2)); // Returns 0 (the strings are equal) // Compare str1 and str3, and print the result printf("%d\n", strcmp(str1, str3)); // Returns -4 (the strings are not equal)
Compare Strings
42
When a variable is created in C, a ... is assigned to the variable. The ... is the location of where the variable is stored on the computer. When we assign a value to the variable, it is stored in this .... . To access it, use the reference operator (&), and the result represents where the variable is stored
memory address
43
... are important in C, because they allow us to manipulate the data in the computer's memory
Pointers
44
that we can get the memory address of a variable with the reference operator
&
45
int myAge = 43; // an int variable printf("%d", myAge); printf("%p", &myAge);
Creating Pointers
46
A ... is a variable that stores the memory address of another variable as its value. A ... variable points to a data type (like int) of the same type, and is created with the * operator
pointer
47
int myAge = 43; int* ptr = &myAge; address of myAge printf("%d\n", myAge); printf("%p\n", &myAge); printf("%p\n", ptr);
pointer
48
we use the pointer variable to get the memory address of a variable (used together with the & reference operator). You can also get the value of the variable the pointer points to, by using the * operator ....
(the dereference operator)
49
When used in declaration (int* ptr), it creates a pointer variable. When not used in declaration, it act as a dereference operator.
50
int myNumbers[4] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { printf("%d\n", myNumbers[i]); }
Result: 25 50 75 100
51
int myNumbers[4] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { printf("%p\n", &myNumbers[i]); }
Result: 0x7ffe70f9d8f0 0x7ffe70f9d8f4 0x7ffe70f9d8f8 0x7ffe70f9d8fc the last number of each of the elements' memory address is different, with an addition of 4. It is because the size of an int type is typically 4 bytes
52
void myFunction(char name[]) { printf("Hello %s\n", name); } int main() { myFunction("Liam"); myFunction("Jenny"); myFunction("Anja"); return 0; }
// Hello Liam // Hello Jenny // Hello Anja
53
void myFunction(char name[], int age) { printf("Hello %s. You are %d years old.\n", name, age); } int main() { myFunction("Liam", 3); myFunction("Jenny", 14); myFunction("Anja", 30); return 0; }
// Hello Liam. You are 3 years old. // Hello Jenny. You are 14 years old. // Hello Anja. Yo
54
void calculateSum(int x, int y) { int sum = x + y; printf("The sum of %d + %d is: %d\n", x, y, sum); } int main() { calculateSum(5, 3); calculateSum(8, 2); calculateSum(15, 15); return 0; }
55
void myFunction(int myNumbers[5]) { for (int i = 0; i < 5; i++) { printf("%d\n", myNumbers[i]); } } int main() { int myNumbers[5] = {10, 20, 30, 40, 50}; myFunction(myNumbers); return 0; }
56
Return Values The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int or float, etc.) instead of void, and use the return keyword inside the function: Example int myFunction(int x) { return 5 + x; } int main() { printf("Result is: %d", myFunction(3)); return 0; }
Outputs 8 (5 + 3)
57
int myFunction(int x, int y) { return x + y; } int main() { printf("Result is: %d", myFunction(5, 3)); return 0; }
Outputs 8 (5 + 3)
58
int calculateSum(int x, int y) { return x + y; } int main() { int result1 = calculateSum(5, 3); int result2 = calculateSum(8, 2); int result3 = calculateSum(15, 15); printf("Result1 is: %d\n", result1); printf("Result2 is: %d\n", result2); printf("Result3 is: %d\n", result3); return 0;
If we consider the "Calculate the Sum of Numbers" example one more time, we can use return instead and store the results in different variables. This will make the program even more flexible and easier to control:
59
int calculateSum(int x, int y) { return x + y; } int main() { // Create an array int resultArr[6]; // Call the function with different arguments and store the results in the array resultArr[0] = calculateSum(5, 3); resultArr[1] = calculateSum(8, 2); resultArr[2] = calculateSum(15, 15); resultArr[3] = calculateSum(9, 1); resultArr[4] = calculateSum(7, 7); resultArr[5] = calculateSum(1, 1); for (int i = 0; i < 6; i++) { printf("Result%d is = %d\n", i + 1, resultArr[i]); } return 0; }
60
// Function to convert Fahrenheit to Celsius float toCelsius(float fahrenheit) { return (5.0 / 9.0) * (fahrenheit - 32.0); } int main() { // Set a fahrenheit value float f_value = 98.8; // Call the function with the fahrenheit value float result = toCelsius(f_value); // Print the fahrenheit value printf("Fahrenheit: %.2f\n", f_value); // Print the result printf("Convert Fahrenheit to Celsius: %.2f\n", result); return 0; }
61
// Global variable int x = 5; void myFunction() { printf("%d\n", ++x); // Increment the value of x by 1 and print it } int main() { myFunction(); printf("%d\n", x); // Print the global variable x return 0; }
The value of x is now 6 (no longer 5)
62
// Function declaration int myFunction(int x, int y); // The main method int main() { int result = myFunction(5, 3); // call the function printf("Result is = %d", result); return 0; } // Function definition int myFunction(int x, int y) { return x + y; }
63
nt sum(int k); int main() { int result = sum(10); printf("%d", result); return 0; } int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } }
Recursion
64
There is also a list of math functions available, that allows you to perform mathematical tasks on numbers. To use them, you must include the math.h header file in your program
#include
65
To find the square root of a number, use the sqrt() function
printf("%f", sqrt(16));
66
printf("%f", ceil(1.4)); printf("%f", floor(1.4));
Round a Number The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds a number downwards to its nearest integer
67
printf("%f", pow(4, 3));
Power The pow() function returns the value of x to the power of y (xy)
68
FILE *fptr; fptr = fopen(filename, mode);
In C, you can create, open, read, and write to files by declaring a pointer of type FILE, and use the fopen() function:
69
FILE *fptr; // Open a file in writing mode fptr = fopen("filename.txt", "w"); // Write some text to the file fprintf(fptr, "Some text"); // Close the file fclose(fptr);
Write To a File
70
In order to read the content of filename.txt, we can use the ... function
fgets()
71
fgets(myString, 100, fptr);
72
FILE *fptr; // Open a file in read mode fptr = fopen("filename.txt", "r"); // Store the content of the file char myString[100]; // Read the content and store it inside myString fgets(myString, 100, fptr); // Print the file content printf("%s", myString); // Close the file fclose(fptr);
73
FILE *fptr; // Open a file in read mode fptr = fopen("filename.txt", "r"); // Store the content of the file char myString[100]; // Read the content and print it while(fgets(myString, 100, fptr)) { printf("%s", myString); } // Close the file fclose(fptr);
The fgets function only reads the first line of the file. If you remember, there were two lines of text in filename.txt
74
struct Car { char brand[50]; char model[50]; int year; }; int main() { struct Car car1 = {"BMW", "X5", 1999}; struct Car car2 = {"Ford", "Mustang", 1969}; struct Car car3 = {"Toyota", "Corolla", 2011}; printf("%s %s %d\n", car1.brand, car1.model, car1.year); printf("%s %s %d\n", car2.brand, car2.model, car2.year); printf("%s %s %d\n", car3.brand, car3.model, car3.year); return 0; }
Structures Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.)
75
Access Structure Members To access members of a structure, use the ... syntax
dot
76
An ... is a special type that represents a group of constants (unchangeable values)
enum
77
enum Level { LOW, MEDIUM, HIGH };
C Enums
78
The process of reserving memory is called
allocation
79
C has two types of memory:
Static memory and dynamic memory
80
... is memory that is reserved for variables before the program runs. Allocation of static memory is also known as compile time memory allocation.
Static memory
81
int students[20]; printf("%lu", sizeof(students)); // 80 bytes
Static memory
82
... is memory that is allocated after the program starts running. Allocation of dynamic memory can also be referred to as runtime memory allocation. Unlike with static memory, you have full control over how much memory is being used at any time. You can write code to determine how much memory you need and allocate it. ... does not belong to a variable, it can only be accessed with pointers. To allocate ... , you can use the malloc() or calloc() functions. It is necessary to include the header to use them. The malloc() and calloc() functions allocate some memory and return a pointer to its address.
Dynamic memory
83
int *ptr1 = malloc(size); int *ptr2 = calloc(amount, size);
Dynamic memory
84