0% found this document useful (0 votes)
3 views

Basics of C Program

The document provides a comprehensive overview of the C programming language, covering its definition, main features, structure, and various components including data types, control statements, and loops. It explains the syntax and usage of fundamental programming constructs such as if statements, loops, and operators, along with examples. Additionally, it details the sizes and ranges of different data types in C, making it a useful resource for beginners and those looking to understand the basics of C programming.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Basics of C Program

The document provides a comprehensive overview of the C programming language, covering its definition, main features, structure, and various components including data types, control statements, and loops. It explains the syntax and usage of fundamental programming constructs such as if statements, loops, and operators, along with examples. Additionally, it details the sizes and ranges of different data types in C, making it a useful resource for beginners and those looking to understand the basics of C programming.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

BASICS OF C

LANGUAGE
Exercise Table of content

1 C program definition

2 Main feature of c

3 Structure of the c program(syntax)

4 #include definition

5 Component of a c program

6 Data types in c

7 Data types and it’s size

8 If statement

9 If else statement

10 Loop in c (for,while,do-while)

11 Loop control statement

12 Operators in c & types

13 Pointers

14 Structure (Detail explanation)

15 Switch case statement

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.

The main features of the C language include:

 General Purpose and Portable


 Low-level Memory Access
 Fast Speed
 Clean Syntax

These features make the C language suitable for system


programming like an operating system or compiler
development.
Structure of the C program
 After the above discussion, we can formally assess the
structure of a C program. By structure, it is meant that any
program can be written in this structure only. Writing a C
program in any other structure will hence lead to a
Compilation Error. The structure of a C program is as follows:

#include command

A way of including a standard or user-defined file in the program and is mostly


written at the beginning of any C/C++ program. The #include preprocessor directive
is read by the preprocessor and instructs it to insert the contents of a user-defined or
system header file in our C/C++ program.

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:

 stddef.h – Defines several useful types and macros.


 stdint.h – Defines exact width integer types.
 stdio.h – Defines core input and output functions
 stdlib.h – Defines numeric conversion functions, pseudo-random network
generator, and memory allocation
 string.h – Defines string handling functions

2. math.h – Defines common mathematical functions.

3. Main Method Declaration

 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.

4. Body of Main Method


 The body of a function in the C program refers to statements that are a part of
that function. It can be anything like manipulations, searching, sorting, printing,
etc. A pair of curly brackets define the body of a function. All functions must start
and end with curly brackets.

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:

Purpose of Data Types in C


Data types used in C language refer to an extensive system that we use to declare
various types of functions or variables in a program. Here, on the basis of the type of
variable present in a program, we determine the space that it occupies in storage,
along with the way in which the stored bit pattern will be interpreted.

A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.

Example of Data Types in C


Let us take a look at an example to understand data types better.

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.

Types of Data Types in C


Here are the five major categories into which data types are divided in C language:

Data Type Example of Data


Type

Basic Data Floating-point,


Type integer, double,
character.

Derived Data Union, structure,


Type array, etc.
Enumerated Enums
Data Type

Void Data Empty Value


Type

Bool Type True or False

The basic data types are also known as the primary data types in C programming.

Primary Data Types in C


Here are the five primitive or primary data types that one can find in C programming
language:

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:

Keyword Used Data Type

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.

DATA TYPES AND ITS SIZE

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

lon 8 -(2^63) to %ll


g (2^63)-1 d
lon
Fo
Si rm
ze at
(b Sp
Data yt eci
Typ es fier
e ) Range

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

The syntax of the if statement in C programming is:

if (test expression)
{
// code
}

How if statement works?

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

// Program to display a number if it is negative

#include <stdio.h>
int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// true if number is less than 0


if (number < 0) {
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

return 0;
}

OUTPUT

Enter an integer: 156

The if statement is easy.

C if...else Statement

The if statement may have an optional else block. The syntax of


the if..else statement is:
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}

How if...else statement works?

If the test expression is evaluated to true,

 statements inside the body of if are executed.


 statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,

 statements inside the body of else are executed


 statements inside the body of if are skipped from execution.

Working
of if...else Statement
Example : if...else statement

// Check whether an integer is odd or even

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// True if the remainder is 0


if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",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:

for (initialize expression; test expression; update


expression)
{
//
// body of for loop
//
}

Example:

for(int i = 0; i < n; ++i)


{
printf("Body of for loop which will execute till n");
}

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

Loop control statements in C programming are used to change execution from its
normal sequence.
Name Description

the break statement is used to terminate the switch and loop


break
statement. It transfers the execution to the statement immediately
statement
following the loop or switch.

continue continue statement skips the remainder body and immediately


statement resets its condition before reiterating it.

goto
goto statement transfers the control to the labeled statement.
statement

Operators in C

