Skip to content

Instantly share code, notes, and snippets.

@fernandozamoraj
Last active October 23, 2021 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandozamoraj/f157e1a3e5763d88b01ef71fdcb5b1e8 to your computer and use it in GitHub Desktop.
Save fernandozamoraj/f157e1a3e5763d88b01ef71fdcb5b1e8 to your computer and use it in GitHub Desktop.
C Programming Language Cheat Sheet - Everything a C Beginner Needs
//First comment
//#include<...> to include libraries
//#include "myfile.c" to include your own headers
#include <stdio.h> //for printf and such
#include <stdlib.h> //for many definitions TODO more examples
#include <string.h> //for copying strings
#include <ctype.h> //for toupper
//preprocesor directives
//contitional define by using #ifndef and ending with #endif
//may also us #elif
//#define appear like constants but they are not... instead they are replacements for code
//wherever they appear
#ifndef MAXVALUE
#define MAXVALUE 100
#endif
//function defintion
float convertMetersToFeet(float meters){
float result = meters * 3.2808;
return result; //return type of function is float so it must return a value
}
//function that does not return value
//first void indicates there is no return value
//second void indicates there are no parameters
//optionally it can be written as: void printHello();
//the second void is optional
//the first void is required
void printHello(void){
printf("Hi there!");
}
//forward declarations of functions
//sometimes calle the function prototype
//or function signatures
//the functions must be defined somewhere in this c file
float convertFeetToMeters(float feet); //formula feet * 0.3048
//These appear the same but are a bit different
void printHelloConsCharP(const char *name);
void printHelloCharP(char *name);
void printHelloCharArray(char name[]);
typedef struct SStudent{
char firstName[MAXVALUE];
char lastName[MAXVALUE];
int id;
} Student;
void fillStudent(Student *student);
void writeAndThenReadFile();
void doArrays();
void doStrings();
void doMathOperations();
void printHeader(const char *header){
printf("\n\n******* %s ********\n", header);
}
/*
Description: main is the main entry point into all C programs
return: returns int to indicate return value of program
negative value indicates error
0 returns normal exit
for beginners return 0 is common unless doing systems programming
param argc: indicates number of parameters
is always at leas equal to 1 but may be more (e.g. myprogram.exe --b myfile.txt has a value of 3)
in the example above myprogram.exe is argv[0]
--b is argv[1]
myfile.txt is argv[2]
optionally main is valid as
int main(){
return 0;
}
the example above does nothing
*/
int main(int argc, char *argv[]){
//many different data types
//all single lines of code end with semicolor (;)
int age = 2; //integer number... for whole numbers
float average = 3.03; //for floating point numbers
int counter = 0; //int counter
char *name = "Joe";
//printf
printHeader("Welcome to my first cheat sheet program"); //parameterless printf ... also notice \n for new line character
//print to the console using print format with arguments
printf("\n%s you are %d years old and you're average is %2.2f", name, age, average);
if(age == 2){
printf("\nplease enter your real age: ");
//read input from console...
//notice the & character which means passing by reference
// &age instead of age
scanf("%d", &age);
}
//for loop
//for loop can also be written empty as: for(;;)
// int i=0 create new variable i
// i < 5 if i < 5 execute the body of the loop
// i++ increment i by 1 after execution of the body
// this loops executes from 0 to 4
// 5 is not less than 5 therefore 5 exits the loop
printHeader("Basic for loop for(int i=0; i < 5; i++){");
for(int i=0; i < 5; i++){
printf("\n i = %d", i);
}
//using modulus operator %
printHeader("print odd and even numbers");
for(int i=1; i <= 10; i++){
if( i % 2 == 0){ //if number divide by 2 has remainder of 0 -- which means it is even number
printf("\n%d is even", i); //prints number
}
else{
printf("\n%d is odd", i);
}
}
//notice that we can execute statements in the loop condition and
//then check the value against 5
printHeader("While loop");
while((counter = counter + 1) < 5){
printf(" %d", counter);
}
counter = -1;
printHeader("Do while loop prints multiples of 20");
while(counter < 1000){
counter++;
//just to demonstrate AND && condition
if(counter % 3 == 0 && counter % 5 ==0)
{
printf("\n%d FizzBuzz", counter);
}
else if(counter % 3 == 0){
printf("\n%d Fizz", counter);
}
else if(counter % 5 == 0){
printf("\n%d Buzz", counter);
}
else{
printf("\n%d Not fizzin nor buzzin!", counter);
}
//just to demonstrate OR || condition
if(counter % 11 == 0 || counter % 7 == 0){
printf("\n %d is multiple of 7 or 11", counter);
}
//go to end of loop and do not execute any more numbers
//if counter is equal to 101
//break works on any loop tipe(e.g. for, while, do while)
if(counter == 101)
break;
//if number is not divisible by 20 skip the rest of the body and go to while condition
//continue works on any loop type
if(counter % 20 != 0)
continue;
printf(" %d", counter);
}
do{
counter++;
}while(counter < 5);
//prints 1 -5
printHeader("Print 1- 5... ");
printHeader("the following two four loops appear the same but provide different output. Why is that?");
for(int i=0;i<5;){
printf("%d ", ++i); //prints i and then increments i
}
//prints 0 - 4
printHeader("Print 0 - 4... ");
for(int i=0;i<5;){
printf("%d ", i++); //increments i and then prints i
}
printHeader("meters to feet and feet to meters");
float feet = convertMetersToFeet(5);
float meters = convertFeetToMeters(feet);
printf("\n5.0 meters converted to feet is %2.2f feet", feet);
printf("\n%2.2f feet converted to meters is %2.2f", feet, meters);
printHeader("4 different ways to define a function that accepts c strings");
printHello();
printHelloCharArray(name);
printHelloConsCharP("Fred"); //this only works with this version of hello
printHelloConsCharP((const char*)name);
printHelloCharP(name);
Student student1;
fillStudent(&student1); //pass student by reference
printf("\nName: %s %s", student1.firstName, student1.lastName);
printf("\nId: %5d\n", student1.id);
//select case is like a chained if else condition... sort of
//it jumps directly to the case in the collection of cases
//it will continue executing the next case and the next until
//it runs into a break statement
printHeader("switch or SELECT statement");
int day = 12;
switch(day){
case 12:
printf("\nOn the twelveth day of christmas...");
//no break which means if day is 12 it will also execute elevent and then break out
case 11: printf("\nOn the 11th daty of Chritmas ....");
break;
//will only get to case 10 if day equals 10
case 10: printf("\nOn the tenth day of Christmas..");
break;
default:
printf("no other cases selected");
}
printf("\n");
writeAndThenReadFile();
doArrays();
doStrings();
doMathOperations();
printHeader("~THE END~");
printf("\n");
return 0;
}
void doMathOperations(){
printHeader("Math operations");
printf("\n20 / 4 equals %d", 20/4);
printf("\n20 + 4 equals %d", 20+4);
printf("\n20 / 3.0 equals %f", 20/3.0);
printf("\n20 / 3 equals %d", 20/3);
printf("\n20 - 3 equals %d", 20 - 3);
printf("\n20 * 3 equals %d", 20 * 3);
}
/*
strings in c are just arrays of char values
a string is terminated with the character '\0'
the actual string array may be longer than the string value in it
but not the other way around
many string functions exist in the string.h library
these are only a few of them.
Strings are case sensitive so for example "Aa" does not equal "aa"
Sometimes you will want to ignore case sensitivity and for that you will have to
rely on what is available in the string library or use the ctype.h library to help you
*/
void doStrings(){
printHeader("doStrings()");
char buffer[MAXVALUE] = {0};
char name[MAXVALUE] = "Joe Smith";
char cat[] = "cat";
char *dog = "dog";
char *id = "123";
char *avg = "4.5";
char *password = "asfsdfAB3434aa2s3w26l45**";
int realId = atoi(id); //converts string numbers to an actual integer type
float realAvg = atof(avg); //convrst string avg to an actual floating type value
//copy name into buffer
strcpy(buffer, name);
//if buffer and name are equal
if(strcmp(buffer, name) == 0){
printf("\n%s and %s are equal", buffer, name);
}
//lexographically speaking
if(strcmp(buffer, name) < 0){
printf("%s is less than %s", buffer, name);
}
//lexographically speaking
if(strcmp(buffer, name) > 0){
printf("\n%s is greater than %s", buffer, name);
}
//make the o in Joe upper case;
buffer[1] = toupper(buffer[1]);
if(strcmp(buffer, name) != 0){
printf("\n%s and %s are not equal", buffer, name);
}
if(strcmp(dog, cat) > 0){
printf("\ndog belongs after cat in the dictionary");
}
if(strcmp(cat, dog) < 0){
printf("\ncat belongs before dog in the dictionary");
}
int digitCount = 0;
int alphaCount = 0;
int upperCount = 0;
int lowerCount = 0;
int symbolCount = 0;
//stlen gets the length of the password string
//loop through all chars in password
//count the different character types
for(int i=0; i < strlen(password); i++){
if(isdigit(password[i]))
digitCount++;
if(isalpha(password[i]))
alphaCount++;
if(islower(password[i]))
lowerCount++;
if(isupper(password[i]))
upperCount++;
//is not digit and not alpha
if(isalnum(password[i]) == 0)
symbolCount++;
}
printf("\nPassword %s has %d upper %d lower %d numbers %d symbols",
password, upperCount, lowerCount, digitCount, symbolCount);
}
/*
arrays are collections of values of the same data type
the memory is contiguos and therefore can be access by an index
Arrays can be of any data type includding user defined data types like
the Student struct in this file for example
an array in C does not know it's length and therefore the length must be passed around
or another approach is to use a known flag to mark the end
c strings for example use the character '\0' to mark the end of the char array
so for example
char name[6] = {'J', 'o', 'e', '\0', 'y', 's']};
printf("%s", name);
name will only print "Joe" and the anything after the element with '\0' will be ignored
char name[3] = {'J', 'o', 'e'};
printf("%s", name);
this example might print garbage or result in an error because there is no null termintating character
*/
void doArrays(){
printHeader("Doing arrays");
//delcare an array of size 100
//and intialize it to 0
int numbers[100] = {0};
//assing values to each element in the array
//arrays start from 0 and go to size-1
for(int i=0; i < 100; i++){
numbers[i] = i*2;
}
//print all the elements in the array
printf("\n");
for(int i=0; i<100; i++){
printf(" %d,", numbers[i]);
}
printf("\n\n");
}
void fillStudent(Student *student){
printHeader("Fill Student");
printf("\n\n Getting student data....\n");
//propt for name and read it from console
printf("\nEnter first name: ");
scanf("%s", student->firstName);
//prompt for last name and read it from console
printf("\nEnter last name: ");
scanf("%s", student->lastName);
//prompt for id and read it from console
printf("\nEnter id: ");
scanf("%d", &(student->id));
}
float convertFeetToMeters(float feet) //formula feet * 0.3048
{
return feet * 0.3048;
}
//These appear the same but are a bit different
void printHelloConsCharP(const char *name){
printf("\nHello %s", name);
}
void printHelloCharP(char *name){
printf("\nHello %s", name);
}
void printHelloCharArray(char name[]){
printf("\nHello %s", name);
}
void writeAndThenReadFile(){
char ch;
printHeader("Doing file IO (Input Output)");
FILE *fileOut = fopen("outfile.txt", "w");
if(fileOut != NULL){
printf("\nWriting file outfile.txt...\n");
fprintf(fileOut, "\nThis is the first line");
fprintf(fileOut, "\nThis is the second line");
fclose(fileOut);
FILE *fileIn = fopen("outfile.txt", "r");
printf("\nReading file outfile.txt...");
while((ch = fgetc(fileIn)) != EOF){
printf("%c", ch);
}
}
}
/* SAMPLE OUTPUT from program
these first two lines are to compile and run the program
user@box1:~/Documents/dev/c_cheat_sheet$ gcc main.c -o a.out
user@box1:~/Documents/dev/c_cheat_sheet$ ./a.out
******* Welcome to my first cheat sheet program ********
Joe you are 2 years old and you're average is 3.03
please enter your real age: 34
******* Basic for loop for(int i=0; i < 5; i++){ ********
i = 0
i = 1
i = 2
i = 3
i = 4
******* print odd and even numbers ********
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
******* While loop ********
1 2 3 4
******* Do while loop prints multiples of 20 ********
0 FizzBuzz
0 is multiple of 7 or 11 0
1 Not fizzin nor buzzin!
2 Not fizzin nor buzzin!
3 Fizz
4 Not fizzin nor buzzin!
5 Buzz
6 Fizz
7 Not fizzin nor buzzin!
7 is multiple of 7 or 11
8 Not fizzin nor buzzin!
9 Fizz
10 Buzz
11 Not fizzin nor buzzin!
11 is multiple of 7 or 11
12 Fizz
13 Not fizzin nor buzzin!
14 Not fizzin nor buzzin!
14 is multiple of 7 or 11
15 FizzBuzz
16 Not fizzin nor buzzin!
17 Not fizzin nor buzzin!
18 Fizz
19 Not fizzin nor buzzin!
20 Buzz 20
21 Fizz
21 is multiple of 7 or 11
22 Not fizzin nor buzzin!
22 is multiple of 7 or 11
23 Not fizzin nor buzzin!
24 Fizz
25 Buzz
26 Not fizzin nor buzzin!
27 Fizz
28 Not fizzin nor buzzin!
28 is multiple of 7 or 11
29 Not fizzin nor buzzin!
30 FizzBuzz
31 Not fizzin nor buzzin!
32 Not fizzin nor buzzin!
33 Fizz
33 is multiple of 7 or 11
34 Not fizzin nor buzzin!
35 Buzz
35 is multiple of 7 or 11
36 Fizz
37 Not fizzin nor buzzin!
38 Not fizzin nor buzzin!
39 Fizz
40 Buzz 40
41 Not fizzin nor buzzin!
42 Fizz
42 is multiple of 7 or 11
43 Not fizzin nor buzzin!
44 Not fizzin nor buzzin!
44 is multiple of 7 or 11
45 FizzBuzz
46 Not fizzin nor buzzin!
47 Not fizzin nor buzzin!
48 Fizz
49 Not fizzin nor buzzin!
49 is multiple of 7 or 11
50 Buzz
51 Fizz
52 Not fizzin nor buzzin!
53 Not fizzin nor buzzin!
54 Fizz
55 Buzz
55 is multiple of 7 or 11
56 Not fizzin nor buzzin!
56 is multiple of 7 or 11
57 Fizz
58 Not fizzin nor buzzin!
59 Not fizzin nor buzzin!
60 FizzBuzz 60
61 Not fizzin nor buzzin!
62 Not fizzin nor buzzin!
63 Fizz
63 is multiple of 7 or 11
64 Not fizzin nor buzzin!
65 Buzz
66 Fizz
66 is multiple of 7 or 11
67 Not fizzin nor buzzin!
68 Not fizzin nor buzzin!
69 Fizz
70 Buzz
70 is multiple of 7 or 11
71 Not fizzin nor buzzin!
72 Fizz
73 Not fizzin nor buzzin!
74 Not fizzin nor buzzin!
75 FizzBuzz
76 Not fizzin nor buzzin!
77 Not fizzin nor buzzin!
77 is multiple of 7 or 11
78 Fizz
79 Not fizzin nor buzzin!
80 Buzz 80
81 Fizz
82 Not fizzin nor buzzin!
83 Not fizzin nor buzzin!
84 Fizz
84 is multiple of 7 or 11
85 Buzz
86 Not fizzin nor buzzin!
87 Fizz
88 Not fizzin nor buzzin!
88 is multiple of 7 or 11
89 Not fizzin nor buzzin!
90 FizzBuzz
91 Not fizzin nor buzzin!
91 is multiple of 7 or 11
92 Not fizzin nor buzzin!
93 Fizz
94 Not fizzin nor buzzin!
95 Buzz
96 Fizz
97 Not fizzin nor buzzin!
98 Not fizzin nor buzzin!
98 is multiple of 7 or 11
99 Fizz
99 is multiple of 7 or 11
100 Buzz 100
101 Not fizzin nor buzzin!
******* Print 1- 5... ********
******* the following two four loops appear the same but provide different output. Why is that? ********
1 2 3 4 5
******* Print 0 - 4... ********
0 1 2 3 4
******* meters to feet and feet to meters ********
5.0 meters converted to feet is 16.40 feet
16.40 feet converted to meters is 5.00
******* 4 different ways to define a function that accepts c strings ********
Hi there!
Hello Joe
Hello Fred
Hello Joe
Hello Joe
******* Fill Student ********
Getting student data....
Enter first name: joe
Enter last name: johnson
Enter id: 45
Name: joe johnson
Id: 45
******* switch or SELECT statement ********
On the twelveth day of christmas...
On the 11th daty of Chritmas ....
******* Doing file IO (Input Output) ********
Writing file outfile.txt...
Reading file outfile.txt...
This is the first line
This is the second line
******* Doing arrays ********
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198,
******* doStrings() ********
Joe Smith and Joe Smith are equal
JOe Smith and Joe Smith are not equal
dog belongs after cat in the dictionary
cat belongs before dog in the dictionary
Password asfsdfAB3434aa2s3w26l45** has 2 upper 11 lower 10 numbers 2 symbols
******* Math operations ********
20 / 4 equals 5
20 + 4 equals 24
20 / 3.0 equals 6.666667
20 / 3 equals 6
20 - 3 equals 17
20 * 3 equals 60
******* ~THE END~ ********
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment