0% found this document useful (0 votes)
49 views79 pages

WINSEM2023-24 BECE320E ETH VL2023240504751 2024-03-11 Reference-Material-I

The document discusses arrays in C programming. It defines what an array is and explains that arrays allow storing multiple elements of the same type in contiguous memory locations. It provides examples of valid and invalid array declarations and initialization. It also discusses multi-dimensional arrays and provides examples of initializing and accessing 2D arrays.

Uploaded by

Divya Jagwani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views79 pages

WINSEM2023-24 BECE320E ETH VL2023240504751 2024-03-11 Reference-Material-I

The document discusses arrays in C programming. It defines what an array is and explains that arrays allow storing multiple elements of the same type in contiguous memory locations. It provides examples of valid and invalid array declarations and initialization. It also discusses multi-dimensional arrays and provides examples of initializing and accessing 2D arrays.

Uploaded by

Divya Jagwani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

Module – III

Marimuthu R
SELECT
Array
• An array is a collection of elements of the same type that are
referenced by a common name.
• All the elements of an array occupy a set of contiguous memory
locations.
Ex: Invalid
1 ‘a’ 2 4.5 3 4 ‘c’ ‘b’ 7.2

Ex: Valid
1 6 2 4 9 7
Why Array?
Why need to use array type?
• Consider the following issue:
• "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will
declare something like the following…“
• int studMark0, studMark1, ...studMark999
• Can you imagine how long we have to write the declaration part by using normal variable declaration?
int main(void)
{
int studMark1, studMark2, studMark3,
studMark4, …, …, studMark998, stuMark999,
studMark1000;


return 0;
}
Array
• A single or one dimensional array declaration has the following form,
array_element_data_type array_name[array_size];
• By using an array, we just declare like this,
int studMark[1000];
• This will reserve 1000 contiguous memory locations for storing the
students’ marks.
• Graphically, this can be depicted as in the following figure.
Note
• The length of an array can be specified by any positive integer constant
expression.
Ex: int arr[5] int arr[5*2] int a; int arr[a=21/3]

int arr[-4] ---- Invalid

• Macros are allowed.


#define N 10
int arr[N];

sizeof(a)/sizeof(a[0]); -- Provides number of elements in an array.


Initializing 1D Array
Method 1:
arr[5] = {1,2,3,4,5};
Method 2:
arr[] = {1,2,3,4,5};
Method 3:
int arr[5];
arr[0]=1; arr[1] = 2; so on….
Method 4:
int arr[5];
for(i=0; i<5; i++) {
scanf(“%d”, &arr[i]);
}
Initializing 1D Array
int arr[10] = {45, 2, 6, 7};
Note:
int arr[10] = {0};
int arr[10] = {}; ---- Invalid
int arr[3] = {2,3,4,5}; ------ Invalid
int arr[10] = {[0] = 1, [4] = 3, [7] = 2}; --- Called designated initialization.
int arr[10] = {[4] = 1, [7] = 3, [0] = 2}; --- Order is not an important.
Response of the survey, can be in the range
between 0 and 5. Assume the population size to
be 10.
#include<stdio.h>
#define SIZE 10
#define ANS 5
int main(void) {
int response[SIZE];
int freq[ANS] = {0};
int i;
for(i=0; i< SIZE; i++){
scanf(“%d”,&response[i]);
++freq[response[i]];
}
for(i=0;i<ANS;i++)
printf("Frequency of %d is %d\n",i,freq[i]);
}
Reverse the given number
#include<stdio.h>
int main()
{
int i;
int arr[9] = {2,3,4,5,6,7,8,9,10};
for(i=0; i<9; i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
for(i=8; i>=0; i--)
{
printf("%d\t",arr[i]);
}

}
Palindrome
#include<stdio.h>
#include<string.h>
void main()
{
int len, i, count = 0;
char a[10];
printf(“Enter a string:”);
scanf("%s", &a);
len = strlen(a);
for(i=0; i<len; i++)
{
if (a[i] ==a[len-i-1])
count++;
}
if (len==count)
printf("Palindrome");
else
printf("Not a palindrome");
}
2D ARRAY
• A two dimensional array has two subscripts/indexes.
• The first subscript refers to the row, and the second, to the column.
• Its declaration has the following form, data_type array_name[1st
dimension size][2nd dimension size];
• For examples,
• int xInteger[3][4];
• float matrixNum[20][25];
• The first line declares x Integer as an integer array with 3 rows and 4
columns.
• Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns
DOUBLE SCRIPTED ARRAY WITH 3 ROWS AND 4
COLUMNS
INITIALIZATION OF 2D ARRAY

• int disp[2][4] = { {10, 11, 12, 13}, {14, 15, 16, 17} }; -- Preferable
or
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
INITIALIZING A 2D ARRAY – Points to be noted
• We already know, when we initialize a normal array (or you can say one
dimensional array) during declaration, we need not to specify the size of it.
• However that’s not the case with 2D array, you must always specify the
second dimension even if you are specifying elements during the declaration.
• /* Valid declaration*/ int abc[2][2] = {1, 2, 3 ,4 }
• /* Valid declaration*/
• int abc[][2] = {1, 2, 3 ,4 }
• /* Invalid declaration – you must specify second dimension*/
• int abc[][] = {1, 2, 3 ,4 }
• /* Invalid because of the same reason mentioned above*/
• int abc[2][] = {1, 2, 3 ,4 }
For array storing string
• char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman",
"Arnold", "Jodie"};
• Here, we can initialize the array with 6 strings, each with maximum 9
characters long. If depicted in rows and columns it will look something
like the following and can be considered as contiguous arrangement
in the memory.
Write a program to read 5 x 5 array of integers and then prints row and column sums.