Operators can be defined as the symbols that help us to perform specific


mathematical, relational, bitwise, conditional, or logical computations on operands. In
other words, we can say that an operator operates the operands. For example, ‘+’ is
an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands.
The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. The
functionality of the C programming language is incomplete without the use of
operators.
Types of Operators in C

C has many built-in operators and can be classified into 6 types:


Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Other Operators

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

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

. Member selection via object name left-to-right


1

-> Member selection via a pointer left-to-right

Postfix increment/decrement (a is a
a++/a– left-to-right
variable)

Prefix increment/decrement (a is a
++a/–a right-to-left
variable)

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

Cast (convert value to temporary value


2 (type) right-to-left
of type)

* Dereference right-to-left

& Address (of operand) right-to-left

Determine size in bytes on this


sizeof right-to-left
implementation
Precedenc
e Operator Description Associativity

3 *,/,% Multiplication/division/modulus left-to-right

4 +/- Addition/subtraction left-to-right

5 << , >> Bitwise shift left, Bitwise shift right left-to-right

Relational less than/less than or equal


< , <= left-to-right
to
6
Relational greater than/greater than or
> , >= left-to-right
equal to

7 == , != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

14 = Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left


Precedenc
e Operator Description Associativity

*= , /= Multiplication/division assignment right-to-left

%= , &= Modulus/bitwise AND assignment right-to-left

Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment

<>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

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?

The use of pointers can be divided into three steps:


Pointer Declaration
Pointer Initialization
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.

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;

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
const data_type * pointer_name;

10. Pointer to Constant

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

We have to declare structure in C before using it in our program. In structure


declaration, we specify its member variables along with their datatype. We can use
the struct keyword to declare the structure in C using the following syntax:

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:

1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand


struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.

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.

1. Initialization using Assignment Operator


structstructure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.
2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };


In this type of initialization, the values are assigned in sequential order as they are
declared in the structure template.

3. Initialization using Designated Initializer List

Designated Initialization allows structure members to be initialized in any order. This


feature has been added in the C99 standard.
struct structure_name str = { .member1 = value1, .member2 = value2, .member3 =
value3 };

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
}

Example: Simple Calculator

// Program to create a simple calculator


#include <stdio.h>

int main() {
char operation;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&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;

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
}

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

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Unions

The Union is a user-defined data type in C language that can contain


elements of the different data types just like structure. But unlike structures,
all the members in the C union are stored in the same memory location.
Due to this, only one member can store data at the given instance.
Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as
follows:

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

// C Program to demonstrate how to use union

#include <stdio.h>

// union template or declaration

union un {

int member1;

char member2;

float member3;

};

// driver code

int main()

// defining a union variable


union un var1;

// initializing the union member

var1.member1 = 15;

printf("The value stored in member1 = %d",

var1.member1);

return 0;

Output

The value stored in member1 = 15

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:

1. Function with no arguments and no return value


2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and with return value

Function Declaration and Definition

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;
}

A function consist of two parts:

 Declaration: the function's name, return type, and parameters (if


any)
 Definition: the body of the function (code to be executed)
 void myFunction() { // declaration
// the body of the function (definition)
}

For code optimization, it is recommended to separate the declaration and


the definition of the function.
You will often see C programs that have function declaration above main(),
and function definition below main(). This will make the code better
organized and easier to read:

Example

// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// 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 sum(int x, int y)

int c;

c = x + y;

// Integer value retured

return c;

// Driver Code

int main()

// Integer Declared

int a = 3, b = 2;

// Function Called

int c = sum(a, b);

printf("Sum of %d and %d : %d", a, b, c);


return 0;

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)

int temp = *x;

*x = *y;

*y = temp;

// Driver Code

int main()

// Declaring Integer

int x = 1, y = 5;

printf("Before Swapping: x:%d , y:%d\n", x, y);

// Calling the function

swap(&x, &y);

printf("After Swapping: x:%d , y:%d\n", x, y);

return 0;

}
Output
Before Swapping: x:1 , y:5
After Swapping: x:5 , y:1

Function with arguments and return value

Syntax:

Function declaration : int function ( int );


Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}
Example:

// C code for function with arguments

// and return value

#include <stdio.h>

#include <string.h>

int function(int, int[]);

int main()

{
int i, a = 20;

int arr[5] = { 10, 20, 30, 40, 50 };

a = function(a, &arr[0]);

printf("value of a is %d\n", a);

for (i = 0; i < 5; i++) {

printf("value of arr[%d] is %d\n", i, arr[i]);

return 0;

int function(int a, int* arr)

int i;

a = a + 20;

arr[0] = arr[0] + 50;

arr[1] = arr[1] + 50;

arr[2] = arr[2] + 50;


arr[3] = arr[3] + 50;

arr[4] = arr[4] + 50;

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

You might also like