You are on page 1of 25

In CodeBlocks, we need to invoke the compiler with the std=c99 option for a lot of

things like the for loop to work. To do this go to Settings Compiler Other
Options and type -std=c99 in the window.

Working with integers


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1 = 5;
int num2 = 7;
int num3 = num1/num2 ;
printf("%i \t", num3);
return 0;
}
Working with floating numbers
#include <stdio.h>

#include <stdlib.h>
float main()
{
float num1 = 5;
float num2 = 7;
float num3 = num1/num2 ;
printf("%.2f \t", num3);
return 0;
}
Working with characters
#include <stdio.h>
#include <stdlib.h>
char main()
{
char char1 = 'A';
printf("%c \t", char1);
return 0;
}
Getting input from the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1 = 0;
printf("Please enter a number:\t");
scanf("%i", &num1);
int num2 = 0;
printf("Please enter a second number:\t");
scanf("%i", &num2);
printf("%i", num1 + num2);
return 0;
}
If loops
#include <stdio.h>
#include <stdlib.h>
void
main()
{
printf("Please provide a character input:\t");
int char1;
scanf("%c", &char1);
if (char1 == 'a')

{
printf("Hello");
}
else if (char1 == 'b')
{
printf("Great");
}
else
{
printf("You have entered an invalid character.\n");
}
return 0;
}
Building a calculator with the if loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Please say what operation you want to
perform:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n");
int char1;
scanf("%c", &char1);
printf("Please enter the first number:\t");
float num1;
scanf("%f", &num1);
printf("Please enter the second number:\t");
float num2;
scanf("%f", &num2);
if (char1 == 'A' || char1 == 'a')
{
printf("The sum is:\t%f", num1+num2);
}
else
{
printf("You have entered an invalid character.\n");
}
return 0;
}
Switch cases
#include <stdio.h>
#include <stdlib.h>
void main()
{
printf("Please provide a character input:\t");

int char1;
scanf("%c", &char1);
switch (char1)
{
case 'A':
printf("Hello");
break;
case 'B':
printf("Happy Birthday");
break;
default:
printf("You entered an invalid char");
break;
}
return 0;
}
While loop
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 1;
while(i <= 100)
{
printf("%i\n", i);
i++;
}
return 0;
}
This will print out the numbers 1 to 100.
Adding user provided numbers
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 0;
int sum = 0;
while(i != -1)
{
sum += i;
printf("Please provide a number that is not -1 \n");
scanf("%i", &i);
}

printf("Sum is %i", sum);


return 0;
}
Do While Loop
Printing all the even numbers between 2 and 50
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 2;
do
{
printf("%i\n", i);
i += 2;
}
while ( i <= 50);
return 0;
}
For loop
#include <stdio.h>
#include <stdlib.h>
void main()
{
for (int i = 1;i < 50;i += 2)
{
printf("All odd numbers between 1 and 50: \n%i\n", i);
}
return 0;
}
Fibonacci sequence generator
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n1 = 1;
int n2 = 1;
printf("%i\n%i\n", n1, n2);
for (int i = 0; i < 18; i++)
{
int temp = n2;
n2 += n1;

n1 = temp;
printf("%i\n", n2);
}
return 0;
}
Arrays
Defining and printing an array
#include <stdio.h>
#include <stdlib.h>
void main()
{
int num[] = { 4, 6, 7, 2, 3 };
printf("%i", num[2]);
return 0;
}
Asking user for floats to store in the array
#include <stdio.h>
#include <stdlib.h>
void main()
{
float num[5];
for (int i = 0; i < 5; i++)
{
printf("Please enter a number\n");
scanf("%f", &num[i]);
}
for (int j = 0; j < 5; j++)
printf("%f\n", num[j]);
return 0;
}
Printing out character from an array
#include <stdio.h>
#include <stdlib.h>
void main()
{
char name[] = "Ratnadeep";
printf("%c\n", name[0]);
return 0;
}
Printing out the whole string
#include <stdio.h>
#include <stdlib.h>

