C-Programming written by Santosh Or Kanchhi Chauhan
C-Programming:-
Written by Santosh chauhan or Kanchhi chauhan
C-Programming-
Written by (Santosh chauhan Or kanchhi chauhan)
I have divided to this course in the 8 chapter.
Chapter 0 Introduction of C- Programming
Chapter 1 Variables, Constants and keywords.
Chapter 2 Instructions and operators
Chapter 3 Conditional statements
Chapter 4 Loop control statements
Chapter 5 Functions
Chapter 6 Recursion
Chapter 7 Pointers
Chapter 8 Dynamic Memory Allocation
Chapter 0:-
Computer Programming:->
Computer programming is a medium for us to the communicate with computers, to communicate with each other
programming is a way for us to deliver our instruction to the
computer.
C-Programming:->
1. C is a case sensitive programming language as well as
one of the oldest programming language and finest
programming.
2. C was developed by Dennis Ritchie AT and T’s Bell
laboratory (USA) in 1972.
Uses of C- Programming:-
1. All operating system (windows, Linux)
are written in C-Programming.
2. C is used to driver programs
for device like Smart calculator,
Printers as well as Tablets.
3. C is used to program Embedded system where
program need to run faster in limited
memory(Microwave, Cameras).
Chapter 1:->
Constants:->
An entity whose value doesn’t change is called a constant.
There are many types of constant:->
Primarily there are 3 types of constant:
1. Integer Constant 3,-6,8,9
2. Real Constant -342.1,5.5,9.0
3. Character Constant ‘a’,’$’,’@’(must be enclosed within single inverted commas)
Keywords:->
These are reserved words whose meaning is already known to the compiler.
There are 32 keywords available in c:->
auto double int struct
break long else switch
case return enum typedef
char register extern union
const short float unsigned
continue signed for void
default sizeof goto volatile
do static if while
Our first C program:->
#include<stdio.h>
int main() {
printf(“Hello, C with Santosh is best cyber security channel");
return 0;
}
File : first.c
The basic structure of a C program:->
All c programs have to follow a basic structure. A c program starts with the main function and executes instructions presents inside it. Each instruction terminated with a semicolon(;)
There are some basic rules which are applicable to all the c programs:->
1. Every program's execution starts from the main function.
2. All the statements are terminated with a semi-colon.
3. Instructions are case-sensitive.
4. Instructions are executed in the same order in which they are
written.
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:
Single line comment: //This is a comment.
Multi-line comment : /*This is multi-line comment*/
Comments in a C program are not executed and ignored.
Compilation and execution
A compiler is a computer program that converts a c program into machine language so that it can be easily understood by the computer.
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 converts 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
// %f for real values
// %c for characters
Integer variables | int a=3; |
Real variables | int a=7.7 (wrong as 7.7 is real) ; float a=7.7; |
Character variables | char a=’B’; |
Receiving input from the user:-
In order to take input from the user and assign it to a variable, we use scanf function.
The syntax for using scanf:
& is the “address of” operator, and it means that the supplied value should be copied to the address which is indicated by variable i.
// %c for characters
Chapter 2:-
Instructions and Operators:-
In the computer science, an instruction is single operation of a processor defined by the processor instruction set.
Types of instructions:
1.Type declaration instruction
2. Arithmetic instruction
3.Control instruction
Type of declaration instruction:
Airthmetic Instructions:-
1. No operator is assumed to be present
int i=ab ( Invalid )
int i=a*b ( valid )
2.There is no operator to perform exponentiation in c however we can use pow(x,y) from <math.h>(More later).
Type Conversion:-
Operator Precedence in C:-
3*x-8y is (3x)-(8y) or 3(x-8y)?
In the c language, simple mathematical rules like BODMAS no longer apply.
The answer to the above question is provided by operator precedence & associativity.
Operator precedence:-
The following table list the operator priority in C
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
Control instructions:-
Determines the flow of control in a program.
Four types of control instruction in C are:
1. Sequence Control Instruction
2. Decision Control Instruction
3. Loop Control Instruction
4. Case-Control Instruction
Relational Operators in C
Relational operators are used to evaluate (true or false) inside the if statements. Some examples of relational operators are:
== | 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.
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.
Use of logical operators:
As the number of conditions increases, the level of indentation increases. This reduces readability. Logical operators come to the 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.
Using if-else if-else reduces indents. The last “else” is optional. Also, there can be any number of “else if.”
Last else is executed only if all conditions fail.
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.
Here, '?' and ':' are Ternary operators.
Switch case-control instruction
Switch-case is used when we have to make a choice between the number of alternatives for a given variable.
Syntax,
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.
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
Chapter 4 - Loop Control Instruction
What is loop in the computer programming:-
When sometimes to any statement, set of instructions and numeric digit again and again - want to print in the computer programming then - uses to loop.
for eg. Printing 1 to 100, first 100 even numbers, etc.
Hence loops make it easy for a programmer to tell the computer that a given set of instructions must be executed repeatedly.
Types of Loops:
Primarily, there are three types of loop in c language:
1.While loop
2.do-while loop
3.for loop
We will look into this one by one.
While Loop
An example:
Note:-
If the condition never becomes false, the while loop keeps getting executed. Such a loop is known as an infinite loop.
Increment and decrement operators:-
This first prints i and then decrements it
- +++ operators does not exists => Important
- += is compound assignment operator just like -=, *=, /= & %= =>Also important
Do-while loop:
The syntax of do-while loop looks like this:
Do-while loop works very similar to while loop
While -> checks the condition & then executes the code
Do-while -> executes the code & then checks the condition
**do-while loop = while loop which executes at least once
For Loop
The syntax of for loop looks like this:
Initialize -> setting a lop counter to an initial value
Test -> checking a condition
Increment -> updating the loop counter
An example:
Output:
0
1
2
3
Quick Quiz: Write a program to print first n natural numbers using for loop.
A case of Decrementing for loop
This for loop will keep on running until i becomes 0.
The loop runs in the following steps:
- i is initialized to 5
- The condition “i” (0 or none) is tested
- The code is executed
- i is decremented
- Condition i is checked, and the code is executed if it's not 0.
- & so on until i is non 0.
The Break Statement in C:-
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 are sent outside the loop.
Let us see with an example:
Output: 0, 1, 2, 3, 4, 5 and not 0 to 100.
The continue statement in c:
The continue statement in c is used to immediately move to the next of the loop. The control is taken to the next iteration, thus skipping everything below continue inside the loop for that iteration.
Let us look at an example:
Output: 7 and not 0................9
Notes:
1. Sometimes, the name of the variable might not indicate the behavior of the program.
2. Break statement completely exits the loop
3. Continue statement skips the particular iteration of the loop
Chapter 5 - Functions
What is function?
Functions in C/C++......
Function is a group of statement which can perform the specific task in the Programming.
Or
A function is a set of statements that take inputs, do some specific computation and produces output.
Example and syntax of a function:
Function prototype:
Function prototype is a way to tell the compiler about the function we are going to define in the program.
Here void indicates that the function returns nothing.
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.
Definition of Function Implementation:
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:
- Execution of a c program starts from main()
- A c program can have more than one function
- Every function gets called directly or indirectly from main()
- There are two types of functions in c. Let's talk about them.
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.
Why use functions?
- To avoid rewriting the same logic again and again
- To keep track of what we are doing in a program
- To test and check logic independently
Passing values to functions:
We can pass values to a function and can get a value in return from a function
int sum(int a, int b)
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
Function definition of sum can be:
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
3. A function can return only one value at a time.
4. If the passed variable is changed inside the function, the function call doesn’t change the value in the calling function.
change is a function which changes a to 77. No, if we call it from main like this.
This happens because a copy of b is paused to the change function.
Recursion:
A function defined in C can call itself. This is called recursion.
A function calling itself is also called a recursive function.
Example of Recursion:
A very good example of recursion is factorial
Since we can write factorial of a number in terms of itself, we can program it using recursion.
How does it work?
Important Notes:
1. Recursion is sometimes the most direct way to code an algorithm
2. The condition which doesn’t call the function any further in a recursive function is called 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 7 - Pointers
A pointer is a variable that stores the address of another variable.
i - 72, j -87994
Address - 87994. Address - 87998
j is a pointer
j points to i.
The "address of" (&) operator
The address of operator is used to obtain the address of a given variable
If you refer to the diagrams above
&i=> 87994
&j=>87998
Format specifier for printing pointer address is ‘%u’
The "value of address" operator (*)
The value at address or * operator is used to obtain the value present at a given memory address. It is denoted by *
*(&i) = 72
*(&j) = 87994
How to declare a pointer?
A pointer is declared using the following syntax,
int *j; => declare a variable j of type int-pointer
j=&i =>store address of i in j
Just like pointer type integer, we also have pointers to char, float, etc.
int *ch_ptr; -> pointer to integer
char *ch_ptr; -> pointer to character
float *ch_ptr -> pointer to float
Although it's a good practice to use meaningful variable names, we should be very careful while reading & working on programs from fellow programmers.
A Program to demonstrate Pointers:
#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;
i - 72, j -87995, k-86445
Address - 87994. Address - 87998
Address
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, function calls are of two types.
Call by value -> sending the values of arguments.
Call by reference -> sending the address of arguments.
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.
This is call by value.
In C, we usually make a call by value.
Call by reference:
Here the address of the variable is passed to the function as arguments.
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.
Chapter 8 - Dynamic Memory Allocation
Dynamic Memory Allocation:
Dynamic memory allocation is a way to allocate memory to a data structure during the runtime we can use DMA function available in C to allocate and free memory during runtime.
Function for DMA in C
Following functions are available in C to perform dynamic memory allocation:
- malloc()
- calloc()
- free()
- 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:
The expression returns a NULL pointer if the memory cannot be allocated.
calloc() function
calloc stands for continuous allocation.
It initializes each memory block with a default value of 0.
Syntax:
If the space is not sufficient, memory allocation fails and a NULL pointer is returned.
free() function
We can use free() function to allocate the memory.
The memory allocated using calloc/malloc is not deallocated automatically.
Syntax:
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:
Comments
Post a Comment