Basics of C Program
Basics of C Program
LANGUAGE
Exercise Table of content
1 C program definition
2 Main feature of c
4 #include definition
5 Component of a c program
6 Data types in c
8 If statement
9 If else statement
10 Loop in c (for,while,do-while)
13 Pointers
16 Unions
17 Function (delaration,call,argument,return)
What is C Programming
C is procedural programming language initially developed by
Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T
Labs. It was mainly developed as a system programming
language to write the UNIX operating system.
#include command
Components of a C Program:
1. Header Files Inclusion
The first and foremost component is the inclusion of the Header files in a C
program. A header file is a file with extension .h which contains C function
declarations and macro definitions to be shared between several source files. All
lines that start with # are processed by a preprocessor which is a program invoked
by the compiler. In the above example, the preprocessor copies the preprocessed
code of stdio.h to our file. The .h files are called header files in C.
Some of the C Header files:
The next part of a C program is to declare the main() function. It is the entry point
of a C program and the execution typically begins with the first line of the main().
The empty brackets indicate that the main doesn’t take any parameter
(See this for more details). The int that was written before the main indicates the
return type of main(). The value returned by the main indicates the status of
program termination. See this post for more details on the return type.
Statement
Statements are the instructions given to the compiler. In C, a statement is always
terminated by a semicolon (;). In this particular case, we use printf() function to
instruct the compiler to display “Hello World” text on the screen.
5. Return Statement
The last part of any C function is the return statement. The return statement refers to
the return values from a function. This return statement and return value depend
upon the return type of the function. The return statement in our program returns the
value from main(). The returned value may be used by an operating system to know
the termination status of your program. The value 0 typically means successful
termination.
DATA TYPES IN C:
A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.
For instance, we may want to utilise some numbers such as 5, 8, 600, or maybe a
decimal point number such as 43.59, 127.368, 271.49, or maybe a text such as
“cappuccino”. Then, the compiler used in C language would handle all of these very
differently. Thus, here, we use different data types for defining what data types we
want in the program.
The basic data types are also known as the primary data types in C programming.
1. Integer – We use these for storing various whole numbers, such as 5, 8, 67, 2390,
etc.
2. Character – It refers to all ASCII character sets as well as the single alphabets,
such as ‘x’, ‘Y’, etc.
3. Double – These include all large types of numeric values that do not come under
either floating-point data type or integer data type. Visit Double Data Type in C to
know more.
4. Floating-point – These refer to all the real number values or decimal points, such
as 40.1, 820.673, 5.9, etc.
5. Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
Various keywords are used in a program for specifying the data types mentioned
above. Here are the keywords that we use:
int Integer
float Floating-point
void Void
char Character
double Double
The size of every data type gets defined in bytes/ bits. Also, these data types are
capable of holding a very wide range of values.
Fo
Si rm
ze at
(b Sp
Data yt eci
Typ es fier
e ) Range
sh
-32,768 to %h
ort 2
32,767 d
int
un 2 0 to 65,535 %h
sig u
ne
d
sh
Fo
Si rm
ze at
(b Sp
Data yt eci
Typ es fier
e ) Range
ort
int
un
sig 0 to
%u
ne 4 4,294,967,29
d 5
int
-
2,147,483,64
%d
int 4 8 to
2,147,483,64
7
-
lon 2,147,483,64
%l
g 4 8 to
d
int 2,147,483,64
7
un
sig
ne 0 to
%l
d 4 4,294,967,29
u
lon 5
g
int
g
int
un
sig
ne
0 to
d
18,446,744,0 %ll
lon 8
73,709,551,6 u
g
15
lon
g
int
sig
ne
%c
d 1 -128 to 127
ch
ar
un
sig
ne %c
1 0 to 255
d
ch
ar
flo
4 1.2E-38 to %f
at
3.4E+38
do 8 1.7E-308 to %lf
ubl 1.7E+308
e
Fo
Si rm
ze at
(b Sp
Data yt eci
Typ es fier
e ) Range
lon
g
1
do 3.4E-4932 to %L
6
ubl 1.1E+4932 f
e
C if Statement
if (test expression)
{
// code
}
The if statement evaluates the test expression inside the parenthesis ().
If the test expression is evaluated to true, statements inside the body of if are
executed.
If the test expression is evaluated to false, statements inside the body
of if are not executed.
Example 1: if statement
#include <stdio.h>
int main() {
int number;
return 0;
}
OUTPUT
C if...else Statement
Working
of if...else Statement
Example : if...else statement
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
When the user enters 7, the test expression number%2==0 is evaluated to false. Hence,
the statement inside the body of else is executed.
LOOPS IN C
Loop Type Description
first Initializes, then condition check, then executes the body and at
for loop
last, 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:
Example:
While Loop
While loop does not depend upon the number of iterations. In for loop the number of
iterations was previously known to us but in the While loop, the execution is
terminated on the basis of the test condition. If the test condition will become false
then it will break from the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
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);
Loop control statements in C programming are used to change execution from its
normal sequence.
Name Description
goto
goto statement transfers the control to the labeled statement.
statement
Operators in C
Precedence of Operators in C
The below table describes the precedence order and associativity of operators in C.
The precedence of the operator decreases from top to bottom.
Precedenc
e Operator Description Associativity
Postfix increment/decrement (a is a
a++/a– left-to-right
variable)
Prefix increment/decrement (a is a
++a/–a right-to-left
variable)
* Dereference right-to-left
12 || Logical OR left-to-right
14 = Assignment right-to-left
Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment
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.
In this article, we will discuss pointers in detail, their types, uses, advantages, and
disadvantages with examples.
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.
Syntax
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?
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.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer
variable. We generally use the ( & ) addressof operator to get the memory address of
a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same time.
3. Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory
address specified in the pointer. We use the same ( * ) dereferencing operator that
we used in the pointer declaration.
Types of Pointers
Pointers 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;
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
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
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
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;
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
const data_type * pointer_name;
The pointers pointing to a constant value that cannot be modified are called pointers
to a constant. Here we can only access the data pointed by the pointer, but cannot
modify it. Although, we can change the address stored in the pointer to constant.
Syntax
data_type * const pointer_name;
C Structures
The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type. The struct keyword is used to define the
structure in the C programming language. The items in the structure are called
its member and they can be of any valid data type.
C Structure Declaration
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no
memory is allocated to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by
creating variables of the structure type. We can define structure variables using two
methods:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow
operator to access the members.
Initialize Structure Members
Structure members cannot be initialized with the declaration. For example, the
following C program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no memory is
allocated for it. Memory is allocated only when variables are created.
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.
Switch Statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
int main() {
char operation;
double n1, n2;
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
return 0;
}
Output
Enter an operator (+, -, *, /): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
The - operator entered by the user is stored in the operation variable. And,
two operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.
Since the operation is - , the control of the program jumps to
Unions
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare
the members’ names and data types along with the name of the union. No
memory is allocated to the union in the declaration.
union union_name {
datatype member1;
datatype member2;
...
};
Example of Union
#include <stdio.h>
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
var1.member1 = 15;
var1.member1);
return 0;
Output
Functions
A user-defined function is one that is defined by the user when writing any
program, as we do not have library functions that have predefined
definitions. To meet the specific requirements of the user, the user has to
develop his or her own functions. Such functions must be defined properly
by the user. There is no such kind of requirement to add any particular
library to the program.
Different Types of User-defined Functions in C
There are four types of user-defined functions divided on the basis of
arguments they accept and the value they return:
You just learned from the previous chapters that you can create and call
a function in the following way:
Example
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
Function Call
A function call is an expression that includes the name of the function being
called or the value of a function pointer and, optionally, the arguments
being passed to the function.
Call by Value
Call by value in C is where in the arguments we pass value and that value
can be used in function for performing the operation. Values passed in the
function are stored in temporary memory so the changes performed in the
function don’t affect the actual value of the variable passed.
Example:
// C Program to implement
// Call by value
#include <stdio.h>
// Call by value
int c;
c = x + y;
return c;
// Driver Code
int main()
// Integer Declared
int a = 3, b = 2;
// Function Called
Output
Sum of 3 and 2 : 5
Call by Reference
Call by reference is the method in C where we call the function with the
passing address as arguments. We pass the address of the memory blocks
which can be further stored in a pointer variable that can be used in the
function. Now, changes performed in the values inside the function can be
directly reflected in the main memory.
Example:
// C Program to implement
// Call by reference
#include <stdio.h>
// Call by reference
void swap(int* x, int* y)
*x = *y;
*y = temp;
// Driver Code
int main()
// Declaring Integer
int x = 1, y = 5;
swap(&x, &y);
return 0;
}
Output
Before Swapping: x:1 , y:5
After Swapping: x:5 , y:1
Syntax:
#include <stdio.h>
#include <string.h>
int main()
{
int i, a = 20;
a = function(a, &arr[0]);
return 0;
int i;
a = a + 20;
return a;
Output
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100