Skip to main content

๐Ÿ”ฐ C Basics

This page provides an introduction to C basics.

Variablesโ€‹

int quantity = 0;
char item[50] = "";
float total = 0.0f;

Reading Inputโ€‹

#include <stdio.h>
#include <string.h>


// read int
scanf("%d", &quantity);

// read string
fgets(item, sizeof(item), stdin);
// this is to remove newline character from input buffer
item[strlen(item) - 1] = '\0';

// read float
scanf("%f", &total);

return 0;

Math Functionโ€‹

#include <math.h>

// sqrt
int x = 9;
printf("%d", sqrt(x));

// pow
x = 2;
printf("%d", pow(x, 2));

// round, ceil & floor
float y = 3.14;
printf("%d", round(y));
printf("%d", ceil(y));
printf("%d", floor(y));

If Elseโ€‹

int age = 21;
if(age >= 65) {
printf("You are a senior");
}
else if(age >= 18) {
printf("You are an adult");
}
else {
printf("You are a child");
}

Switchโ€‹

int dayOfWeek = 4;
switch(dayOfWeek) {
case 1: printf("It is Monday");
break;
case 2: printf("It is Tuesday");
break;
case 3: printf("It is Wednesday");
break;
case 4: printf("It is Thursday");
break;
case 5: printf("It is Friday");
break;
case 6: printf("It is Saturday");
break;
case 7: printf("It is Sunday");
break;
default: printf("Please only enter number 1-7");
}

While Loopโ€‹

int number = 0
while(number <= 10) {
printf("Number: %d\n", number);
number++;
}

Do While Loopโ€‹

int number = 0;
do {
printf("Enter a number greater than 0");
scanf("%d", &number);
} while(number <= 0);

For Loopโ€‹

for(int i = 0; i < 10; i++) {
printf("Number %d\n", i);
}

Random Numberโ€‹

#include<stdio.h>
#include<stdlib.h>
printf("%d", rand());
printf("%d", srand(time(NULL))); // this is seeding rand function
printf("%d", rand());

// random number from min and max
int min = 1;
int max = 6;
int randomNumber = (rand() % (max - min + 1)) + min;
printf("%d", randomNumber);

Arrayโ€‹


#include <stdio.h>

int number[] = {10, 20, 30, 40, 50};
char grade[] = {'A', 'B', 'C', 'D'};
char name[] = "Testing"

// size of an array
printf("%d", sizeof(number));
printf("%d", sizeof(number[0]));

// length of an array
int length = sizeof(number) / sizeof(number[0]);
prinf("%d", size);

// defining an array with all zeros
int scores[5] = {0};
for(int i = 0; i < 5; i++) {
prinf("%d", scores[i]);
}

2D Arraysโ€‹

int numbers[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int rows = sizeof(array) / sizeof(array[0]);
int cols = sizeof(array[0]) / sizeof(array[0][0]);
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("%d", numbers[i][j]);
}
printf("\n");
}

String Operationsโ€‹

include <ctype.h>

char sample[100] = "This is test";
char uppercaseSample[100] = toupper(sample);

printf("Original text is: %s \n", sample);
printf("Uppercase text is: %s \n", uppercaseSample);