Notes of C
Notes of C
There come situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next. Similar situations
arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code. For example, in C if x
occurs then execute y else execute z. There can also be multiple conditions like in
C if x occurs then execute p, else if condition y occurs execute q, else execute r.
This condition of C else-if is one of the many ways of importing multiple
conditions.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. If we do not provide the curly braces ‘{‘ and
‘}’ after if(condition) then by default if statement will consider the first
immediately below statement to be inside its block.
Example of if in C/C++:
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15) {
printf("10 is greater than 15");
}
{
// Executes this block if
// condition is false
}
Example of if-else
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15) {
int main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
return 0;
}
4. switch Statement in C/C++
The switch case statement is an alternative to the if else if ladder that can be used
to execute the conditional code based on the value of the variable specified in the
switch statement. The switch block consists of cases to be executed based on the
value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Example of switch Statement
#include <stdio.h>
int main()
{
// variable to be used in switch statement
int var = 2;
return 0;
}
Jump Statements in C/C++
These statements are used in C or C++ for the unconditional flow of control
throughout the functions in a program. They support four types of jump
statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break
statement is encountered from within a loop, the loop iterations stop there, and
control returns from the loop immediately to the first statement after the loop.
Syntax of break
break;
Basically, break statements are used in situations when we are not sure about the
actual number of iterations for the loop or we want to terminate the loop based on
some condition.
B) continue
This loop control statement is just like the break statement. The continue
statement is opposite to that of the break statement, instead of terminating the
loop, it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the loop,
the code inside the loop following the continue statement will be skipped and the
next iteration of the loop will begin.
Syntax of continue
continue;
C) goto
The goto statement in C/C++ also referred to as the unconditional jump statement
can be used to jump from one point to another within a function.
Syntax of goto
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the
statement marked as a label. Here, a label is a user-defined identifier that indicates
the target statement. The statement immediately followed after ‘label:’ is the
destination statement. The ‘label:’ can also appear before the ‘goto label;’
statement in the above syntax.
D) return
The return in C or C++ returns the flow of the execution to the function from
where it is called. This statement does not mandatorily need any conditional
statements. As soon as the statement is executed, the flow of the program stops
immediately and returns the control from where it was called. The return
statement may or may not return anything for a void function, but for a non-void
function, a return value must be returned.
Syntax of return
return [expression];
C – Loops:
Loops in programming are used to repeat a block of code until the specified
condition is met. A loop statement allows programmers to execute a statement or
group of statements multiple times without repetition of code.
int main()
{
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Loop
Type Description
first Initializes, then condition check, then executes the body and at last,
for loop
the update is done.
while first Initializes, then condition checks, and then executes the body, and
loop updating can be inside the body.
do-while
do-while first executes the body and then the condition check is done.
loop
for Loop:
for loop in C programming is a repetition control structure that allows
programmers to write a loop that will be executed a specific number of times. for
loop enables programmers to perform n number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
// Driver code
int main()
{
int i = 0;
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
// C program to illustrate
// while loop
#include <stdio.h>
// Driver code
int main()
{
// Initialization expression
int i = 2;
// Test expression
while(i < 10)
{
// loop body
printf( "Hello World\n");
// update expression
i++;
}
return 0;
}
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-
while loop test condition which is tested at the end of the body. In the do-while
loop, the loop body will execute at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
// C program to illustrate
// do-while loop
#include <stdio.h>
// Driver code
int main()
{
// Initialization expression
int i = 2;
do
{
// loop body
printf( "Hello World\n");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0;
}
C Functions:
A function in C is a set of statements that when called perform some specific task.
It is the basic building block of a C program that provides modularity and code
reusability. The programming statements of a function are enclosed within { }
braces, having certain meanings and performing certain operations. They are also
called subroutines or procedures in other languages.
Syntax of Functions in C
Function Declaration
Function Definition
Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and
the number and type of its parameters. A function declaration tells the compiler
that there is a function with the given name defined somewhere else in the
program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also
declare the function without using the name of the data variables.
Example
int sum(int a, int b);
int sum(int , int);
Function Definition
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the
function definition always starts with the function declaration so we do not need
to declare it explicitly. The below example serves as both a function definition
and a declaration.
Example of C Function
Types of Functions
There are two types of functions in C:
Library Functions
User Defined Functions
1. Library Function
A library function is also referred to as a “built-in function”. A compiler package
already exists that contains these functions, each of which has a specific meaning
and is included in the package. Built-in functions have the advantage of being
directly usable without being defined, whereas user-defined functions must be
declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they always work.
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
double Number;
Number = 49;
1. Pass by Value: Parameter passing in this method copies values from actual
parameters into formal function parameters. As a result, any changes made inside
the functions do not reflect in the caller’s parameters.
Example:
#include <stdio.h>
void swap(int var1, int var2){
int temp = var1;
var1 = var2;
var2 = temp;
}
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
2. Pass by Reference: The caller’s actual parameters and the function’s actual
parameters refer to the same locations, so any changes made inside the function
are reflected in the caller’s actual parameters.
Example:
// call by Reference
#include <stdio.h>
void swap(int *var1, int *var2)
{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
int main()
{
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned
below:
The function can reduce the repetition of the same statements in the
program.
The function makes code readable by providing modularity to our program.
There is no fixed number of calling functions it can be called as many times
as you want.
The function reduces the size of the program.
Once the function is declared you can just use it without thinking about the
internal working of the function.
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
Cannot return multiple values.
Memory and time overhead due to stack frame allocation and transfer of
program control.
Scope of variable:
A scope is a region of the program, and the scope of variables refers to the area of
the program where the variables can be accessed after its declaration. This tutorial
guides you on how to use C variable scope.
In C programming, every variable is defined in scope. You can define scope as
the section or region of a program where a variable has its existence; moreover,
that variable cannot be used or accessed beyond that region. In C programming, a
variable declared within a function differs from a variable declared outside of a
function. The variable can be declared in three places. These are:
Position Type
Local variable:
Variables that are declared within the function block and can be used only within
the function are called local variables.
A local scope or block is a collective program statement placed and declared
within a function or block (a specific area surrounded by curly braces). Variables
lying inside such blocks are termed local variables. All these locally scoped
statements are written and enclosed within the left ({) and right (}) curly braces. C
also has a provision for nested blocks, which means that a block or function can
occur within another block or function. So it means that variables declared within
a block can be accessed within that specific block and all other internal blocks of
that block but cannot be accessed outside the block.
#include <stdio.h>
int main ()
{
//local variable definition and initialization
int x,y,z;
//actual initialization
x = 20;
y = 30;
z = x + y;
return 0;
}
Gobal variable
Variables declared outside the function block and accessed inside the function are
called global variables. In most cases, global variables are defined outside a
function or any specific block on top of the C program. These variables hold their
values all through the end of the program and are accessible within any of the
functions defined in your program. Any function can access variables defined
within the global scope, i.e., its availability stays for the entire program after
being declared.
#include <stdio.h>
int main ()
{
//local variable definition and initialization
int x,y;
//actual initialization
x = 20;
y = 30;
z = x + y;
return 0;
}
C Recursion:
In C programming language, you may have heard of the concept of recursion.
You may also have heard that recursion is difficult and complex to understand
and implement. Do not worry! In this article, we are going to cover the basics of
recursion in C, recursive functions, recursive calls, and how it is different from
iteration.
What is Recursion in C?
First, let’s start with the recursion definition,
Recursion is the process of a function calling itself repeatedly till the given
condition is satisfied. A function that calls itself directly or indirectly is called a
recursive function and such kind of function calls are called recursive calls.
In C, recursion is used to solve complex problems by breaking them down into
simpler sub-problems. We can solve large numbers of problems using recursion
in C. For example, factorial of a number, generating Fibonacci series, generating
subsets, etc.
Recursive Functions in C
In C, a function that calls itself is called Recursive Function. The recursive
functions contain a call to themselves somewhere in the function body. Moreover,
such functions can contain multiple recursive calls.
return res;
}
int main()
{
int n = 5;
Strings in C:
A String in C programming is a sequence of characters terminated with a null
character ‘\0’. The C String is stored as an array of characters. The difference
between a character array and a C string is that the string in C is terminated with a
unique character ‘\0’.
C String Declaration Syntax
Declaring a string in C is as simple as declaring a one-dimensional array. Below
is the basic syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable and size
is used to define the length of the string, i.e the number of characters strings will
store.There is an extra terminating character which is the Null character (‘\0’)
used to indicate the termination of a string that differs strings from normal
character arrays.
int main()
{
// declare and initialize string
char str[] = "GeeksforGeeks";
return 0;
}
strlen(string_name
Returns the length of string name.
)
Compares the first string with the second string. If strings are the same it
strcmp(str1, str2)
returns 0.
strcat(s1, s2) Concat s1 string with s2 string and the result is stored in the first string.
C Pointers:
Pointers are one of the core components of the C programming language. A
pointer can be used to store the memory address of other variables, functions, or
even other pointers. The use of pointers allows low-level memory access,
dynamic memory allocation, and many other functionality in C.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C
variables or a memory location. We can access and manipulate the data stored in
that memory location using pointers. As the pointers in C store the memory
addresses, their size is independent of the type of data they are pointing to. This
size of pointers in C only depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the
( * ) dereferencing operator in the pointer declaration.
datatype * ptr;
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define
pointers to functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration: In pointer declaration, we only declare the pointer but do
not initialize it. To declare a pointer, we use the ( * ) dereference
operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not
initialized. Such pointers are called wild pointers.
void geeks()
{
int var = 10;
int* ptr;
int main()
{
geeks();
return 0;
}
Output
Value at ptr = 0x7fff1038675c
Value at var = 10
Value at *ptr = 10
Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter
on which we are defining their types. If we consider the type of variable stored in
the memory location pointed by the pointer, then the pointers can be classified
into the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;
These pointers are pronounced as Pointer to Integer.
Similarly, a pointer can point to any primitive data type. It can point also point to
derived data types such as arrays and user-defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the
pointer to its first element. They are also known as Pointer to Arrays. We can
create a pointer to an array using the given syntax.
Syntax
char *ptr = &array_name;
Pointer to Arrays exhibits some interesting properties which we discussed later in
this article.
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to
Structure. It can be declared in the same way as we declare the other primitive
data types.
Syntax
struct struct_name *ptr;
In C, structure pointers are used in data structures such as linked lists, trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the
pointers in the sense that instead of pointing to the data, they point to the code.
Let’s consider a function prototype – int func (int, char), the function pointer for
this function will be
Syntax
int (*ptr)(int, char);
Note: The syntax of the function pointers changes according to the function
prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another
pointer. Such pointers are called double-pointers or pointers-to-pointer. Instead of
pointing to a data value, they point to another pointer.
Syntax
datatype ** pointer_name;
Dereferencing Double Pointer
*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer
Note: In C, we can create multi-level pointers with any number of levels such as –
***ptr3, ****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location.
They can be created by assigning a NULL value to the pointer. A pointer of any
type can be assigned the NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not
have any associated data type. They are also called generic pointers as they can
point to any type and can be typecasted to any type.
Syntax
void * pointer_name;
One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet.
These types of C-pointers can cause problems in our programs and can eventually
cause them to crash.
Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and
cannot be modified once it is defined. It will always point to the same memory
address.
Syntax
data_type * const pointer_name;
Advantages of Pointers
Following are the major advantages of pointers in C:
Pointers are used for dynamic memory allocation and deallocation.
An Array or a structure can be accessed efficiently with pointers
Pointers are useful for accessing memory locations.
Pointers are used to form complex data structures such as linked lists, graphs,
trees, etc.
Pointers reduce the length of the program and its execution time as well.
Disadvantages of Pointers
Pointers are vulnerable to errors and have following disadvantages:
Memory corruption can occur if an incorrect value is provided to pointers.
Pointers are a little bit complex to understand.
Pointers are majorly responsible for memory leaks in C.
Pointers are comparatively slower than variables in C.
Uninitialized pointers might cause a segmentation fault.