#include <stdio.h>
int main()
{
int a[5][5] = { {28,33,59,0,10}, {33,65,17,19,12}, {12,28,36,23,41}, {15,27,34,26,98},
{26,14,52,65,80} };
int i,j;
int sum=0;
printf("Row Sum:");
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
{
sum+=a[i][j];
}
printf("%d\t", sum);
sum=0;
}
Contd….
printf("\n");
printf("Column Sum:");
for(j=0; j<5; j++)
{
for(i=0; i<5; i++)
{
sum+=a[i][j];
}
printf("%d\t", sum);
sum=0;
}
return 0;
}
Print Transpose of a Matrix
#include <stdio.h>
void main()
{
static int array[10][10];
int i, j, m, n;
printf("Enter the order of the matrix \n");
scanf("%d %d", &m, &n);
printf("Enter the coefficients of the matrix\n");
for (i = 0; i < m; ++i){
for (j = 0; j < n; ++j){
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i){
for (j = 0; j < n; ++j){
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j){
for (i = 0; i < m; ++i){
printf(" %d", array[i][j]);
}
printf("\n");
}
}
Practice
• Write a program to find the largest number in the given array.
10 11 09 45 27

• Write a program to remove the duplicate elements in the given array.

10 11 11 10 09

• Program to move zeroes in an array in the tail end.


7 0 5 0 0

• Program to add two matrix elements.


Pointers
• A pointer is a variable that contains the address of another variable.
They are derived data types.

• They have a number of useful applications.


–Enables us to access a variable that is defined outside the function.
–Can be used to pass information back and forth between a function
and its reference point. (Call by reference)
–More efficient in handling data tables.
–Reduces the length and complexity of a program.
Basic Concept
• In memory, every data item occupies one or more contiguous memory cells
(bytes).
• The number of bytes required to store a data item depends on its type (char, int,
float, double, etc.).
• Whenever we declare a variable, the system allocates memory location(s) for the
variable.
• Since every byte in memory has a unique address, this location will also have its
own (unique) address.
Consider the statement
int xyz = 50;
–This statement instructs the compiler to allocate a location for the integer variable
xyz, and put the value 50 in that location. –Suppose that the address location
chosen is 1380.
Pointer Variable Declarations and
Initialization
• Pointer variables – Contain memory addresses as their values–Normal
variables contain a specific value (direct reference)

• Pointers contain address of a variable that has a specific value


(indirect reference) – Indirection –referencing a pointer value
Contd.
• During execution, the system always associates the name xyz with the
address 1380.
–The value 50 can be accessed by using either the name xyz or the
address 1380.
Since memory addresses are simply numbers, they can be assigned to
some variables which can be stored in memory.
–Such variables that hold memory addresses are called pointers.
–Since a pointer is a variable, its value is also stored in some memory
location.
Contd.

• Suppose we assign the address of xyz to a pointer variable p.


–p is said to point to the variable xyz.
int xyz=50;
int *p;
p = &xyz;
Accessing the Address of a Variable
• The address of a variable can be determined using the ‘&’ operator.
–The operator ‘&’ immediately preceding a variable returns the
address of the variable.
• Example: p = &xyz;
• –The address of xyz (1380) is assigned to p.
• The ‘&’ operator can be used only with a simple variable or an array
element.
&distance
&x[0]
&x[i-2]
Contd.

• Following usages are illegal:


&235 -- Pointing at a constant.
&(a+b) -- Pointing at expression.
Example

#include <stdio.h>
main()
{
int a; float b, c; double d; char ch;
a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ’A’;
printf (”%d is stored in location %u \n”, a, &a) ;
printf (”%f is stored in location %u \n”, b, &b) ;
printf (”%f is stored in location %u \n”, c, &c) ;
printf (”%ld is stored in location %u \n”, d, &d) ;
printf (”%c is stored in location %u \n”, ch, &ch) ;
}
Pointer Declarations
• Pointer variables must be declared before we use them.
• General form:
data_type *pointer_name;
Three things are specified in the above declaration:
•The asterisk (*) tells that the variable
pointer_name is a pointer variable.
pointer_name needs a memory location.
pointer_name points to a variable of type data_type.
Example: int *count; float *speed;
Once a pointer variable has been declared, it can be made to point to a variable using an
assignment statement like:
int *p, xyz;
:
p = &xyz; –This is called pointer initialization.
Remember

• Pointer variables must always point to a data item of the same type.

float x;
int *p;
p = &x; will result in erroneous output
Accessing a Variable Through its Pointer

• Once a pointer has been assigned the address of a variable, the value
of the variable can be accessed using the indirection operator (*).

int a, b;
int *p;
: Equivalent to b = a;
p = &a;
b = *p;
Pointers Example
#include<stdio.h>
void main()
{
int a=10, b=9;
int *p, *q;
p=&a;
q=&b;
printf(“value of a =%d\n”, a);
printf(“value of a =%d\n”, *p);
printf(“value of a =%d\n”, &a);
printf(“value of a =%d\n”, p);
printf(“value of a =%d\n”, &p);
}
Example

#include <stdio.h>
main()
{
int a, b;
int c = 5;
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (”a=%d b=%d \n”, a, b);
}
Example
Pointer Expressions

• Like other variables, pointer variables can be used in expressions.


• If p1 and p2 are two pointers, the following statements are valid:
• sum = *p1 + *p2;
• prod = *p1 * *p2;
• prod = (*p1) * (*p2);
• *p1 = *p1 + 2;
• x = *p1 / *p2 + 5;
Allowed/Not Allowed
• What are allowed in C?
– Add an integer to a pointer.
– Subtract an integer from a pointer.
– Subtract one pointer from another (related).
• If p1 and p2 are both pointers to the same array, then p2–p1 gives the number of
elements between p1 and p2.
• What are not allowed?
– Add two pointers.
p1 = p1 + p2;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5;
p1 = p1 – p2 * 10;
Scale Factor
• We have seen that an integer value can be added to or subtracted from a pointer
variable.
int *p1, *p2;
int i, j;
:
p1 = p1 + 1;
p2 = p1 + j;
p2++;
p2 = p2 – (i + j);
In reality, it is not the integer value which is added/subtracted, but rather the scale
factor times the value.
Contd
• Data Type Scale Factor
char 1
int 4
float 4
double 8

• – If p1 is an integer pointer, then p1++ will increment the value of p1


by 4.
Note: – The exact scale factor may vary from one machine to another. –
Can be found out using the sizeof function. – Syntax: sizeof (data_type)
Pointers and Arrays
• When an array is declared,
– The compiler allocates a base address and sufficient amount of storage to contain all the
elements of the array in contiguous memory locations.
– The base address is the location of the first element (index 0) of the array.
– The compiler also defines the array name as a constant pointer to the first element.
• Consider the declaration:
• int x[5] = {1, 2, 3, 4, 5};
– Suppose that the base address of x is 2500, and each integer requires 4 bytes.
• Element Value Address
• x[0] 1 2500
• x[1] 2 2504
• x[2] 3 2508
• x[3] 4 2512
• x[4] 5 2516
Contd
• Both x and &x[0] have the value 2500.
• p = x; and p = &x[0]; are equivalent.
– We can access successive values of x by using p++ or p-- to move from
one element to another.
• Relationship between p and x:
•p = &x[0] = 2500
• p+1 = &x[1] = 2504
• p+2 = &x[2] = 2508
• p+3 = &x[3] = 2512
• p+4 = &x[4] = 2516
*(p+i) gives the value of x[i]
Example
Pointer to Pointer
• A pointer-to-pointer (double pointer) is used to store the address of
another pointer.
Example

#include <stdio.h>

int main()
{
int var = 78;
int* ptr2;
int** ptr1;
ptr2 = &var;
ptr1 = &ptr2;
printf("Value of var = %d\n", var);
printf("Value of var using single pointer = %d\n", *ptr2);
printf("Value of var using double pointer = %d\n", **ptr1);

return 0;
}
Program

#include<stdio.h>
int main ()
{
int i = 10;
int *ptr;
int **pptr;
int ***ppptr;
ptr = &i;
pptr = &ptr;
ppptr = &pptr;
printf ("\n %d %d %d %d", i, *ptr, **pptr, ***ppptr);
}
Example – Pointer Addition
#include <stdio.h>
int main()
{
int a[5] = {1,4,3,-8,0};
int *p = &a;
int *q = &a;
printf("Value is : %d\n", *p);
printf("Value is : %d\n", p);
p=p+2;
*p = 32;
printf("Value is : %d\n", *p);
printf("Value is : %d\n", p);
return 0;
}
Example - Pointer Subtraction
#include <stdio.h>
int main()
{
int a[5] = {1,4,3,-8,0};
int *p = &a;
int *q = &a[3];
printf("p-q is : %d\n", p-q);
printf("q-p is : %d\n", q-p);
q=q-2;
printf("Value is : %d\n", *q);
printf("Value is : %d\n", q);
p=p+2;
printf("q-p is : %d\n", q-p);
q=q-2;
printf("Value is : %d\n", *q);
return 0;
}
Example – Pointer Increment/Decrement

#include <stdio.h>
int main()
{
int a[] = {4,6,-1,9,-1,18, 11};
int *p, *q;
p=a;
printf("%d \n", *p);
printf("%d %d %d \n", (*p)++, *p++, *++p);
q=p+3;
printf("%d\n", *q-3);
printf("%d\n", *--p +5);
printf("%d\n", *p + *q);
return 0;
}
Examples

#include<stdio.h>
void main()
{
const int a = 10;
const int *p = &a;
*p = 20;
printf(“%d”, a);
}
Void Pointer
• The void pointer in C is a pointer that is not associated with any data types.
• It points to some data location in the storage. This means that it points to the address of variables. It is also called
the general purpose pointer.
#include<stdio.h>
void main()
{
void *v;
int a=10;
float b = 10.32;
char ch = 'c';
v = &a;
printf(“%d\n”, *(int*)v);
v = &b;
printf("%f\n", *(float*)v);
v = &ch;
printf("%c\n", *(char*)v);
}
NULL Pointer
• A null pointer is a pointer that does not point to any memory location and hence does not hold the
address of any variables.
• Dereferencing a null pointer would crash the program.
#include <stdio.h>
int main()
{
// declaring null pointer
int* ptr = NULL;
// derefencing only if the pointer have any value
if (ptr == NULL) {
printf("Pointer does not point to anything");
}
else {
printf("Value pointed by pointer: %d", *ptr);
}
return 0;
}
Dangling Pointer

• A dangling pointer is a pointer that points to a memory location that has been
deallocated or is no longer valid.
• Dangling pointers can cause various problems in a program, including segmentation
faults, memory leaks, and unpredictable behavior.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=10;
printf("%d\n", *ptr);
free(ptr);
printf("%d\n", *ptr);
}
String
• Array of characters. Only char data type is allowed. Ends with null
character.
• When the compiler encounters a sequence of characters enclosed in
the double quotation marks, it appends a null character \0 at the end
by default.

char c[] = "c string";


Declare of String
• char s[5];

Here, we have declared a string of 5 characters.


char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = "abcde"; Here, we are trying to assign 6 characters (the last character is '\0') to a char array
having 5 characters.
Arrays and strings are second-class citizens in C; they do not support the assignment operator once it
is declared.
For example, char c[100]; c = "C programming"; --- Not Valid
Reading String
scanf(): function reads the sequence of characters until it encounters whitespace (space, newline, tab,
etc.).

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Scanf already points to the address of the first element in the string, which is why we don't need to use &.
To avoid:
gets() function is used. This function will print entire message including whitespaces.
Program
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
gets(name);
printf("Your name is %s.", name);
return 0;
}
Note:
Both scanf & gets has “Buffer overflow” issue. To avoid that, fgets() function is
used.
fgets()
Syntax: fgets(char *str, int n, FILE *stream)
char *str: a pointer to an array of characters where the read values will be stored
int n: maximum number of characters to be read
FILE *stream: pointer to the file stream from where the input is to be taken (it can be replaced
with stdin when taking input from the standard input ie through the console)
#include <stdio.h>
#define MAX 15
int main()
{
// defining buffer
char buf[MAX];
// using fgets to take input from stdin
fgets(buf, MAX, stdin);
printf("string is: %s\n", buf);
return 0;
puts()
puts() function automatically insert new line character and content will be printed in the next line.
Ex:
#include <stdio.h>
int main()
{
char name[50];
printf(“Enter name”);
scanf("%s",name);
printf("%10.4s", name);
printf("%10.4s", &name[2]);
puts(name);
puts(name);
return 0;
}
String Functions in C

• strcat() - string concatenation


• strlen() - length of a given string
• strcmp() - two strings as arguments and compares these two strings
lexicographically.
• strcpy - copy one string to another.
• strncpy() - is similar to strcpy() function, except that at most n bytes of src are
copied.
• strchr() - This function is used to find the first occurrence of a character in a string.
• strstr() - first occurrence of a substring in another string.
• strtok() - is used to split the string into small tokens based on a set of delimiter
characters.
strlen()
#include <stdio.h>
#include<string.h>
int main()
{
char name[30];
unsigned int count=0;
int i;
printf("Enter Name");
scanf("%s",name);
count=strlen(name);
/* while(name[i]!='\0')
{
count++;
i++;
}*/
puts(name);
printf("The length of the String is: %d", count);
}
strcat()
#include <stdio.h>
#include <string.h>
Syntax: char *strcat(char *destination, const char *source)
destination - destination string
int main () { source - source string
char str1[50], str2[50];
The strcat() function concatenates the destination string
//destination string and the source string, and the result is stored in the destination string.
strcpy(str1, “Hello VITians");

//source string
strcpy(str2, ", Good to see you");

//concatenating the string str2 to the string str1


strcat(str1, str2);

//displaying destination string


printf("String after concatenation: %s", str1);

return(0);
}
Without strcat()
#include<stdio.h>

void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
strcmp()
The strcmp() function is part of the standard C library (string.h). Its primary
purpose is to compare the characters of the two strings in sequence until it
finds a mismatch or until the end of the strings is reached (that is, the null
character '\0')
int strcmp(const char *s1, const char *s2);
• s1 denotes the first string to be compared.
• s2 denotes the second string to be compared.
then returns 0,1, or -1 as the result.
It compares the corresponding characters from both strings based on their
ASCII values, which are numeric codes that represent each character.
Program using strcmp function
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "apple";
char str2[] = "banana";

int result = strcmp(str1, str2);

if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("String 1 is less than string 2.\n");
} else {
printf("String 1 is greater than string 2.\n");
}

return 0;
Program without strcmp function
#include<stdio.h>
#include<string.h>
void main(void)
{
char str1[30],str2[30];
int ans,i, count=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
// ans = strcmp(str1,str2);
for(i=0;str1[i]!='\0'||str2[i]!='\0'; i++)
{
if (str1[i]!=str2[i])
{
count=1;
break;
}
}
if(count==0)
printf("String values are same");
else
printf("String values are not same");
}
strrev() function
#include <stdio.h>
#include<string.h>
void main()
{
char c[50],ch;
int i, len;
printf("Enter String:");
gets(c);
len=strlen(c);
// printf("%d",len);
for(i=0;i<len/2;i++)
{
ch=c[i];
c[i]=c[len-1-i];
c[len-1-i]=ch;

}
printf("%s",c);

}
Functions
• In c, we can divide a large program into the basic building blocks
known as function.
• The function contains the set of programming statements enclosed by
{}.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• In other words, we can say that the collection of functions creates a
program.
• The function is also known as procedure or subroutine in other
programming languages.
Functions

Advantage
• By using functions, we can avoid rewriting same logic/code again and
again in a program.
• We can call C functions any number of times in a program and from
any place in a program.
• We can track a large C program easily when it is divided into multiple
functions.
• Reusability is the main achievement of C functions.
Note: However, function calling is always a overhead in a C program.
Three Function Aspects
• Function declaration: A function must be declared globally in a c program to tell
the compiler about the function name, function parameters, and return type.
• Function call: Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
• Function definition: It contains the actual statements which are to be executed. It
is the most important aspect to which the control comes when the function is
called. Here, we must notice that only one value can be returned from the
function.
• Function declaration: return_type function_name (argument list);
• Function call: function_name (argument_list)
• Function definition: return_type function_name (argument list) {function body;}
Functions
• Function should be declared before its definition. This is recommendation but not necessary.
• If return type is not specified, by default compiler consider int data type.
Syntax: return type function name(set_of_inputs with their data types or arguments);
Ex:
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
int add = sum(10, 30);

printf("Sum is: %d", add);


return 0;
Types of Functions
• Two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C
header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

2. User-defined functions: are the functions which are created by the


C programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.
Return Value
• A C function may or may not return a value from the function. If you don't have to return any value from the function, use
void for the return type.
• Let's see a simple example of C function that doesn't return any value from the function.
• Example without return value:
void hello()
{
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int, long, char, etc.
The return type depends on the value to be returned from the function. Let's see a simple example of C function that returns
int value from the function. Example with return value:
int get()
{
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-point value
(e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.
float get()
{
return 10.2;
}
Type of functions
• Different aspects of function calling --- A function may or may not
accept any argument.
• It may or may not return any value. Based on these facts, There are
four different aspects of function calls.
• function without arguments and without return value
• function without arguments and with return value
• function with arguments and without return value
• function with arguments and with return value
Example for Function without argument and return value

#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("IET");
}
Example

#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Example for function without argument and
with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Example for function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Example for Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Call by Value
#include<stdio.h>
void set(int a)
{
a=0;
printf("In set function a %d\n",a);
}
int main()
{
int a=10;
printf("Before calling value of a is: %d\n", a);
set(a);
printf("After calling value of a is: %d\n", a);
return 0;
}
Note: Any value changes in calling function, will update locally i.e., will not update in the main
function.
Call by Reference
#include<stdio.h>
void set(int *a)
{
*a=0;
printf("In set function a %d\n",a);
}
int main()
{
int a=10;
printf("Before calling value of a is: %d\n", a);
set(&a);
printf("After calling value of a is: %d\n", a);
return 0;
}
Note: Changes made in call function will reflect in main function as well.

You might also like