void main()
{
char name[] = "Hello World, how is it going?";
printf("%s\n", name);
return 0;
}
Reversing an array
#include <stdio.h>
#include <stdlib.h>
void main()
{
int nums[] = { 1, 2, 3, 4, 5 };
int reversed[5];
for (int i = 0; i < 5; i++)
{
reversed[4 - i] = nums[i];
}
for (int i = 0; i < 5; i++)
printf("%i", reversed[i]);
return 0;
}
Functions
#include <stdio.h>
#include <stdlib.h>
void printError()
{
printf("Error!\n");
}
void main()
{
printError();
return 0;
}
Passing error to the callee by the caller
#include <stdio.h>
#include <stdlib.h>
void printError(char message[])
{
printf("Error: %s!\n", message);
}
void main()

{
printError("Some Error Message");
return 0;
}
A little more detailed explanation
#include <stdio.h>
#include <stdlib.h>
float sum(float a, float b); #Prototyping the function.
void main()
{
float a, b;
printf("Please provide a number:\n");
scanf("%f", &a);
printf("Please provide a number:\n");
scanf("%f", &b);
printf("The sum is: %f", sum(a,b));
return 0;
}
float sum(float a, float b) #Defining the function.
{
return a + b;
}
Structures
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int numerator;
int denomenator;
}fraction;
void main()
{
fraction f;
f.numerator = 1;
f.denomenator = 3;
printf("%i/%i\n", f.numerator, f.denomenator);
return 0;
}
Arrays of type struct can also be created.
Pointers

#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 4;
int *p = &i;
printf("%u\n%u", p, &i);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
void main()
{
float f = 5.67;
float *pf = &f;
printf("%u\n", pf);
printf("%f", *pf);
return 0;
}
The name of an array is just a pointer to its first element:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int nums[] = {1,2,3,4,5};
int *n = &nums[0];
printf("%u\n%u", n, nums);
return 0;
}
Since array names are the same thing as pointers, the following can be
done:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char *name;
char *email;
int age;
} client;
void main()
{

client c1;
c1.name = "John";
c1.email = "jdoe@email.com";
c1.age = 31;
printf("%c\n", c1.name[0]);
printf("%s\n", c1.email);
return 0;
}
Changing value of variable in another function:
Method 1 does not work:
#include <stdio.h>
#include <stdlib.h>
void func(int i);
void main()
{
int myInt = 5;
func(myInt);
printf("%i\n", myInt);
}
void func(int i)
{
i = 0;
}
This does:
#include <stdio.h>
#include <stdlib.h>
void func(int *i);
void main()
{
int myInt = 5;
func(&myInt);
printf("%i\n", myInt);
}
void func(int *i)
{
*i = 0;
}
Double pointers
#include <stdio.h>

#include <stdlib.h>
void main()
{
int i = 5;
int *p = &i;
int **pp = &p;
printf("%i\n", **pp);
return 0;
}
Pointer calculation
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 5;
int *p = &i;
int **pp = &p;
printf("%i\n%i\n", pp, pp+1); Here pp+1 actually moves by 4 bytes because
the pointer data type is 4 bytes long.
return 0;
}
Report card program: (This is a solid exercise in working with structures
and pointers).
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char *name; /*store the student's name as a character array.*/
int sc, math, his, eng;
} reportcard;
void printreport (reportcard *rc); /*The whole struct is passed to the function as a
pointer instead of passing the members individually*/
void main()
{
reportcard r;
printf("Please provide the student's name:\n");
char str[20];
scanf("%s", str);/*Since str defines an array it is a pointer and the & is not
required.*/
r.name = str; /*r.name is just a pointer and thus str is temporarily required*/
printf("Please provide sc:\n");

scanf("%i", &r.sc);
printf("Please provide math:\n");
scanf("%i", &r.math);
printf("Please provide his:\n");
scanf("%i", &r.his);
printf("Please provide eng:\n");
scanf("%i", &r.eng);
printreport(&r);
return 0;
}
void printreport(reportcard *rc)
{
int avg = rc->sc + rc->his + rc->math + rc->eng;
printf("The student: %s has an avg of %i: ", rc->name, avg/4);
}
Character variables in depth
#include <stdio.h>
#include <stdlib.h>
void main()
{
char c = 'c';
printf("%i\n", c);/*Everything is C is represented as a number. This is 99 in this
case.*/
int i = 99;
printf("%c\n", i);/*This prints out c*/
printf("%c\n", c+1); /*This prints out d*/
return 0;
}
Integral data types
A character and an integer are integral data types since they only store integers.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char c = 127; //1 byte in memory
int i = 2147000000; //4 bytes in memory
short s = 32000; // 2 bytes memory. The same as 'short int s'
long l = 2147000000; //4 bytes in memory. The same as 'long int l'.
long long ll = 34354546576004; //8 bytes in memory. The same as 'long long ll'
printf("%i\n", sizeof(long));//Outputs 4
printf("%li\n", l); //If long and int have same size then %i also works. Otherwise it
does not.

