SlideShare una empresa de Scribd logo
1 de 95
Descargar para leer sin conexión
Arrays,
Pointers
and
Functions
UNIT II
BY DR.T.P.LATCHOUMI
Arrays
An array is a collection of variables of the same type that are referenced by a common name. In C, all
arrays consist of contiguous memory locations.
The lowest address corresponds to the first element, and the highest address to the last element. Arrays
may have from one to several dimensions. A specific element in an array is accessed by an index.
One Dimensional Array
The general form of single-dimension array declaration is:
Type variable-name[size];
How to declare Array in C
int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Here, type declares the base type of the array, size defines how many elements the array will hold.
For example, the following declares as integer array named sample that is ten elements long:
int sample [10];
In C, all arrays have zero as the index of their first element. This declares an integer array that has ten
elements, sample [0] through sample [9]
Cont… To declare an array, you simply need to specify the data type of the array
elements, the variable name, and the array size. For example, if you want
to declare an integer array with four elements, you will use:
int a[4];
This statement allocates a contiguous block of memory for four integers
and initializes all the values to 0. This is how it is laid out in memory:
Array Initialization
The general form of array initialization is:
Type_specifier array_name[size1]…. [sizeN] = { value_list};
The value list is a comma_separated list of constants whose type is compatible with type_specifier.
Example 1
char str[9] = “I like C”;
this is same as writing:
char str[9] = {„I‟, „ „, „l‟, ‟i‟, ‟k‟, ‟e‟, ‟ „, ‟C‟, ‟0‟};
You can use the indexes to set or get specific values from the array. Here are a few examples:
a[0] = 10;
a[1] = 20;
a[2] = a[1] / a[0]; // a[2] will be set to 20/10 = 2
a[3] = a[1] - 2; // a[3] will be set to 20-2 = 18
After these changes, here is how the array will look like in memory:
Apart from the square brackets to indicate the index, array elements behave like normal
variables.
Example 2
#include <stdio.h>
int main() {
// dec lare an array of size 4
int a[4];
// storing integers in the array
a[0] = 10;
a[1] = 20;
a[2] = a[1] / a[0]; // a[2] will be set to 20/10 = 2
a[3] = a[1] - 2; // a[3] will be set to 20 -2 = 18
// printing the integers
printf("%d %d %d %d n", a[0], a[1], a[2], a[3]);
return 0;
}
Output
10 20 2 18
Example 3
Output
Enter the value of N 5
Enter 5 numbers (-ve, +ve and zero)
10 20 30 40 50
Input array elements 10 20 30 40 50
Sum of all numbers = 150
Average of all input numbers = 30
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array elements n");
for (i = 0; i < num; i++)
{
printf("%+3dn", array[i]);
}
/* Summation starts */
for (i = 0; i < num; i++)
{
total+=array[i];/* this means total=total+array[i]; */
}
average = total / num;
printf("n Sum of all numbers = %.2fn", total);
printf("n Average of all input numbers = %.2fn", average);
}
Two
dimensional
array
Example
// C program to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main() {
int temperature[CITY][WEEK];
// Using nested loop to store values in a 2d array
for (int i = 0; i < CITY; ++i) {
for (int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]); } }
printf("nDisplaying values: nn");
// Using nested loop to display vlues of a 2d array
for (int i = 0; i < CITY; ++i) {
for (int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d = %dn", i + 1, j + 1, temperature[i][j]); } }
return 0;
}
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
Multidimensio
nal array
//CProgramtostoreandprint12valuesenteredbytheuser
#include<stdio.h>
intmain() {
inttest[2][3][2];
printf("Enter12values: n");
for(inti=0;i<2;++i) {
for(intj=0;j<3;++j) {
for(intk=0;k<2;++k) {
scanf("%d",&test[i][j][k]); } } }
//Printingvalueswithproperindex.
printf(" nDisplayingvalues: n");
for(inti=0;i<2;++i) {
for(intj=0;j<3;++j) {
for(intk=0;k <2;++k) {
printf("test[%d][%d][%d]=%d n",i,j,k,test[i][j][k]); } } }
return0; }
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[ 0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
Strings
In C, In order to allow variable length strings the 0 character is
used to indicate the end of a string. A null is specified using „0‟
and is zero. Because of the null terminator, It is necessary to
declare character array to be one character longer than the
largest string that they are to hold. For example, to declare an
array str that can hold a 10 character string, we write:
char str[11];
this makes room for the null at the end of the string. A string
constant is a list of characters enclosed by double quotation
marks.
For example:
“hello, this is a test”
It is not necessary to manually add the null onto end of string
constants – the compiler does this automatically
Reading a string from the
keyboard
The easiest way to input a string from the keyboard is with the gets() library function. The general
form gets() is:
gets(array_name);
To read a string, call gets() with the name of the array, with out any index, as its arguments. Upon
return form gets() the array will hold the string input. The gets() function will continue to read
characters until you enter a carriage return. The header file used for gets() is stdio.h
Example
# include <stdio.h>
main()
{
char str[80];
printf (“ nEnter a string:”);
gets (str);
printf (“%s”, str);
}
the carriage return does not become part of the string instead a null terminator is placed at the
end.
Writing strings
The puts() functions writes its string argument to the screen followed by a newline. Its prototype is:
puts(string);
It recognizes the same back slash code as printf(), such as “t” for tab. As puts() can output a string of
characters – It cannot output numbers or do format conversions it required faster overhead than
printf(). Hence, puts() function is often used when it is important to have highly optimized code.
For example, to display “hello” on the screen:
puts(“hello”);
Array of strings
To create an array of strings, a two-dimensional character array is used with the size of the left-Index
determining the number of strings and the size of the right Index specifying the maximum length of
each string.
For example, to declare an array of 30 strings each having a max length of 80 characters.
char str_array[30][80];
To access an individual string is quite easy: you simply specify only the left Index
Example
/* to accept lines of text and redisplay them when a blank line is entered */
main()
{
int t, i;
char text [100][80];
for (t=0; t<100; t++)
{
printf (“%d Enter Text: “, t);
gets (text [t]);
if (! text [t][0]) /* quit on blank line */
break;
}
for (i=0; i<t; i++)
printf (“%s n”, text [i]);
}
Read & write
Strings in C
using Printf()
and Scanf()
functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];
printf("Enter your Nick name:");
/* I am reading the input string and storing it in nickname
* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);
/*Displaying String*/
printf("%s",nickname);
return 0;
}
Output:
Enter your Nick name:Negan
Negan
Read & Write
Strings in C
using gets() and
puts() functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];
/* Console display using puts */
puts("Enter your Nick name:");
/*Input using gets*/
gets(nickname);
puts(nickname);
return 0;
}
Output:
Enter your Nick name:Negan
Negan
Basic String Handling Functions
As string data type is not present. A string constant is a list of characters enclosed in double
quotes.
For example, “Hello”
C- supports a wide range of string manipulation functions,
1. Strlen()
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf( "Length of string str1: %d", strlen(str1));
return 0;
}
Output: Length of string str1: 13
It returns the length of the string
without including end character
(terminating char ‘0’).
Syntax:
size_t strlen(const char *str)
size_t represents unsigned short
2. strnlen()
Example
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Lengt h of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf( "Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10
It returns length of the string if it is
less than the value specified for
maxlen (maximum length)
otherwise it returns maxlen value.
Syntax:
size_t strnlen(const char *str,
size_t maxlen)
size_t represents unsigned short
3. strcmp()
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "Beginner sBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s 2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
string 1 and 2 are different
It compares the two strings and returns an
integer value. If both the strings are same
(equal) then this function would return 0
otherwise it may return a negative or positive
value based on the comparison.
int strcmp(const char *str1, const char *str2)
If string1 < string2 OR string1 is a substring of
string2 then it would result in a negative value.
If string1 > string2 then it would return positive
value.
If string1 == string2 then you would get 0(zero)
when you use this function for compare strings.
4. strncmp()
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are eq ual");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
string1 and string 2 are equal
It compares both the string till n
characters or in other words it
compares first n characters of
both the strings.
int strncmp(const char *str1,
const char *str2, size_t n)
size_t is for unassigned short
5. strcat()
Example
#include < stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Output string after concatenation: HelloWor ld
It concatenates two strings and
returns the concatenated string.
char *strcat(char *str1, char
*str2)
strncat()
#include <stdio.h>
#include <string.h>
int main ()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Concatenation using strncat: HelloWor
It concatenates n characters of
str2 to string str1. A terminator
char (‘0’) will always be
appended at the end of the
concatenated string.
char *strncat(char *str1, char
*str2, int n)
7. strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I‟m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: string 2: I‟m gonna copied into s1
It copies the string str2 into string
str1, including the end character
(terminator char ‘0’).
char *strcpy( char *str1, char
*str2)
8. strncpy()
#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I‟m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: string 2: I‟m
Case1: If length of str2 > n then it just
copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies
all the characters of str2 into str1 and
appends several terminator chars(‘0’) to
accumulate the length of str1 to make it
n.
char *strncpy( char *str1, char *str2,
size_t n)
size_t is unassigned short and n is a
number.
9. strchr()
#include <stdio.h>
#include <string.h>
int main()
{
char my str[30] = "I‟m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:
f function strchr
It searches string str for character
ch (you may be wondering that in
above definition I have given data
type of ch as int, don’t worry I didn’t
make any mistake it should be int
only. The thing is when we give any
character while using strchr then it
internally gets converted into integer
for better searching.
char *strchr(char *str, int ch)
10. strrchr()
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I‟m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:
function strchr
It is similar to the function strchr,
the only difference is that it
searches the string in reverse
order, now you would have
understood why we have extra r in
strrchr, yes you guessed it correct,
it is for reverse only.
char *strrchr(char *str, int ch)
11. strstr()
#include <stdio.h>
#include < string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:
Output string is: BeginnersBook.COM
You can also use this function in plac e of strchr as you can give single char also in place of
search_term string.
It is like strchr, except that it
searches for string srch_term
instead of a single char.
char *strstr(char *str, char
*srch_term)
User defined functions
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-
defined functions. For example: Suppose, you need to create a circle and color it depends upon
the radius and color. You can create two functions to solve this problem:
createCircle() function
color() function
Function prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain
function body.
A function prototype gives information to the compiler that the function may later be used in the program.
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2, ...);
In the above example, int addNumbers(int a, int b); is the function prototype which provides the following information to the compiler:
1. name of the function is addNumbers()
2. return type of the function is int
3. two arguments of type int are passed to the function
The function prototype is not needed if the user-defined function is defined before the main() function.
Calling a function
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call
functionName(argument1, argument2, ...);
In the above example, the function call is made using addNumbers(n1, n2); statement inside the
main() function.
Function definition
Function definition contains the block of code to perform a specific task. In our example, adding two
numbers and returning it.
Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
When a function is called, the control of the program is transferred to the function definition. And the
compiler starts executing the codes inside the body of a function.
Passing
arguments to a
function
In programming, argument refers
to the variable passed to the
function. In the above example,
two variables n1 and n2 are
passed during the function call.
The parameters a and b accepts
the passed arguments in the
function definition. These
arguments are called formal
parameters of the function.
Return
Statement
The return statement terminates the execution of a
function and returns a value to the calling function. The
program control is transferred to the calling function
after the return statement.
In the above example, the value of the result variable is
returned to the main function. The sum variable in the
main() function is assigned this value.
Syntax of return statement
return (expression);
For example,
return a;
return (a+b);
Example 1
Creating a user defined function
addition()
Example 2
#include <stdio.h>
/* function return type is void and it doesn't have parameters*/
void introduction()
{
printf("Hi n");
printf("My name is Cha itanya n");
printf("How are you?");
}
int main()
{
introduction();
return 0 ;
}
Output:
Hi
My name is Chaitanya
How are you?
Creating a void user defined
function that doesn’t return
anything
Types of user defined function
These 4 programs below check whether the integer entered by the user is a prime number or not.
The output of all these programs below is the same, and we have created a user-defined function
in each example. However, the approach we have taken in each example is different.
1. No argument and no return value
2. No argument and with return value
3. With argument and no return value
4. With argument and with return value
1. Function with no arguments
and no return value
Such functions can either be used to display information or they are completely dependent on
user inputs.
Function with no argument means the called function does not receive any data from calling
function and Function with no return value means calling function does not receive any data from
the called function. So there is no data transfer between calling and called function.
Example
#include<stdio.h>
void greatNum(); // function declaration
int main()
{
greatNum(); // funct ion call
return 0;
}
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that y ou want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf( "The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}
Output
Enter 2 numbers that you want to compare... 12 20
The great er number is: 20
2. Function with no arguments
and return value
As said earlier function with no arguments means called function does not receive any data from
calling function and function with one return value means one result will be sent back to the caller
from the function.
Example
#include<stdio.h>
int greatNum(); // function declaration
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum() // function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compa re...");
scanf( "%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}
Output
Enter 2 numbers that you want to compare...12 20
The greater number is: 20
3. Function with arguments and
no return values
Here function will accept data from the calling function as there are arguments, however, since
there is no return type nothing will be returned to the calling program. So it’s a one-way type
communication
Example
#include<stdio.h>
void greatNum(int a, int b); // function declaration
int main()
{
int i, j;
printf ("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}
void greatNum(int x, int y) // functio n definition
{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}
Output
Enter 2 numbers that you want to compare...12 20
The greater number is:20
4. Function with arguments and
with return value
Function with arguments and one return value means both the calling function and called function
will receive data from each other. It’s like a dual communication.
Example
#include<stdio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // fun ction call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}
Output
Enter 2 numbers that you want to compare...12 20
The greater number is:20
Function with multiple return
values
So far we have used functions that return only one value because function normally returns a
single value.
However, we can use functions which can return multiple values by using input parameters and
output parameters.
Those parameters which are used to receive data are called input parameters and the parameters
used to send data are called output parameters. This is achieved by using address operator(&)
and indirection operator(*). Moreover, following example will clarify this concept.
Example
#include <stdio.h>
void area_volume(int l, int *a, int *v); //function prototype
int main()
{
int l,a,v;
printf("Enter the side of square :");
scanf("%d",&l);
area_volume(l,&a,&v); //func tion call
printf("Area = %d n Volume = %d",a,v);
return 0;
}
void are a_volume(int l, int *a, int *v)
{
*a = l*l;
*v = l*l*l;
}
Output
Enter the side of square: 6
Area = 36
Nesting of
Functions
If function2() also has a call for function1() inside it, then in
that case, it will lead to an infinite nesting. They will keep
calling each other and the program will never terminate.
Not able to understand? Lets consider that inside the main()
function, function1() is called and its execution starts, then
inside function1(), we have a call for function2(), so the
control of program will go to the function2().
But as function2() also has a call to function1() in its body,
it will call function1(), which will again call function2(),
and this will go on for infinite times, until you forcefully
exit from program execution.
C language also allows nesting of functions i.e to
use/call one function inside another function's body. We
must be careful while using nested functions, because it
may lead to infinite nesting.
function1()
{
// function1 body here
function2();
// function1 body here
}
Recursion
A function that calls itself is known as a recursive function. And this technique is known
as recursion.
How recursion works?
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
How it works?
Example 1
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n -1);
else
return n;
}
Output
Enter a positive integer:3
sum = 6
Cont…
Advantages and Disadvantages of
Recursion
Recursion makes program elegant. However, if performance is vital, use loops instead as
recursion is usually much slower.
Recursion is an important concept. It is frequently used in data structure and algorithms. For
example, it is common to use recursion in problems such as tree traversal.
Example 1
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d n", i, factorial(i));
return 0;
}
Output
Factorial of 12 is 479001600
Example 2
#includ e <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i -1) + fibonacci(i -2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d tn", fibonacci(i));
}
return 0;
}
Output
0
1
1
2
3
5
8
13
21
34
Pointers
Look at some of the valid pointer declarations
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether
integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address.
The only difference between pointers of different data
types is the data type of the variable or constant that the
pointer points to.
A pointer is a variable whose value
is the address of another variable,
i.e., direct address of the memory
location. Like any variable or
constant, you must declare a pointer
before using it to store any variable
address.
The general form of a pointer
variable declaration is −
type *var-name;
Initialize a
pointer
After declaring a pointer, we initialize it like standard
variables with a variable address. If pointers in C
programming are not uninitialized and used in the
program, the results are unpredictable and potentially
disastrous.
To get the address of a variable, we use the ampersand
(&)operator, placed before the name of a variable whose
address we need. Pointer initialization is done with the
following syntax.
Pointer Syntax
pointer = &variable;
Example
#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is :%xn",p); //accessing the address
printf("Value stored in a variable p is:%d n",*p); //accessing the value
return 0;
}
Output:
Address stored in a variable p is:60ff08
Value stored in a variable p is:10
Changing
Value Pointed
by Pointers
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf( "Address of c: %p n", &c);
printf("Value of c: %d nn", c); // 22
pc = &c;
printf("Address of pointer pc: %p n", pc);
printf("Content of pointer pc: %d nn", *pc); // 22
c = 11;
printf("Address of pointer pc: %p n", pc);
printf("Content of pointer pc: %d nn", *pc); // 11
*pc = 2;
printf("Ad dress of c: %p n", &c);
printf("Value of c: %d nn", c); // 2
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
Example 2
#include <stdio.h >
int main()
{
// A normal integer variable
int Var = 10;
// A pointer variable that holds address of var.
int *ptr = &Var;
// This line prints value at address stored in ptr.
// Value stored is value of variable "var"
printf("Value of Var = %d n", *ptr);
// The output of this line may be different in different
// runs even on same machine.
printf("Address of Var = %p n", ptr);
// We can also use ptr as lvalue (Left hand
// side of assignment)
*ptr = 20; // Value at address is now 20
// This prints 20
printf("After doing *ptr = 20, *ptr is %d n", *ptr);
return 0;
}
Output :
Value of Var = 10
Address of Var = 0x7fffa057dd4
After doing *ptr = 20, *ptr is 20
Pointer Expressions and Pointer
Arithmetic
A limited set of arithmetic operations can be performed on pointers. A pointer may be:
• incremented ( ++ )
• decremented ( — )
• an integer may be added to a pointer ( + or += )
• an integer may be subtracted from a pointer ( – or -= )
Pointer arithmetic is meaningless unless performed on an array.
Note : Pointers contain addresses. Adding two addresses makes no sense, because there is no idea
what it would point to. Subtracting two addresses lets you compute the offset between these two
addresses.
Example
#include < stdio.h>
int main()
{
// Declare an array
int v[3] = {10, 100, 200};
// Declare pointer variable
int *ptr;
// Assign the address of v[0] to ptr
ptr = v;
for (int i = 0; i < 3; i++)
{
printf("Value of *ptr = %d n", *ptr);
printf("Value of ptr = %p nn", ptr);
// Increment pointer ptr by 1
ptr++;
}
}
Output:
Value of *ptr = 10
Value of ptr = 0x7ffcae30c710
Value of *ptr = 100
Value of ptr = 0x7ffcae30c714
Value of *ptr = 200
Value of ptr = 0x7ffcae30c718
Key Points to Remember About
Pointers in C
• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).
Example
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output
50
Types of
Pointers in C
#include <stdio.h>
int main()
{
int *p = NULL; //null po inter
printf(“The value inside variable p is: n%x”,p);
return 0;
}
Output:
The value inside variable p is:
0
Null Pointer
We can create a null pointer by
assigning null value during the
pointer declaration. This method
is useful when you do not have
any address assigned to the
pointer. A null pointer always
contains value 0.
Void Pointer
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%dn",sizeof(p));
return 0;
}
Output:
The size of pointer is:4
In C programming, a void pointer
is also called as a generic pointer.
It does not have any standard
data type. A void pointer is created
by using the keyword void. It can
be used to store an address of any
variable.
Wild pointer
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("n%d",*p);
return 0;
}
Output
timeout: the monitored command dumped core
sh: line 1: 95298 Segmentation fault timeout 10s main
A pointer is said to be a wild pointer
if it is not being initialized to
anything. These types of C pointers
are not efficient because they may
point to some unknown memory
location which may cause problems
in our program and it may lead to
crashing of the program. One should
always be careful while working with
wild pointers.
C Pointers &
Arrays with
Examples
#include <stdio.h>
int main()
{
int a[5]={1,2,3,4,5}; //array initialization
int *p; / /pointer declaration
/*the pt r points to the first element of the array*/
p=a; /*We can also type simply ptr==&a[0] */
printf("Printing the array elements using pointer n");
for(int i=0;i<5;i++) //loop for traversing array elements
{
printf(" n%x",*p); //printing array elements
p++; //incrementing to the next element, you can also write p=p+1
}
return 0;
}
Output
1
2
3
4
5
Pointers and
Multidimensio
nal Arrays
Consider pointer notation for the
two-dimensional numeric arrays.
consider the following declaration
int nums[2][3] = { {16, 18, 20},
{25, 26, 27} };
In general, nums[i][j] is equivalent
to *(*(nums+i)+j)
C Pointers and
Strings
A string is an array of char objects,
ending with a null character ' 0'.
We can manipulate strings using
pointers. This pointer in C example
explains this section
Advantages of Pointers in C
• Pointers are useful for accessing memory locations.
• Pointers provide an efficient way for accessing the elements of an array structure.
• Pointers are used for dynamic memory allocation as well as deallocation.
• Pointers are used to form complex data structures such as linked list, graph, tree, etc.
Disadvantages of Pointers in C
• Pointers are a little complex to understand.
• Pointers can lead to various errors such as segmentation faults or can access a memory
location which is not required at all.
• If an incorrect value is provided to a pointer, it may cause memory corruption.
• Pointers are also responsible for memory leakage.
• Pointers are comparatively slower than that of the variables.
• Programmers find it very difficult to work with the pointers; therefore it is programmer's
responsibility to manipulate a pointer carefully.
Pointer to Pointer in C
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that contains the actual
value as shown below.
Example
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d n", var );
printf("Value available at *ptr = %d n", *ptr );
printf("Value available at **pptr = %d n", **pptr);
return 0;
}
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Dynamic
Memory
Allocation in C
Dynamic Memory Allocation is manual
allocation and freeing of memory according to
your programming needs. Dynamic memory is
managed and served with pointers that point to
the newly allocated memory space in an area
which we call the heap.
Now you can create and destroy an array of
elements dynamically at runtime without any
problems. To sum up, the automatic memory
management uses the stack, and the C
Dynamic Memory Allocation uses the heap.
The <stdlib.h> library has functions responsible
for Dynamic Memory Management.
C malloc()
Function
The C malloc() function stands for memory
allocation. It is a function which is used to
allocate a block of memory dynamically. It
reserves memory space of specified size
and returns the null pointer pointing to the
memory location. The pointer returned is
usually of type void. It means that we can
assign C malloc() function to any pointer.
Syntax of malloc() Function:
ptr = (cast_type *) malloc (byte_size);
Example
#include <stdlib.h>
int main(){
int *ptr;
ptr = malloc(15 * sizeof(* ptr)); /* a block of 15 integers */
if (ptr != NULL) {
*(ptr + 5) = 480; /* assign 480 to sixth integer */
printf("Value of the 6th integer is %d",*(ptr + 5));
}
}
Output:
Value of the 6th integer is 480
C calloc()
Function
The C calloc() function stands for
contiguous allocation. This function is
used to allocate multiple blocks of
memory. It is a dynamic memory
allocation function which is used to
allocate the memory to complex data
structures such as arrays and structures.
Syntax of calloc() Function:
ptr = (cast_type *) calloc (n, size);
Example
#include <stdio.h>
int main() {
int i, * ptr, sum = 0;
ptr = calloc(10, sizeof(int));
if (pt r == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Building and calculating the sequence sum of the first 10 terms  n ");
for (i = 0; i < 10; ++i) { * (ptr + i) = i;
sum += * (ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Result:
Building and calculating the sequence sum of the first 10 terms
Sum = 45
C free() method
“free” method in C is used to dynamically de-
allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated
on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by
freeing it.
Syntax:
free(ptr);
Example
C realloc()
method
“realloc” or “re-allocation” method in C is used to dynamically
change the memory allocation of a previously allocated memory.
In other words, if the memory previously allocated with the help
of malloc or calloc is insufficient, realloc can be used to
dynamically re-allocate memory. re-allocation of memory
maintains the already present value and new blocks will be
initialized with default garbage value.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
Example
#include <stdio.h>
#includ e <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u n",pt r + i);
printf(" nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: ");
for(i = 0; i < n2; ++i)
printf("%u n", ptr + i);
free(ptr);
return 0;
}
When you run the program, the output will be:
Enter size: 2
Addresses of previously allocated memory:26855472
26855476
Enter the new size: 4
Addresses of newly allocated memory:26855472
26855476
26855480
26855484
Difference between static and
dynamic memory allocation
Difference Between malloc() and
calloc() Functions in C:
Array of
pointers
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d n", i, *ptr[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Pointer to an
Array in C
#include <stdio.h>
int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
/* output each array element's value */
printf( "Array values using pointern");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %fn", i, *(p + i) );
}
printf( "Array values using balance as addressn");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %fn", i, *(balance + i) );
}
return 0;
}
Array values using pointer
*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000
Pointers and functions
In C programming, it is also possible to pass addresses as arguments to functions.
To accept these addresses in the function definition, we can use pointers. It's because pointers
are used to store addresses.
Pass
Addresses to
Functions
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %dn", num1);
printf("num2 = %d", num2);
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
When you run the program, the
output will be:
num1 = 10
num2 = 5
Passing
Pointers to
Functions
#include <stdio.h>
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
Output
11
Function
Pointer in C
#include <stdio.h>
// A n ormal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equiva lent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}
Output:
Value of a is 10
Thank You

Más contenido relacionado

La actualidad más candente

Character Array and String
Character Array and StringCharacter Array and String
Character Array and StringTasnima Hamid
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsRai University
 
Functions torage class and array and strings-
Functions torage class and array and strings-Functions torage class and array and strings-
Functions torage class and array and strings-aneebkmct
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsRai University
 
Mcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and stringsMcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and stringsRai University
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and stringsRai University
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++Vikash Dhal
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick referenceArduino Aficionado
 

La actualidad más candente (20)

Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Strings
StringsStrings
Strings
 
String in c
String in cString in c
String in c
 
strings
stringsstrings
strings
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and strings
 
Tut1
Tut1Tut1
Tut1
 
Functions torage class and array and strings-
Functions torage class and array and strings-Functions torage class and array and strings-
Functions torage class and array and strings-
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and strings
 
Mcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and stringsMcai pic u 4 function, storage class and array and strings
Mcai pic u 4 function, storage class and array and strings
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
 
Strings
StringsStrings
Strings
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
C++ string
C++ stringC++ string
C++ string
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
 
The string class
The string classThe string class
The string class
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 

Similar a Unit 2

Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsJamesChristianGadian
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...AntareepMajumder
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx8759000398
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functionsSwarup Boro
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptxFolkAdonis
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programmingnmahi96
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxrohinitalekar1
 

