C Language Tutorial For Beginners
C Language Tutorial For Beginners
Chapter 0: Introduction
What is Programming?
Variables
do static if while
Our first C program
#include<stdio.h>
int main() {
}
Copy
File : first.c
There are some basic rules which are applicable to all the c programs:
printf(“This is %d”,i);
// %d for integers
// %c for characters
Copy
Types of variables
In order to take input from the user and assign it to a variable, we use
scanf function.
Q2. Calculate the area of a circle and modify the same program to
calculate the volume of a cylinder given its radius and height.
2. Arithmetic instruction
3.Control instruction
Type of declaration instruction:
Arithmetic Instructions
Note:
Solution- 3.0/9=0.333 but since k is an int, it cannot store floats & value
0.33 is demoted to 0.
Operator Precedence in C
Operator precedence
Operator associativity
x * y / z => (x * y) / z
x / y * z => (x / y) * z
4. Case-Control Instruction
1. int a; b=a;
2. int v=3^3;
3. char dt= '21 Dec 2020' ;
1. Integer
2. Floating number
3. Character
If-else statement
Switch statement
If-else statement
if ( condition to be checked) {
Statements-if-condition-true ;
else{
statements-if-condition-false ;
}
Code Example
int a=23;
if (a>18){
printf(“you can drive\n”);
}
Copy
Note that else block is not necessary but optional.
Relational Operators in C
== equals to
>= greater than or equal to
> greater than
< less than
<= less than or equal to
!= not equal to
Important Note: '=' is used for an assignment whereas '==' is used for
an equality check.
&&, ||, and ! are the three logical operators in C. These are read as
“and”, ”or”, and “not”. They are used to provide logic to our c programs.
Instead of using multiple if statements, we can also use else if along with
if thus forming an if-else if-else ladder.
if {
// statements ;
else if { //statements;
else { //statements;
Using if-else if-else reduces indents. The last “else” is optional. Also,
there can be any number of “else if”.
Priority Operator
1st !
2nd *,/,%
3rd +,-
4th <>,<=,>=
5th ==,!=
6th &&
7th ||
8th =
Conditional operators
Syntax,
Switch(integer-expression)
Case c1:
Code;
Case c3:
Code;
default:
Code;
Quick Quiz: Write a program to find the grade of a student given his
marks based on below:
90-100 A <70- F
80-90 B
70-80 C
60-70 D
Important notes
int a=10;
if(a=11)
printf(“I am 11”);
else
printf(“I am not 11”);
Copy
Why loops?
Hence loops make it easy for a programmer to tell the computer that a
given set of instructions must be executed repeatedly.
1.While loop
2.do-while loop
3.for loop
While(condition is true) {
// Code
An example:
int i=0;
while (i<10){
printf(“The value of i is %d”,i); i++;
}
Copy
Note:
If the condition never becomes false, the while loop keeps getting
executed. Such a loop is known as an infinite loop.
i++ (i is increased by 1)
i-- (i is decreased by 1)
printf(“—i=%d”,--i);
printf(“i--=%d”,i--);
do {
//code;
//code;
}while(condition)
Do-while loop works very similer to while loop
While -> checks the condition & then executes the code
Do-while -> executes the code & then checks the condition
//code;
//code;
An example:
for(i=0;i<3;i++)
{
printf(“%d”,i);
printf(“\n”);
}
Copy
Output:
2
Quick Quiz: Write a program to print first n natural numbers using for
loop.
for(i=5; i; i--)
printf(“%d\n”,i);
1. i is initialized to 5
2. The condition “i” (0 or none) is tested
3. The code is executed
4. i is decremented
5. Condition i is checked and the code is executed if it's not 0.
6. & so on until i is non 0.
The break statement is used to exit the loop irrespective of whether the
condition is true or false. Whenever a “break” is encountered inside the
loop, the controls sent outside the loop.
int skip=5;
int i=0;
while(i<10){
if(i != skip)
continue;
else
printf(%d”,i);
}
Copy
Output: 5 and not 0................9
Notes:
1. Sometimes, the name of the variable might not indicate the behavior
of the program.
At least once
At least twice
At most once
4. What can be done using one type of loop can also be done using the
other two types of loops – True or False.
5. Write a program to sum the first ten natural numbers using a while
loop.
When the user guesses the correct number, the program displays the
number of guesses the player used to arrive at the number.
Hints:
Use loops
Use a random number generator.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int number, guess, nguesses=1;
srand(time(0));
number = rand()%100 + 1; // Generates a random number
between 1 and 100
// printf("The number is %d\n", number);
// Keep running the loop until the number is guessed
do{
printf("Guess the number between 1 to 100\n");
scanf("%d", &guess);
if(guess>number){
printf("Lower number please!\n");
}
else if(guess<number){
printf("Higher number please!\n");
}
else{
printf("You guessed it in %d attempts\n",
nguesses);
}
nguesses++;
}while(guess!=number);
return 0;
}
Copy
Sometimes our program gets bigger in size and its not possible for a
programmer to track which piece of code is doing what.
The function is a way to break our code into chunks so that it is possible
for a programmer to reuse them.
What is a function?
#include<stdio.h>
void display(); // Function prototype
int main(){
int a;
display(); // Function call
return(0);
}
Function prototype is a way to tell the compiler about the function we are
going to define in the program.
Function call:
Function call is a way to tell the compiler to execute the function body at
the time the call is made.
Note that the program execution starts from the main function in the
sequence the instructions are written.
Function definition:
This part contains the exact set of instructions that are executed during
the function call. When a function is called from main(), the main function
falls asleep and gets temporarily suspended. During this time the control
goes to the function being called when the function body is done
executing main() resumes.
We can pass values to a function and can get a value in return from a
function
The above prototype means that sum is a function which takes values
a(of type int) and b(of type int) and returns a value of type int
c=a+b;
return c;
Now we can call sum(2,3) [here 2 and 3 are arguments]; from main to
get 5 in return.
4. If the passed variable is changed inside the function, the function call
doesn’t change the value in the calling function.
return 0;
int b=22;
Quick Quiz: Use the library function to calculate the area of a square
with side a.
Recursion
Example of Recursion:
factorial(n) = 1x 2 x 3...........x n
factorial(n)= 1 x 2 x 3...........n-1 x n
Important Notes:
2. The condition which doesn’t call the function any further in a recursive
function is called as the base condition.
***
*****
Chapter 6 - Pointers
j is a pointer
j points to i.
The "address of" (&) operator
&i=> 87994
&j=>87998
*(&j) = 87994
How to declare a pointer?
Just like pointer type integer, we also have pointers to char, float, etc.
#include<stdio.h>
int main()
{
int i=8;
int *j;
j=&i;
printf(“Add i=%u\n”,&i);
printf(“Add i=%u\n”,j);
printf(“Add j=%u\n”,&j);
printf(“Value i=%d\n”,i);
printf(“Value i=%d\n”,*(&i));
printf(“Value i=%d\n”,*j);
return 0;
}
Copy
Output:
Add i=87994
Add i=87994
Add j=87998
Value i=8
Value i=8
Value i=8
This program sums it all. If you understand it, you have got the idea of
pointers.
Pointers to a pointer:
int **k;
k= &j;
We can even go further one level and create a variable l of type int*** to
store the address of k. We mostly use int* and int** sometimes in real-
world programs.
Types of function calls
Based on the way we pass arguments to the function, functions calls are
of two types.
Call by value:
Here the values of the arguments are passed to the function. Consider
this example:
If sum is defined as sum(int a, int b), the values 3 and 4 are copied to a
and b. Now even if we change a and b, nothing happens to the variables
x and y.
Call by reference:
Now since the addresses are passed to the function, the function can
now modify the value of a variable in calling function using * and &
operators. Example:
int main()
{
int a=3; // a is 3 and b is 4
int b=4;
swap(a,b)
return 0; // now a is 4 and b is 3
}
Copy
Chapter 7 - Arrays
Syntax,
marks[0]=33;
marks[1]=12;
Note: It is very important to note that the array index starts with 0.
Accessing Elements
float marks[]={33,40}
Arrays in memory
This will reserve 4x3=12 bytes in memory. 4 bytes for each integer.
1 2 3
62302 62306 62310 {Array in Memory}
Pointer Arithmetic
ptr++;
or
We can access the elements of this array as arr [0] [0], arr [0] [1] & so
on...
At arr [0] [0] value would be 1 and at arr [0] [1] value would be 4.
2-D arrays in Memory
A 2-d array like a 1-d array is stored in contiguous memory blocks like
this:
Quick Quiz: Create a 2-d array by taking input from the user. Write a
display function to print the content of this 2-d array on the screen.
True
False
Depends
Chapter 8 - Strings
char s[]={‘H’,’A’,’R’,’R’,’Y’,’\0’}
Quick Quiz: Create a string using " " and print its content using a loop.
Printing Strings
We can use %s with scanf to take string input from the user:
char st[50];
scanf(“%s”,&st);
scanf automatically adds the null character when the enter key is
pressed.
Note:
char st[30];
puts(st); =>Prints the string and places the cursor on the next line
Declaring a string using pointers
This tells the compilers to store the string in the memory and the
assigned address is stored in a char pointer.
Note:
strcpy() - This function is used to copy the content of second string into
first string passed to it.
char target[30];
Target string should have enough capacity to store the source string.
Gets()
Puts()
Printf()
Scanf()
Chapter 9 - Structures
struct employee{
float salary;
char name[10];
}; • semicolon is important
We can create the data types in the employee structure separately but
when the number of properties in a structure increases, it becomes
difficult for us to create data variables without structures. In a nutshell:
facebook[0].code=100;
facebook[1].code=101;
..........and so on.
Initializing structures
ptr=&e1;
Copy
Now we can print structure elements using:
printf(“%d”,*(ptr).code);
Copy
Arrow operator
*(ptr).code or ptr->code
A structure can be passed to a function just like any other data type.
struct complex{
float real; // struct complex c1,c2;
for defining complex numbers
float img;
};
A file data stored in a storage device. A C program can talk to the file by
reading content from it and writing content to it.
File pointer
The “File” is a structure that needs to be created for opening the file. A
file pointer is a pointer to this structure of the file.
File pointer is needed for communication between the file and the
program.
FILE *ptr;
ptr=fopen(“filename.ext”,”mode”);
Copy
File opening modes in C
FILE *ptr;
ptr=fopen(“Harry.txt”,”r”);
int num;
Copy
Let us assume that “Harry.txt” contains an integer
This will read an integer from the file in the num variable.
Quick Quiz: Modify the program above to check whether the file exists
or not before opening the file.
Closing the file
It is very important to close file after read or write. This is achieved using
fclose as follows:
fclose(ptr);
This will tell the compiler that we are done working with this file and the
associated resources could be freed.
Writing to a file
FILE *fptr;
fptr=fopen(“Harry.txt”,”w”);
int num=432;
fprintf(fptr,”%d”,num);
fclose(fptr);
Copy
fgetc() and fputc()
fgetc and fputc are used to read and write a character from/to a file.
fgetc returns EOF when all the characters from a file have read. So we
can write a check like below to detect the end of file.
while(1){
ch=fgetc(ptr); // When all the content of a file has
been read, break the loop
if(ch==EOF){
break;
}
//code
}
Copy
Chapter 10 - Practice Set
name1, 3300
name2, 7700
Your program should be able to print the result after you choose
Snake/Water or Gun.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
// Non-draw conditions
// Cases covered:
// sg
// gs
// sw
// ws
// gw
// wg
}
int main(){
char you, comp;
srand(time(0));
int number = rand()%100 + 1;
if(number<33){
comp = 's';
}
else if(number>33 && number<66){
comp='w';
}
else{
comp='g';
}
printf("Enter 's' for snake, 'w' for water and 'g' for
gun\n");
scanf("%c", &you);
int result = snakeWaterGun(you, comp);
if(result ==0){
printf("Game draw!\n");
}
else if(result==1){
printf("You win!\n");
}
else{
printf("You Lose!\n");
}
printf("You chose %c and computer chose %c. ", you, comp);
return 0;
}
Copy
Chapter 11 - Dynamic Memory Allocation
1. malloc()
2. calloc()
3. free()
4. realloc()
malloc() function
Syntax:
Syntax:
If the space is not sufficient, memory allocation fails and a NULL pointer
is returned.
Syntax:
realloc is used to allocate memory of new size using the previous pointer
and size.
Syntax:
Chapter 11 - Practice Set