printf("%lli\n", ll);
return 0;
}
Binary number system
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 0b101; //0b means that the following number is binary.
printf("%i\n",i);
return 0;
}
Octal number system
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 0637; //0 means that the following number is octal.
printf("%i\n",i); //prints the decimal version of i
printf("%o\n",i); //prints the octal number
int j = 415;
printf("%o\n",i);//prints the octal version of the decimal number
return 0;
}
Hexadecimal number system
The hexadecimal system is very useful in computer science. A 2-digit hexadecimal
number takes 1 byte in computer memory. So an unsigned int, which is 4 bytes, has
a largest value of FFFF. Similarly, a signed int has the largest value of 7FFF. Here 7 is
roughly the half of F.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i = 0x7FEA; //Hexadecimal number is recognised by the system with the 0x
printf("%i\n",i);//This prints the decimal version
printf("%x\n",i);//This prints the hex version.
return 0;
}
Floating point data types

#include <stdio.h>
#include <stdlib.h>
void main()
{
float f = 3.5; //4 bytes. Can only store 6 digits.
double d = 5.678;//8 bytes. Can store 15 digits.
long double ld = 6.78;//12 bytes. Can store 18 digits. Most precise.
double w = 0.0000000453; //Will look very unprofessional if printed out like this.
printf("%f\n", f);
printf("%f\n",d);
printf("%llf\n",ld);//Prints the long double.
printf("%.3e\n", w);//Print out too small or too long numbers in scientific notation
return 0;
}
Union
#include <stdio.h>
#include <stdlib.h>
typedef union
{
char *firstName;
char *lastName;
}myUnion;
void main()
{
myUnion mu;
mu.firstName = "Adam";
mu.lastName = "Smith";
printf("%s\n",mu.firstName);//This will print Smith
return 0;
}
The reason is that a Union has a memory size that is as large as the largest variable
defined in it. The difference between a union and a structure is that at any
one point in time, a structure can store values for all the variables defined
in it but a union can store only one of the variables defined in it.
Writing code in separate files
The first thing to do is create a header file.
Go to File New File C/C++ Header

Name the file and save it in the project folder.

#ifndef MYFILE_H_INCLUDED
#define MYFILE_H_INCLUDED /*These two lines just say that if MYFILE_H_INCLUDED
is not defined then define it and include the following
code. However if the file is included then do not include the following code again. So
this ensures that the code will be included
in the project only once.*/
void printInt (int i); //This declares a function prototype
#endif // MYFILE_H_INCLUDED
Once the header file is created and the prototypes are defined, the code file needs
to be created:
Go to File New File
void printInt (int i)
{
printf("%i\n", i);
}

Then to include the printInt (int i) function in the main program add this line to the
main file:
#include "myFile.h"
Include and Define preprocessor directives
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
/*The quotes mean that the preprocessor will search for the file in the directory
where main.c is. If the file is not found then it will look in the directory where
standard libraries are located. The angle brackets mean that the preprocessor will
directly look into the standard library folder.*/
#define MY_NAME "Deep" //Every appearance of MY_NAME is going to be replaced
by Deep in the body of the code
#define Name printf("Deep\n"); //Every appearance of Name in the body of the code
will print out Deep
void main()
{
printInt(5);
printf(MY_NAME"\n");
Name //Since the define directive has a semicolon, another one is not needed
here.
return 0;
}
Macros
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
#define DOUBLE(x) ( x * 2 ) /*This is a macro to double the value of any number
provided as an argument. The type of the parameter for the MACRO need not be
declared. The second set of parentheses contains all the code for the MACRO.
Typically, MACRO names are capitals so that anyone reading through the code
knows that it is a MACRO.*/
void main()
{
printInt(5);
printf("%i\n", DOUBLE(3));
printf("%f\n", DOUBLE(2.568));
return 0;
}