Similar a Unit 2 (20)

Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
String notes
String notesString notes
String notes
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Array &strings
Array &stringsArray &strings
Array &strings
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
02 arrays
02 arrays02 arrays
02 arrays
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 

Más de TPLatchoumi (9)

Unit 3
Unit 3Unit 3
Unit 3
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Unit i
Unit iUnit i
Unit i
 
Unit ii
Unit iiUnit ii
Unit ii
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit v
Unit vUnit v
Unit v
 
Unit iv
Unit ivUnit iv
Unit iv
 
Coa
Coa Coa
Coa
 
17 cs002
17 cs00217 cs002
17 cs002
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 

Último (20)

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 

Unit 2

  • 2. Arrays An array is a collection of variables of the same type that are referenced by a common name. In C, all arrays consist of contiguous memory locations. The lowest address corresponds to the first element, and the highest address to the last element. Arrays may have from one to several dimensions. A specific element in an array is accessed by an index. One Dimensional Array The general form of single-dimension array declaration is: Type variable-name[size];
  • 3. How to declare Array in C int num[35]; /* An integer array of 35 elements */ char ch[10]; /* An array of characters for 10 elements */ Here, type declares the base type of the array, size defines how many elements the array will hold. For example, the following declares as integer array named sample that is ten elements long: int sample [10]; In C, all arrays have zero as the index of their first element. This declares an integer array that has ten elements, sample [0] through sample [9]
  • 4. Cont… To declare an array, you simply need to specify the data type of the array elements, the variable name, and the array size. For example, if you want to declare an integer array with four elements, you will use: int a[4]; This statement allocates a contiguous block of memory for four integers and initializes all the values to 0. This is how it is laid out in memory:
  • 5. Array Initialization The general form of array initialization is: Type_specifier array_name[size1]…. [sizeN] = { value_list}; The value list is a comma_separated list of constants whose type is compatible with type_specifier.
  • 6. Example 1 char str[9] = “I like C”; this is same as writing: char str[9] = {„I‟, „ „, „l‟, ‟i‟, ‟k‟, ‟e‟, ‟ „, ‟C‟, ‟0‟}; You can use the indexes to set or get specific values from the array. Here are a few examples: a[0] = 10; a[1] = 20; a[2] = a[1] / a[0]; // a[2] will be set to 20/10 = 2 a[3] = a[1] - 2; // a[3] will be set to 20-2 = 18 After these changes, here is how the array will look like in memory: Apart from the square brackets to indicate the index, array elements behave like normal variables.
  • 7. Example 2 #include <stdio.h> int main() { // dec lare an array of size 4 int a[4]; // storing integers in the array a[0] = 10; a[1] = 20; a[2] = a[1] / a[0]; // a[2] will be set to 20/10 = 2 a[3] = a[1] - 2; // a[3] will be set to 20 -2 = 18 // printing the integers printf("%d %d %d %d n", a[0], a[1], a[2], a[3]); return 0; } Output 10 20 2 18
  • 8. Example 3 Output Enter the value of N 5 Enter 5 numbers (-ve, +ve and zero) 10 20 30 40 50 Input array elements 10 20 30 40 50 Sum of all numbers = 150 Average of all input numbers = 30 for (i = 0; i < num; i++) { scanf("%d", &array[i]); } printf("Input array elements n"); for (i = 0; i < num; i++) { printf("%+3dn", array[i]); } /* Summation starts */ for (i = 0; i < num; i++) { total+=array[i];/* this means total=total+array[i]; */ } average = total / num; printf("n Sum of all numbers = %.2fn", total); printf("n Average of all input numbers = %.2fn", average); }
  • 10. Example // C program to store temperature of two cities of a week and display it. #include <stdio.h> const int CITY = 2; const int WEEK = 7; int main() { int temperature[CITY][WEEK]; // Using nested loop to store values in a 2d array for (int i = 0; i < CITY; ++i) { for (int j = 0; j < WEEK; ++j) { printf("City %d, Day %d: ", i + 1, j + 1); scanf("%d", &temperature[i][j]); } } printf("nDisplaying values: nn"); // Using nested loop to display vlues of a 2d array for (int i = 0; i < CITY; ++i) { for (int j = 0; j < WEEK; ++j) { printf("City %d, Day %d = %dn", i + 1, j + 1, temperature[i][j]); } } return 0; } Output City 1, Day 1: 33 City 1, Day 2: 34 City 1, Day 3: 35 City 1, Day 4: 33 City 1, Day 5: 32 City 1, Day 6: 31 City 1, Day 7: 30 City 2, Day 1: 23 City 2, Day 2: 22 City 2, Day 3: 21 City 2, Day 4: 24 City 2, Day 5: 22 City 2, Day 6: 25 City 2, Day 7: 26 Displaying values: City 1, Day 1 = 33 City 1, Day 2 = 34 City 1, Day 3 = 35 City 1, Day 4 = 33 City 1, Day 5 = 32 City 1, Day 6 = 31 City 1, Day 7 = 30 City 2, Day 1 = 23
  • 11. Multidimensio nal array //CProgramtostoreandprint12valuesenteredbytheuser #include<stdio.h> intmain() { inttest[2][3][2]; printf("Enter12values: n"); for(inti=0;i<2;++i) { for(intj=0;j<3;++j) { for(intk=0;k<2;++k) { scanf("%d",&test[i][j][k]); } } } //Printingvalueswithproperindex. printf(" nDisplayingvalues: n"); for(inti=0;i<2;++i) { for(intj=0;j<3;++j) { for(intk=0;k <2;++k) { printf("test[%d][%d][%d]=%d n",i,j,k,test[i][j][k]); } } } return0; } Enter 12 values: 1 2 3 4 5 6 7 8 9 10 11 12 Displaying Values: test[0][0][0] = 1 test[0][0][1] = 2 test[0][1][0] = 3 test[ 0][1][1] = 4 test[0][2][0] = 5 test[0][2][1] = 6 test[1][0][0] = 7 test[1][0][1] = 8 test[1][1][0] = 9 test[1][1][1] = 10
  • 12. Strings In C, In order to allow variable length strings the 0 character is used to indicate the end of a string. A null is specified using „0‟ and is zero. Because of the null terminator, It is necessary to declare character array to be one character longer than the largest string that they are to hold. For example, to declare an array str that can hold a 10 character string, we write: char str[11]; this makes room for the null at the end of the string. A string constant is a list of characters enclosed by double quotation marks. For example: “hello, this is a test” It is not necessary to manually add the null onto end of string constants – the compiler does this automatically
  • 13. Reading a string from the keyboard The easiest way to input a string from the keyboard is with the gets() library function. The general form gets() is: gets(array_name); To read a string, call gets() with the name of the array, with out any index, as its arguments. Upon return form gets() the array will hold the string input. The gets() function will continue to read characters until you enter a carriage return. The header file used for gets() is stdio.h
  • 14. Example # include <stdio.h> main() { char str[80]; printf (“ nEnter a string:”); gets (str); printf (“%s”, str); } the carriage return does not become part of the string instead a null terminator is placed at the end.
  • 15. Writing strings The puts() functions writes its string argument to the screen followed by a newline. Its prototype is: puts(string); It recognizes the same back slash code as printf(), such as “t” for tab. As puts() can output a string of characters – It cannot output numbers or do format conversions it required faster overhead than printf(). Hence, puts() function is often used when it is important to have highly optimized code. For example, to display “hello” on the screen: puts(“hello”);
  • 16. Array of strings To create an array of strings, a two-dimensional character array is used with the size of the left-Index determining the number of strings and the size of the right Index specifying the maximum length of each string. For example, to declare an array of 30 strings each having a max length of 80 characters. char str_array[30][80]; To access an individual string is quite easy: you simply specify only the left Index
  • 17. Example /* to accept lines of text and redisplay them when a blank line is entered */ main() { int t, i; char text [100][80]; for (t=0; t<100; t++) { printf (“%d Enter Text: “, t); gets (text [t]); if (! text [t][0]) /* quit on blank line */ break; } for (i=0; i<t; i++) printf (“%s n”, text [i]); }
  • 18. Read & write Strings in C using Printf() and Scanf() functions #include <stdio.h> #include <string.h> int main() { /* String Declaration*/ char nickname[20]; printf("Enter your Nick name:"); /* I am reading the input string and storing it in nickname * Array name alone works as a base address of array so * we can use nickname instead of &nickname here */ scanf("%s", nickname); /*Displaying String*/ printf("%s",nickname); return 0; } Output: Enter your Nick name:Negan Negan
  • 19. Read & Write Strings in C using gets() and puts() functions #include <stdio.h> #include <string.h> int main() { /* String Declaration*/ char nickname[20]; /* Console display using puts */ puts("Enter your Nick name:"); /*Input using gets*/ gets(nickname); puts(nickname); return 0; } Output: Enter your Nick name:Negan Negan
  • 20. Basic String Handling Functions As string data type is not present. A string constant is a list of characters enclosed in double quotes. For example, “Hello” C- supports a wide range of string manipulation functions,
  • 21. 1. Strlen() #include <stdio.h> #include <string.h> int main() { char str1[20] = "BeginnersBook"; printf( "Length of string str1: %d", strlen(str1)); return 0; } Output: Length of string str1: 13 It returns the length of the string without including end character (terminating char ‘0’). Syntax: size_t strlen(const char *str) size_t represents unsigned short
  • 22. 2. strnlen() Example #include <stdio.h> #include <string.h> int main() { char str1[20] = "BeginnersBook"; printf("Lengt h of string str1 when maxlen is 30: %d", strnlen(str1, 30)); printf( "Length of string str1 when maxlen is 10: %d", strnlen(str1, 10)); return 0; } Output: Length of string str1 when maxlen is 30: 13 Length of string str1 when maxlen is 10: 10 It returns length of the string if it is less than the value specified for maxlen (maximum length) otherwise it returns maxlen value. Syntax: size_t strnlen(const char *str, size_t maxlen) size_t represents unsigned short
  • 23. 3. strcmp() #include <stdio.h> #include <string.h> int main() { char s1[20] = "Beginner sBook"; char s2[20] = "BeginnersBook.COM"; if (strcmp(s1, s 2) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; } Output: string 1 and 2 are different It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison. int strcmp(const char *str1, const char *str2) If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
  • 24. 4. strncmp() #include <stdio.h> #include <string.h> int main() { char s1[20] = "BeginnersBook"; char s2[20] = "BeginnersBook.COM"; /* below it is comparing first 8 characters of s1 and s2*/ if (strncmp(s1, s2, 8) ==0) { printf("string 1 and string 2 are eq ual"); }else { printf("string 1 and 2 are different"); } return 0; } Output: string1 and string 2 are equal It compares both the string till n characters or in other words it compares first n characters of both the strings. int strncmp(const char *str1, const char *str2, size_t n) size_t is for unassigned short
  • 25. 5. strcat() Example #include < stdio.h> #include <string.h> int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); return 0; } Output: Output string after concatenation: HelloWor ld It concatenates two strings and returns the concatenated string. char *strcat(char *str1, char *str2)
  • 26. strncat() #include <stdio.h> #include <string.h> int main () { char s1[10] = "Hello"; char s2[10] = "World"; strncat(s1,s2, 3); printf("Concatenation using strncat: %s", s1); return 0; } Output: Concatenation using strncat: HelloWor It concatenates n characters of str2 to string str1. A terminator char (‘0’) will always be appended at the end of the concatenated string. char *strncat(char *str1, char *str2, int n)
  • 27. 7. strcpy() #include <stdio.h> #include <string.h> int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : I‟m gonna copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; } Output: String s1 is: string 2: I‟m gonna copied into s1 It copies the string str2 into string str1, including the end character (terminator char ‘0’). char *strcpy( char *str1, char *str2)
  • 28. 8. strncpy() #include <stdio.h> #include <string.h> int main() { char first[30] = "string 1"; char second[30] = "string 2: I‟m using strncpy now"; /* this function has copied first 10 chars of s2 into s1*/ strncpy(s1,s2, 12); printf("String s1 is: %s", s1); return 0; } Output: String s1 is: string 2: I‟m Case1: If length of str2 > n then it just copies first n characters of str2 into str1. Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several terminator chars(‘0’) to accumulate the length of str1 to make it n. char *strncpy( char *str1, char *str2, size_t n) size_t is unassigned short and n is a number.
  • 29. 9. strchr() #include <stdio.h> #include <string.h> int main() { char my str[30] = "I‟m an example of function strchr"; printf ("%s", strchr(mystr, 'f')); return 0; } Output: f function strchr It searches string str for character ch (you may be wondering that in above definition I have given data type of ch as int, don’t worry I didn’t make any mistake it should be int only. The thing is when we give any character while using strchr then it internally gets converted into integer for better searching. char *strchr(char *str, int ch)
  • 30. 10. strrchr() #include <stdio.h> #include <string.h> int main() { char mystr[30] = "I‟m an example of function strchr"; printf ("%s", strrchr(mystr, 'f')); return 0; } Output: function strchr It is similar to the function strchr, the only difference is that it searches the string in reverse order, now you would have understood why we have extra r in strrchr, yes you guessed it correct, it is for reverse only. char *strrchr(char *str, int ch)
  • 31. 11. strstr() #include <stdio.h> #include < string.h> int main() { char inputstr[70] = "String Function in C at BeginnersBook.COM"; printf ("Output string is: %s", strstr(inputstr, 'Begi')); return 0; } Output: Output string is: BeginnersBook.COM You can also use this function in plac e of strchr as you can give single char also in place of search_term string. It is like strchr, except that it searches for string srch_term instead of a single char. char *strstr(char *str, char *srch_term)
  • 32. User defined functions A function is a block of code that performs a specific task. C allows you to define functions according to your need. These functions are known as user- defined functions. For example: Suppose, you need to create a circle and color it depends upon the radius and color. You can create two functions to solve this problem: createCircle() function color() function
  • 33. Function prototype A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program. Syntax of function prototype returnType functionName(type1 argument1, type2 argument2, ...); In the above example, int addNumbers(int a, int b); is the function prototype which provides the following information to the compiler: 1. name of the function is addNumbers() 2. return type of the function is int 3. two arguments of type int are passed to the function The function prototype is not needed if the user-defined function is defined before the main() function.
  • 34. Calling a function Control of the program is transferred to the user-defined function by calling it. Syntax of function call functionName(argument1, argument2, ...); In the above example, the function call is made using addNumbers(n1, n2); statement inside the main() function.
  • 35. Function definition Function definition contains the block of code to perform a specific task. In our example, adding two numbers and returning it. Syntax of function definition returnType functionName(type1 argument1, type2 argument2, ...) { //body of the function } When a function is called, the control of the program is transferred to the function definition. And the compiler starts executing the codes inside the body of a function.
  • 36. Passing arguments to a function In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during the function call. The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function.
  • 37. Return Statement The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling function after the return statement. In the above example, the value of the result variable is returned to the main function. The sum variable in the main() function is assigned this value. Syntax of return statement return (expression); For example, return a; return (a+b);
  • 38. Example 1 Creating a user defined function addition()
  • 39. Example 2 #include <stdio.h> /* function return type is void and it doesn't have parameters*/ void introduction() { printf("Hi n"); printf("My name is Cha itanya n"); printf("How are you?"); } int main() { introduction(); return 0 ; } Output: Hi My name is Chaitanya How are you? Creating a void user defined function that doesn’t return anything
  • 40. Types of user defined function These 4 programs below check whether the integer entered by the user is a prime number or not. The output of all these programs below is the same, and we have created a user-defined function in each example. However, the approach we have taken in each example is different. 1. No argument and no return value 2. No argument and with return value 3. With argument and no return value 4. With argument and with return value
  • 41. 1. Function with no arguments and no return value Such functions can either be used to display information or they are completely dependent on user inputs. Function with no argument means the called function does not receive any data from calling function and Function with no return value means calling function does not receive any data from the called function. So there is no data transfer between calling and called function.
  • 42. Example #include<stdio.h> void greatNum(); // function declaration int main() { greatNum(); // funct ion call return 0; } void greatNum() // function definition { int i, j; printf("Enter 2 numbers that y ou want to compare..."); scanf("%d%d", &i, &j); if(i > j) { printf( "The greater number is: %d", i); } else { printf("The greater number is: %d", j); } } Output Enter 2 numbers that you want to compare... 12 20 The great er number is: 20
  • 43. 2. Function with no arguments and return value As said earlier function with no arguments means called function does not receive any data from calling function and function with one return value means one result will be sent back to the caller from the function.
  • 44. Example #include<stdio.h> int greatNum(); // function declaration int main() { int result; result = greatNum(); // function call printf("The greater number is: %d", result); return 0; } int greatNum() // function definition { int i, j, greaterNum; printf("Enter 2 numbers that you want to compa re..."); scanf( "%d%d", &i, &j); if(i > j) { greaterNum = i; } else { greaterNum = j; } // returning the result return greaterNum; } Output Enter 2 numbers that you want to compare...12 20 The greater number is: 20
  • 45. 3. Function with arguments and no return values Here function will accept data from the calling function as there are arguments, however, since there is no return type nothing will be returned to the calling program. So it’s a one-way type communication
  • 46. Example #include<stdio.h> void greatNum(int a, int b); // function declaration int main() { int i, j; printf ("Enter 2 numbers that you want to compare..."); scanf("%d%d", &i, &j); greatNum(i, j); // function call return 0; } void greatNum(int x, int y) // functio n definition { if(x > y) { printf("The greater number is: %d", x); } else { printf("The greater number is: %d", y); } } Output Enter 2 numbers that you want to compare...12 20 The greater number is:20
  • 47. 4. Function with arguments and with return value Function with arguments and one return value means both the calling function and called function will receive data from each other. It’s like a dual communication.
  • 48. Example #include<stdio.h> int greatNum(int a, int b); // function declaration int main() { int i, j, result; printf("Enter 2 numbers that you want to compare..."); scanf("%d%d", &i, &j); result = greatNum(i, j); // fun ction call printf("The greater number is: %d", result); return 0; } int greatNum(int x, int y) // function definition { if(x > y) { return x; } else { return y; } } Output Enter 2 numbers that you want to compare...12 20 The greater number is:20
  • 49. Function with multiple return values So far we have used functions that return only one value because function normally returns a single value. However, we can use functions which can return multiple values by using input parameters and output parameters. Those parameters which are used to receive data are called input parameters and the parameters used to send data are called output parameters. This is achieved by using address operator(&) and indirection operator(*). Moreover, following example will clarify this concept.
  • 50. Example #include <stdio.h> void area_volume(int l, int *a, int *v); //function prototype int main() { int l,a,v; printf("Enter the side of square :"); scanf("%d",&l); area_volume(l,&a,&v); //func tion call printf("Area = %d n Volume = %d",a,v); return 0; } void are a_volume(int l, int *a, int *v) { *a = l*l; *v = l*l*l; } Output Enter the side of square: 6 Area = 36
  • 51. Nesting of Functions If function2() also has a call for function1() inside it, then in that case, it will lead to an infinite nesting. They will keep calling each other and the program will never terminate. Not able to understand? Lets consider that inside the main() function, function1() is called and its execution starts, then inside function1(), we have a call for function2(), so the control of program will go to the function2(). But as function2() also has a call to function1() in its body, it will call function1(), which will again call function2(), and this will go on for infinite times, until you forcefully exit from program execution. C language also allows nesting of functions i.e to use/call one function inside another function's body. We must be careful while using nested functions, because it may lead to infinite nesting. function1() { // function1 body here function2(); // function1 body here }
  • 52. Recursion A function that calls itself is known as a recursive function. And this technique is known as recursion. How recursion works? void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... }
  • 54. Example 1 #include <stdio.h> int sum(int n); int main() { int number, result; printf("Enter a positive integer: "); scanf("%d", &number); result = sum(number); printf("sum = %d", result); return 0; } int sum(int n) { if (n != 0) // sum() function calls itself return n + sum(n -1); else return n; } Output Enter a positive integer:3 sum = 6
  • 56. Advantages and Disadvantages of Recursion Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is usually much slower. Recursion is an important concept. It is frequently used in data structure and algorithms. For example, it is common to use recursion in problems such as tree traversal.
  • 57. Example 1 #include <stdio.h> unsigned long long int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %d n", i, factorial(i)); return 0; } Output Factorial of 12 is 479001600
  • 58. Example 2 #includ e <stdio.h> int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i -1) + fibonacci(i -2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d tn", fibonacci(i)); } return 0; } Output 0 1 1 2 3 5 8 13 21 34
  • 59. Pointers Look at some of the valid pointer declarations int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is − type *var-name;
  • 60. Initialize a pointer After declaring a pointer, we initialize it like standard variables with a variable address. If pointers in C programming are not uninitialized and used in the program, the results are unpredictable and potentially disastrous. To get the address of a variable, we use the ampersand (&)operator, placed before the name of a variable whose address we need. Pointer initialization is done with the following syntax. Pointer Syntax pointer = &variable;
  • 61. Example #include <stdio.h> int main() { int a=10; //variable declaration int *p; //pointer variable declaration p=&a; //store address of variable a in pointer p printf("Address stored in a variable p is :%xn",p); //accessing the address printf("Value stored in a variable p is:%d n",*p); //accessing the value return 0; } Output: Address stored in a variable p is:60ff08 Value stored in a variable p is:10
  • 62. Changing Value Pointed by Pointers #include <stdio.h> int main() { int* pc, c; c = 22; printf( "Address of c: %p n", &c); printf("Value of c: %d nn", c); // 22 pc = &c; printf("Address of pointer pc: %p n", pc); printf("Content of pointer pc: %d nn", *pc); // 22 c = 11; printf("Address of pointer pc: %p n", pc); printf("Content of pointer pc: %d nn", *pc); // 11 *pc = 2; printf("Ad dress of c: %p n", &c); printf("Value of c: %d nn", c); // 2 return 0; } Output Address of c: 2686784 Value of c: 22 Address of pointer pc: 2686784 Content of pointer pc: 22 Address of pointer pc: 2686784 Content of pointer pc: 11 Address of c: 2686784 Value of c: 2
  • 63. Example 2 #include <stdio.h > int main() { // A normal integer variable int Var = 10; // A pointer variable that holds address of var. int *ptr = &Var; // This line prints value at address stored in ptr. // Value stored is value of variable "var" printf("Value of Var = %d n", *ptr); // The output of this line may be different in different // runs even on same machine. printf("Address of Var = %p n", ptr); // We can also use ptr as lvalue (Left hand // side of assignment) *ptr = 20; // Value at address is now 20 // This prints 20 printf("After doing *ptr = 20, *ptr is %d n", *ptr); return 0; } Output : Value of Var = 10 Address of Var = 0x7fffa057dd4 After doing *ptr = 20, *ptr is 20
  • 64. Pointer Expressions and Pointer Arithmetic A limited set of arithmetic operations can be performed on pointers. A pointer may be: • incremented ( ++ ) • decremented ( — ) • an integer may be added to a pointer ( + or += ) • an integer may be subtracted from a pointer ( – or -= ) Pointer arithmetic is meaningless unless performed on an array. Note : Pointers contain addresses. Adding two addresses makes no sense, because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between these two addresses.
  • 65. Example #include < stdio.h> int main() { // Declare an array int v[3] = {10, 100, 200}; // Declare pointer variable int *ptr; // Assign the address of v[0] to ptr ptr = v; for (int i = 0; i < 3; i++) { printf("Value of *ptr = %d n", *ptr); printf("Value of ptr = %p nn", ptr); // Increment pointer ptr by 1 ptr++; } } Output: Value of *ptr = 10 Value of ptr = 0x7ffcae30c710 Value of *ptr = 100 Value of ptr = 0x7ffcae30c714 Value of *ptr = 200 Value of ptr = 0x7ffcae30c718
  • 66. Key Points to Remember About Pointers in C • Normal variable stores the value whereas pointer variable stores the address of the variable. • The content of the C pointer always be a whole number i.e. address. • Always C pointer is initialized to null, i.e. int *p = null. • The value of null pointer is 0. • & symbol is used to get the address of the variable. • symbol is used to get the value of the variable that the pointer is pointing to. • If a pointer in C is assigned to NULL, it means it is pointing to nothing. • Two pointers can be subtracted to know how many elements are available between these two pointers. • But, Pointer addition, multiplication, division are not allowed. • The size of any pointer is 2 byte (for 16 bit compiler).
  • 67. Example #include <stdio.h> int main() { int *ptr, q; q = 50; /* address of q is assigned to ptr */ ptr = &q; /* display q's value using ptr variable */ printf("%d", *ptr); return 0; } Output 50
  • 68. Types of Pointers in C #include <stdio.h> int main() { int *p = NULL; //null po inter printf(“The value inside variable p is: n%x”,p); return 0; } Output: The value inside variable p is: 0 Null Pointer We can create a null pointer by assigning null value during the pointer declaration. This method is useful when you do not have any address assigned to the pointer. A null pointer always contains value 0.
  • 69. Void Pointer #include <stdio.h> int main() { void *p = NULL; //void pointer printf("The size of pointer is:%dn",sizeof(p)); return 0; } Output: The size of pointer is:4 In C programming, a void pointer is also called as a generic pointer. It does not have any standard data type. A void pointer is created by using the keyword void. It can be used to store an address of any variable.
  • 70. Wild pointer #include <stdio.h> int main() { int *p; //wild pointer printf("n%d",*p); return 0; } Output timeout: the monitored command dumped core sh: line 1: 95298 Segmentation fault timeout 10s main A pointer is said to be a wild pointer if it is not being initialized to anything. These types of C pointers are not efficient because they may point to some unknown memory location which may cause problems in our program and it may lead to crashing of the program. One should always be careful while working with wild pointers.
  • 71. C Pointers & Arrays with Examples #include <stdio.h> int main() { int a[5]={1,2,3,4,5}; //array initialization int *p; / /pointer declaration /*the pt r points to the first element of the array*/ p=a; /*We can also type simply ptr==&a[0] */ printf("Printing the array elements using pointer n"); for(int i=0;i<5;i++) //loop for traversing array elements { printf(" n%x",*p); //printing array elements p++; //incrementing to the next element, you can also write p=p+1 } return 0; } Output 1 2 3 4 5
  • 72. Pointers and Multidimensio nal Arrays Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration int nums[2][3] = { {16, 18, 20}, {25, 26, 27} }; In general, nums[i][j] is equivalent to *(*(nums+i)+j)
  • 73. C Pointers and Strings A string is an array of char objects, ending with a null character ' 0'. We can manipulate strings using pointers. This pointer in C example explains this section
  • 74. Advantages of Pointers in C • Pointers are useful for accessing memory locations. • Pointers provide an efficient way for accessing the elements of an array structure. • Pointers are used for dynamic memory allocation as well as deallocation. • Pointers are used to form complex data structures such as linked list, graph, tree, etc.
  • 75. Disadvantages of Pointers in C • Pointers are a little complex to understand. • Pointers can lead to various errors such as segmentation faults or can access a memory location which is not required at all. • If an incorrect value is provided to a pointer, it may cause memory corruption. • Pointers are also responsible for memory leakage. • Pointers are comparatively slower than that of the variables. • Programmers find it very difficult to work with the pointers; therefore it is programmer's responsibility to manipulate a pointer carefully.
  • 76. Pointer to Pointer in C A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
  • 77. Example #include <stdio.h> int main () { int var; int *ptr; int **pptr; var = 3000; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr; /* take the value using pptr */ printf("Value of var = %d n", var ); printf("Value available at *ptr = %d n", *ptr ); printf("Value available at **pptr = %d n", **pptr); return 0; } Value of var = 3000 Value available at *ptr = 3000 Value available at **pptr = 3000
  • 78. Dynamic Memory Allocation in C Dynamic Memory Allocation is manual allocation and freeing of memory according to your programming needs. Dynamic memory is managed and served with pointers that point to the newly allocated memory space in an area which we call the heap. Now you can create and destroy an array of elements dynamically at runtime without any problems. To sum up, the automatic memory management uses the stack, and the C Dynamic Memory Allocation uses the heap. The <stdlib.h> library has functions responsible for Dynamic Memory Management.
  • 79. C malloc() Function The C malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location. The pointer returned is usually of type void. It means that we can assign C malloc() function to any pointer. Syntax of malloc() Function: ptr = (cast_type *) malloc (byte_size);
  • 80. Example #include <stdlib.h> int main(){ int *ptr; ptr = malloc(15 * sizeof(* ptr)); /* a block of 15 integers */ if (ptr != NULL) { *(ptr + 5) = 480; /* assign 480 to sixth integer */ printf("Value of the 6th integer is %d",*(ptr + 5)); } } Output: Value of the 6th integer is 480
  • 81. C calloc() Function The C calloc() function stands for contiguous allocation. This function is used to allocate multiple blocks of memory. It is a dynamic memory allocation function which is used to allocate the memory to complex data structures such as arrays and structures. Syntax of calloc() Function: ptr = (cast_type *) calloc (n, size);
  • 82. Example #include <stdio.h> int main() { int i, * ptr, sum = 0; ptr = calloc(10, sizeof(int)); if (pt r == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Building and calculating the sequence sum of the first 10 terms n "); for (i = 0; i < 10; ++i) { * (ptr + i) = i; sum += * (ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } Result: Building and calculating the sequence sum of the first 10 terms Sum = 45
  • 83. C free() method “free” method in C is used to dynamically de- allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr);
  • 85. C realloc() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.
  • 86. Example #include <stdio.h> #includ e <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Addresses of previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%u n",pt r + i); printf(" nEnter the new size: "); scanf("%d", &n2); // rellocating the memory ptr = realloc(ptr, n2 * sizeof(int)); printf("Addresses of newly allocated memory: "); for(i = 0; i < n2; ++i) printf("%u n", ptr + i); free(ptr); return 0; } When you run the program, the output will be: Enter size: 2 Addresses of previously allocated memory:26855472 26855476 Enter the new size: 4 Addresses of newly allocated memory:26855472 26855476 26855480 26855484
  • 87. Difference between static and dynamic memory allocation
  • 88. Difference Between malloc() and calloc() Functions in C:
  • 89. Array of pointers #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr[MAX]; for ( i = 0; i < MAX; i++) { ptr[i] = &var[i]; /* assign the address of integer. */ } for ( i = 0; i < MAX; i++) { printf("Value of var[%d] = %d n", i, *ptr[i] ); } return 0; } When the above code is compiled and executed, it produces the following result − Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
  • 90. Pointer to an Array in C #include <stdio.h> int main () { /* an array with 5 elements */ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; int i; p = balance; /* output each array element's value */ printf( "Array values using pointern"); for ( i = 0; i < 5; i++ ) { printf("*(p + %d) : %fn", i, *(p + i) ); } printf( "Array values using balance as addressn"); for ( i = 0; i < 5; i++ ) { printf("*(balance + %d) : %fn", i, *(balance + i) ); } return 0; } Array values using pointer *(p + 0) : 1000.000000 *(p + 1) : 2.000000 *(p + 2) : 3.400000 *(p + 3) : 17.000000 *(p + 4) : 50.000000 Array values using balance as address *(balance + 0) : 1000.000000 *(balance + 1) : 2.000000 *(balance + 2) : 3.400000 *(balance + 3) : 17.000000 *(balance + 4) : 50.000000
  • 91. Pointers and functions In C programming, it is also possible to pass addresses as arguments to functions. To accept these addresses in the function definition, we can use pointers. It's because pointers are used to store addresses.
  • 92. Pass Addresses to Functions #include <stdio.h> void swap(int *n1, int *n2); int main() { int num1 = 5, num2 = 10; // address of num1 and num2 is passed swap( &num1, &num2); printf("num1 = %dn", num1); printf("num2 = %d", num2); return 0; } void swap(int* n1, int* n2) { int temp; temp = *n1; *n1 = *n2; *n2 = temp; } When you run the program, the output will be: num1 = 10 num2 = 5
  • 93. Passing Pointers to Functions #include <stdio.h> void addOne(int* ptr) { (*ptr)++; // adding 1 to *ptr } int main() { int* p, i = 10; p = &i; addOne(p); printf("%d", *p); // 11 return 0; } Output 11
  • 94. Function Pointer in C #include <stdio.h> // A n ormal function with an int parameter // and void return type void fun(int a) { printf("Value of a is %d n", a); } int main() { // fun_ptr is a pointer to function fun() void (*fun_ptr)(int) = &fun; /* The above line is equiva lent of following two void (*fun_ptr)(int); fun_ptr = &fun; */ // Invoking fun() using fun_ptr (*fun_ptr)(10); return 0; } Output: Value of a is 10