C Language Tutorial For Beginners (With Notes) - Code With Harry
C Language Tutorial For Beginners (With Notes) - Code With Harry
Show Player
p )
C Language Tutorial For Beginners (With Notes) Free YouTube Video
I have written these notes, practice sheets, and source code just for you. These are available for free to download and
use. However, some bad people may start selling this material to some innocent students for19.some money!
Create If you think
A Responsive
this material helps, please share this video with everyone and spread the word that this video and notes
Website Using are free!
HTML, CSS
And Bootstrap 4 In Hindi
C programming is the best way to learn to code and get your journey started as a programmer.ThisFree video is Video
YouTube a 15 Hour
long course that will teach you C language from the basics to the very advanced level. We will make two fun games
during the course which you can even play during your free time. There are practice sets included along with Free
Handwritten notes for all the chapters. You can download them from the links below. 20. Login And Registration
Form Using Php & MySQL
Note: You can either download the notes or you can read them on this site itself. PDF download links System
[Php Login for all the chapters
In Hindi]
are at the end of the page Free YouTube Video
Chapter 0: Introduction
21. Linux Tutorial For
What is Programming?
Beginners in Hindi
Computer programming is a medium for us to communicate with computers just like we use Hindi or YouTube
Free English Video
to
communicate with each other, programming is a way for us to deliver our instructions to the computer.
Uses of C
C is a language that is used to program a wide variety of systems. Some of the uses of C are23.asHow
follows:
To Make a
WordPress Website |
1. Major parts of Windows, Linux, and other operating systems are written in C. Wordpress Tutorial for
2. C is used to write driver programs for devices like Tablets, Printers, etc. Beginners | Elementor Tutorial
3. C language is used to program embedded systems where programs need to run faster In in Hindi
limited memory.
4. Free quickly
C is used to develop games, an area where latency is very important i.e. computer has toreact YouTubeonVideo
user
input.
Constants
An entity whose value doesn’t change is called a constant.
Types of constant
Primarily there are 3 types of constant:
Keywords
These are reserved words, whose meaning is already known to the compiler. There are 32 keywords available in c:
do static if while
#include<stdio.h>
int main() {
File : first.c
There are some basic rules which are applicable to all the c programs:
Comments
Comments are used to clarify something about the program in plain language. It is a way for us to add notes to our
program. There are two types of comments in c:
A program is written in plain text. This plain text is a combination of instructions in a particular sequence. The compiler
performs some basic checks and finally convert the program into an executable.
Library functions
C language has a lot of valuable library functions which is used to carry out a certain task, for instance, printf function is
used to print values on the screen.
printf(“This is %d”,i);
// %d for integers
// %c for characters
Types of variables
1. Integer variables - int a=3;
2. Real variables - int a=7.7 (wrong as 7.7 is real) ; float a=7.7;
3. Character variables - char a=’B’;
& is the “address of” operator and it means that the supplied value should be copied to the address which is indicated by
variable i.
Q2. Calculate the area of a circle and modify the same program to calculate the volume of a cylinder given its radius
and height.
Q4. Write a program to calculate simple interest for a set of values representing principle, no of years, and rate of
interest.
Chapter 2: Instructions and Operators:
A C-program is a set of instructions. Just like a recipe - which contains instructions to prepare a particular dish.
Types of instructions:
1.Type declaration instruction
2. Arithmetic instruction
3.Control instruction
Arithmetic Instructions
Note:
2.There is no operator to perform exponentiation in c however we can use pow(x,y) from <math.h>(More later).
Type conversion
Quick Quiz:
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
3*x-8y is (3x)-(8y) or 3(x-8y)?
The answer to the above question is provided by operator precedence & associativity.
Operator precedence
Priority Operators
1st */%
2nd + -
3rd =
Operators of higher priority are evaluated first in the absence of parenthesis.
Operator associativity
When operators of equal priority are present in an expression, the tie is taken care of by associativity
x * y / z => (x * y) / z
x / y * z => (x / y) * z
Control instructions
Determines the flow of control in a program.
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
In ‘C’ language too, we must be able to execute instructions on a condition(s) being met.
If-else statement
The syntax of an if-else statement in c looks like:
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”);
}
== equals to
!= not equal to
Important Note: '=' is used for an assignment whereas '==' is used for an equality check.
The condition can be any valid expression. In C a non-zero value is considered to be true.
Logical Operators
&&, ||, 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.
As the number of conditions increases, the level of indentation increases. This reduces readability. Logical operators
come to rescue in such cases.
Else if clause
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”.
Operator Precedence
Priority Operator
1st !
2nd *,/,%
3rd +,-
4th <>,<=,>=
5th ==,!=
6th &&
7th ||
8th =
Conditional operators
A shorthand “if-else” can be written using conditional or ternary operators.
Syntax,
Switch(integer-expression)
Case c1:
Code;
Case c3:
Code;
default:
Code;
The value of integer-expression is matched against c1,c2,c3......if it matched any of these cases, that case along with all
subsequent “case” and “default” statements are executed.
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
We can use switch case statements even by writing in any order of our choice
Char values are allowed as they can be easily evaluated to an integer
A switch can occur within another but in practice, this is rarely done
int a=10;
if(a=11)
printf(“I am 11”);
else
printf(“I am not 11”);
2. Write a program to find out whether a student is pass or fail; if it requires a total of 40% and at least 33% in each
subject to pass. Assume 3 subjects and take marks as an input from the user.
3. Calculate income tax paid by an employee to the government as per the slabs mentioned below:
4. Write a program to find whether a year entered by the user is a leap year or not. Take the year as input from the
user.
5. Write a program to determine whether a character entered by the user is lowercase or not.
6. Write a program to find the greatest of four numbers entered by the user.
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 Loop
While(condition is true) {
// Code
An example:
int i=0;
while (i<10){
printf(“The value of i is %d”,i); i++;
}
Note:
If the condition never becomes false, the while loop keeps getting executed. Such a loop is known as an infinite loop.
Quick Quiz: Write a program to print natural numbers from 10 to 20 when initial loop counter i is initialized to 0.
i-- (i is decreased by 1)
printf(“—i=%d”,--i);
printf(“i--=%d”,i--);
Do-while loop:
The syntax of do-while loop looks like this:
do {
//code;
//code;
}while(condition)
While -> checks the condition & then executes the code
Do-while -> executes the code & then checks the condition
For Loop
The syntax of for loop looks like this:
//code;
//code;
An example:
for(i=0;i<3;i++)
{
printf(“%d”,i);
printf(“\n”);
}
Output:
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.
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.
7. Write a program to calculate the sum of the numbers occurring in the multiplication table of 8.(Consider 8x1 to 8x10)
8. Write a program to calculate the factorial of a given number using for loop.
10. Write a program to check whether a given number is prime or not using loops.
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);
}
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?
A function is a block of code that performs a particular task. A function can be reused by the programmer in a given
program any number of times.
#include<stdio.h>
void display(); // Function prototype
int main(){
int a;
display(); // Function call
return(0);
}
Function prototype:
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.
Important Points:
Types of Functions:
Library functions: Commonly required functions grouped together in a library file on disk.
User-defined functions: These are the functions declared and defined by the user.
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.
Note:
1. Parameters are the values or variable placeholders in the function definition. Ex: a & b
2. Arguments are the actual values passed to the function to make a call. Ex: 2 & 3
4. If the passed variable is changed inside the function, the function call doesn’t change the value in the calling function.
int change(int a){
return 0;
change is a function which changes a to 77. No, if we call it from main like this.
int b=22;
Quick Quiz: Use the library function to calculate the area of a square with side a.
Recursion
A function defined in C can call itself. This is called recursion.
Example of Recursion:
factorial(n) = 1x 2 x 3...........x n
factorial(n)= 1 x 2 x 3...........n-1 x n
Since we can write factorial of a number in terms of itself, we can program it using recursion.
2. The condition which doesn’t call the function any further in a recursive function is called as the base condition.
3. Sometimes due to a mistake made by the programmer, a recursive function can keep running without returning,
resulting in a memory error.
***
*****
Chapter 6 - Pointers
A pointer is a variable that stores the address another variable.
j is a pointer
j points to i.
&i=> 87994
&j=>87998
*(&i) = 72
*(&j) = 87994
Just like pointer type integer, we also have pointers to char, float, etc.
Although it's a good practice to use meaningful variable names, we should be very careful while reading & working on
programs from fellow programmers.
#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;
}
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:
Just like j is pointing to i or storing the address of i, we can have another variable k which can store the address of j.
What will be the type of k?
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.
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:
This function is capable of swapping the values passed to it. If a=3 and b=4 before a call to swap(a,b), a=4 and b=3
after calling swap.
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
}
Chapter 7 - Arrays
An array is a collection of similar elements.
Syntax,
marks[0]=33;
marks[1]=12;
Note: It is very important to note that the array index starts with 0.
Accessing Elements
Elements of an array can be accessed using:
Quick Quiz: Write a program to accept marks of five students in an array and print them to the screen.
Initialization of an array
There are many other ways in which an array can be initialized.
int cgpa[3]={9,8,8} => Arrays can be initialised while declaration
float marks[]={33,40}
Arrays in memory
Consider this array:
This will reserve 4x3=12 bytes in memory. 4 bytes for each integer.
1 2 3
Pointer Arithmetic
A pointer can be incremented to point to the next memory location of that type.
Quick Quiz: Try these operations on another variable by creating pointers in a separate program. Demonstrate all the
four operations.
This way we can have an integer pointer pointing to the first element of the array like this:
ptr++;
*ptr => will have 9 as it’s value
or
Multidimensional arrays
An array can be of 2 dimension / 3 dimension / n dimensions.
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.
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
3. Write a program to create an array of 10 integers and store a multiplication table of 5 in it.
4. Repeat problem 3 for a general input provided by the user using scanf()
5. Write a program containing a function that reverses the array passed to it.
6. Write a program containing functions that counts the number of positive integers in an array.
7. Create an array of size 3x10 containing multiplication tables of the numbers 2,7 and 9 respectively.
8. Repeat problem 7 for a custom input given by the user.
9. Create a three-dimensional array and print the address of its elements in increasing order.
Chapter 8 - Strings
A string is a 1-d character array terminated by a null(‘\0’) => {this is null character}
The null character is used to denote string termination, characters are stored in contiguous memory locations.
Initializing Strings
Since string is an array of characters, it can be initialized as follows:
char s[]={‘H’,’A’,’R’,’R’,’Y’,’\0’}
Strings in memory
A string is sorted just like an array in the memory as shown below
Quick Quiz: Create a string using " " and print its content using a loop.
Printing Strings
A string can be printed character by character using printf and %c.
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
This tells the compilers to store the string in the memory and the assigned address is stored in a char pointer.
Note:
1. Once a string is defined using char st[]= ”harry”, it cannot be initialized to something else.
2. A string defined using pointers can be reinitialized. => ptr=”rohan”;
strlen() - This function is used to count the number of characters in the string excluding the null ('\0') character.
int length=strlen(st);
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.
strcmp() - This function is used to compare two strings. It returns: 0 if strings are equal
Negetive value if first strings mismatching character's ASCII value is not greater than second string's corresponding
mismatching character. It returns positive values otherwise.
Gets()
Puts()
Printf()
Scanf()
2. Write a program to take a string as an input from the user using %c and %s. Confirm that the strings are equal.
3. Write your own version of strlen function from <string.h>
4. Write a function slice() to slice a string. It should change the original string such that it is now the sliced strings.
Take m and n as the start and ending position for slice.
5. Write your own version of strcpy function from <string.h>
6. Write a program to encrypt a string by adding 1 to the ASCII value of its characters.
7. Write a program to decrypt the string encrypted using the encrypt function in problem 6.
8. Write a program to count the occurrence of a given character in a string.
9. Write a program to check whether a given character is present in a string or not.
Chapter 9 - Structures
Arrays and Strings => Similar data (int, float, char)
Structures can hold => dissimilar data
struct employee{
float salary;
char name[10];
}; • semicolon is important
Quick Quiz: Write a program to store the details of 3 employees from user-defined data. Use the structure declared
above.
Array of Structures
Just like an array of integers, an array of floats, and an array of characters, we can create an array of structures.
facebook[0].code=100;
facebook[1].code=101;
..........and so on.
Initializing structures
Structures can also be initialized as follows:
Structures in memory
Structures are stored in contiguous memory locations for the structures e1 of type struct employee, memory layout looks
like this:
In an array of structures, these employee instances are stored adjacent to each other.
Pointer to structures
A pointer to the structure can be created as follows:
ptr=&e1;
printf(“%d”,*(ptr).code);
Arrow operator
Instead of writing *(ptr).code, we can use an arrow operator to access structure properties as follows
*(ptr).code or ptr->code
Quick Quiz: Complete this show function to display the content of employee.
Typedef keyword
We can use the typedef keyword to create an alias name for data types in c.
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”);
Types of Files
There are two types of files:
Reading a file
A file can be opened for reading as follows:
FILE *ptr;
ptr=fopen(“Harry.txt”,”r”);
int num;
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.
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
We can write to a file in a very similar manner as we read the file
FILE *fptr;
fptr=fopen(“Harry.txt”,”w”);
int num=432;
fprintf(fptr,”%d”,num);
fclose(fptr);
while(1){
ch=fgetc(ptr); // When all the content of a file has been read, break the loop
if(ch==EOF){
break;
}
//code
}
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
1. malloc()
2. calloc()
3. free()
4. realloc()
malloc() function
Malloc stands for memory allocation. It takes number of bytes to be allocated as an input and returns a pointer of type
void.
Syntax:
Quick Quiz: Write a program to create a dynamic array of 5 floats using malloc().
calloc() function
calloc stands for continuous allocation.
Syntax:
If the space is not sufficient, memory allocation fails and a NULL pointer is returned.
Quick Quiz: Write a program to create an array of size n using calloc() where n is an integer entered by the user.
free() function
We can use free() function to allocate the memory.
Syntax:
Quick Quiz: Write a program to demonstrate the usage of free() with malloc().
realloc() function
Sometimes the dynamically allocated memory is insufficient or more than required.
realloc is used to allocate memory of new size using the previous pointer and size.
Syntax:
← Previous Next →
© 2020-2021 CodeWithHarry.com
Back to top | Privacy | Terms