Enumeration
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
typedef enum
{
summer, fall, winter, spring
} season;
void printSeason (season s);
void main()
{
printSeason(summer);
printSeason(2); //Each member of the enum corresponds to a number by default.
Typically it starts at 0. So 2 here is Winter.
return 0;
}
void printSeason (season s) /*This function just prints out a phrase based on what
season it is*/
{
if (s == summer)
printf("It's hot.\n");
else if (s == fall)
printf("It's getting cooler.\n");
else if (s == winter)
printf("It's rather cold.\n");
else if (s == spring)
printf("It's getting warmer.\n");
}
Changing the default numbering of enum
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
typedef enum
{
summer, fall, winter = 50, spring /*The number for winter is now changed to 50.
Spring automatically changes to 51. Each enumerant corresponds to a number one
greater than the last. So summer = 0, fall = 1, winter = 50 and spring = 51.*/
} season;
void printSeason (season s);

void main()
{
printSeason(summer);
printSeason(51); //Since winter changed to 50, spring changed to 52.
printSeason(1); //Fall is still 1.
return 0;
}
void printSeason (season s) /*This function just prints out a phrase based on what
season it is*/
{
if (s == summer)
printf("It's hot.\n");
else if (s == fall)
printf("It's getting cooler.\n");
else if (s == winter)
printf("It's rather cold.\n");
else if (s == spring)
printf("It's getting warmer.\n");
}
Enumerations are always stored in memory as their corresponding
number.
Typedef keyword
Sometimes some type of data is used a lot in the code. For example Unsigned
Long Long.
So typedef allows us to create an alternative name for variable types.
typedef unsigned long long UINT64;
We have been declaring data types like this:
typedef struct
{
Some code
} myStruct;
Inside main:
myStruct s = something;
however, if we define it this way:
struct myStruct
{
Some code
};

Then the initialization becomes:


