C basics Flashcards
Variables
int myNum = 15;
int myNum2; // do not assign, then assign
myNum2 = 15;
int myNum3 = 15; // myNum3 is 15
myNum3 = 10; // myNum3 is now 10
float myFloat = 5.99; // floating point number
char myLetter = ‘D’; // character
int x = 5;
int y = 6;
int sum = x + y; // add variables to sum
// declare multiple variables
int x = 5, y = 6, z = 50;
constants
const int minutesPerHour = 60;
const float PI = 3.14;
access string
char greetings[] = “Hello World!”;
printf(“%c”, greetings[0]);
modify string
char greetings[] = “Hello World!”;
greetings[0] = ‘J’;
printf(“%s”, greetings);
// prints “Jello World!”
Another way to create a string
char greetings[] = {‘H’,’e’,’l’,’l’,’\0’};
printf(“%s”, greetings);
// print “Hell!”
Creating String using character pointer (String Literals)
char *greetings = “Hello”;
printf(“%s”, greetings);
// print “Hello!”
condition
int time = 20;
if (time < 18) {
printf(“Goodbye!”);
} else {
printf(“Good evening!”);
}
// Output -> “Good evening!”
int time = 22;
if (time < 10) {
printf(“Good morning!”);
} else if (time < 20) {
printf(“Goodbye!”);
} else {
printf(“Good evening!”);
}
// Output -> “Good evening!”
Ternary operator
int age = 20;
(age > 19) ? printf(“Adult”) : printf(“Teenager”);
Switch
int day = 4;
switch (day) {
case 3: printf(“Wednesday”); break;
case 4: printf(“Thursday”); break;
default:
printf(“Weekend!”);
}
// output -> “Thursday” (day 4)
While Loop
int i = 0;
while (i < 5) {
printf(“%d\n”, i);
i++;
}
Do/While Loop
int i = 0;
do {
printf(“%d\n”, i);
i++;
} while (i < 5);
For Loop
for (int i = 0; i < 5; i++) {
printf(“%d\n”, i);
}
Break out of the loop Break/Continue
break out of the loop when i is equal to 4 for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf(“%d\n”, i);
}
Example to skip the value of 4
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf(“%d\n”, i);
}
While Break
int i = 0;
while (i < 10) {
if (i == 4) {
break;
}
printf(“%d\n”, i);
i++;
}
While continue
int i = 0;
while (i < 10) {
i++;
if (i == 4) {
continue;
}
printf(“%d\n”, i);
}