struct myStruct = something;
Const keyword
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
void main()
{
const int i = 2; //i is now a constant data type and the value cannot be changed
anymore.
printf("%i\n",i);
return 0;
}
Const for pointers
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
void main()
{
int i = 3, j = 7;
const int * ip = &i;//can't change the value that ip points to (i). But can change
what ip points to.
printf("%i\n",ip);
ip = &j;
printf("%i\n",ip);
int * const jp = i; //can't change what jp points to but can change the value of
what jp points to.
printf("%i\n",jp);
*jp = 5;
printf("%i\n",*jp);
const int * const kp = i; //can't change what kp points to and neither the value of
what kp points to.
return 0;
}
Ternary operator
#include <stdio.h>
#include <stdlib.h>
#include "myFile.h"
/*int isFive (int i)
{
if (i == 5)

return 1;
else return 0;
}*/
int isFive (int i)
{
return ((i == 5) ? 1:0);//return 1 if the condition is true, 0 otherwise. Equivalent to
the above function.
}
void main()
{
printf("%i\n", isFive(5));
return 0;
}
Character functions
Character functions are located in the file ctype.h
So this file has to be included: #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void main()
{
printf("%i\n", isalnum('g'));//This function determines whether the argument is a
character or a number. Returns 0 if the argument is not a char or a num.
printf("%i\n", isalpha('g'));//This function checks whether this is an alphabet.
printf("%i\n", isdigit('5'));//This function checks whether this is a decimal digit.
printf("%i\n", isxdigit('F'));//This function checks whether this is a hexadecimal
digit.
printf("%i\n", islower('d'));//This function checks whether this is a lower case
letter.
printf("%i\n", isupper('D'));//This function checks whether this is a upper case
letter.
printf("%c\n", tolower('D'));//This function converts the argument to a lower case
letter.
printf("%c\n", toupper('d'));//This function converts the argument to an upper
case letter.
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void main()

{
printf("\a"); //Alert. On most systems this generates a beep.
printf("Book\bt\n"); //Backspace. Changes Book to Boot here.
printf("adam\rbob\n"); //Carriage return. The last three characters - Bob replaces
the first three - ada.
printf("%i\n", iscntrl('\n')); //Determines whether the argument is a control
character - between 0 and 31 along with 127.
printf("%i\n", isprint('n')); //Determines whether the argument is a print character
- between 32 and 126.
printf("%i\n", isgraph(' ')); //Determines whether the argument is a print
character. But ignores space.
printf("%i\n", ispunct('$')); //Determines whether the argument is a special
character.
return 0;
}
String functions
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
size_t intSize = sizeof(int); //The size_t variable exists to be able to store sizeof
data. It is big enough to store this data on any computer.
printf("%u\n", intSize); //All these are unsigned types.
char *name = "Bobby";
printf("%u\n", strlen(name)); //strlen calculates the size of the string but does not
account for the null terminating character.
char *name2 = "Bob";
printf("%i\n", strcmp(name, name2)); //Compares the two strings character by
character and returns a negative number if they don't match. Returns a 0 if each
character in both strings is the same.
if (strcmp(name, name2) != 0)
printf("The names do not match\n");
printf("%i\n", strncmp(name, name2, 3)); //This function simple compares the
two strings but only for the number of characters mentioned.
if (strncmp(name, name2, 3) == 0)
printf("The names match\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
char *source = "Bob";
char dest[strlen(source)]; //The dest is always an array and not a pointer
because if a char pointer is used there is no way to allocate memory for the strcpy()
function.
strcpy(dest,source); //Copies the entire string from source to dest. If source is
bigger than dest then program crashes due to invalid memory access.
printf("%s\n", dest);
char dest1[2];
strncpy(dest1, source, 2); //This copies 2 characters from the source string into
the dest1 array.
printf("%s\n", dest1);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char first[20] = "Deep "; //This is an array so that the strcat() function has
memory space in first to copy "Bhatt" from the location pointed to by last to the end
of "Deep"
char first1[20];
strcpy(first1, first);
char *last = "Bhattacharya";
strcat(first, last); //This function just copies the string last and pastes it at the
end of the string first. But last is not removed.
printf("%s\n", first);
strncat(first1, last, 5); //Copies 5 characters from last to the end of first1.
printf("%s\n", first1);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char *sent = "What a day!";
char *loc_1 = strchr(sent, 'a'); //The strchr() function finds the memory location
of the first a (searches from the left) inside 'sent'.

printf("%i\t%i\t%i\n", &sent, &loc_1, loc_1 - sent); //loc_1 - sent gives us the


index of the first a inside sent.
char *loc_2 = strrchr(sent, 'a'); //Finds the memory location of the last a
(searches from the right) inside 'sent'.
printf("%i\t%i\n", &loc_2, loc_2 - sent);
return 0;
}
Generating random numbers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
srand(time(NULL)); /*The time(NULL) function gets the system time down to the
millisecond. This is used to create the seed by srand(). The time() function is located
in the time.h file.*/
/*The following code generates 10 random numbers. However, if we run this
multiple times the numbers won't change. The srand() function is required to
change the seed.*/
for (int i = 0; i < 10; i++)
printf("%i\n", rand() % 50 + 5); //We want a random number between 5 and 50.
This is what the '%10' is doing.
return 0;
}
Math functions
#include <math.h>
pow(2,3)
When pow(m,n) is too large it returns a value called HUGE_VAL. The following can
be used:
if (ans == HUGE_VAL)
printf("Value is too large.\n");
else
printf("%.2f", ans);
sqrt(i)
floor(m)
ceil(m)

fabs(m) floating point absolute value. This takes a double argument and returns a
double.
abs(m) this is in stdlib.h and not in math.h. This takes an integer and returns an
integer.

You might also like