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

Unit 3 FOC

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

Unit 3 FOC

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

C programming and problem solving Module 3

MODULE 3
Arrays
INTRODUCTION
Arrays: Array is a sequential collection of similar data items.
Pictorial representation of an array of 5 integers

10 20 30 40 50
A[0] A[1] A[2] A[3] A[4]

 An array is a collection of similar data items.


 All the elements of the array share a common name .
 Each element in the array can be accessed by the subscript(or index) and array name.
 The arrays are classified as:
1. Single dimensional array
2. Multidimensional array.

Single Dimensional Array.

 A single dimensional array is a linear list of related data items of same data type.
 In memory, all the data items are stored in contiguous memory locations.
Declaration of one-dimensional array(Single dimensional array)
Syntax:

datatype array_name[size];

 datatype can be int,float,char,double.


 array_name is the name of the array and it should be an valid identifier.
 Size is the total number of elements in array.
For example:
int a[5];
The above statement allocates 5*2=10 Bytes of memory for the array a.

a[0] a[1] a[2] a[3] a[4]

float b[5];

Nivesh Balyan 1
C programming and problem solving Module 3

The above statement allocatests 5*4=20 Bytes of memory for the array b.

 Each element in the array is identified using integer number called as index.
 If n is the size of array, the array index starts from 0 and ends at n-1.

Storing Values in Arrays

 Declaration of arrays only allocates memory space for array. But array elements are not initialized
and hence values has to be stored.
 Therefore to store the values in array, there are 3 methods
1. Initialization
2. Assigning Values
3. Input values from keyboard through scanf()

Initialization of one-dimensional array


 Assigning the required values to an array elements before processing is called initialization.

data type array_name[expression]={v1,v2,v3…,vn};

Where
 datatype can be char,int,float,double
 array name is the valid identifier
 size is the number of elements in array
 v1,v2,v3… ..... vn are values to be assigned.

 Arrays can be initialized at declaration time.


Example:
int a[5]={2,4,34,3,4};

2 4 34 3 4

a[0] a[1] a[2] a[3] a[4]

 The various ways of initializing arrays are as follows:


1. Initializing all elements of array(Complete array initialization)
2. Partial array initialization

Nivesh Balyan 2
C programming and problem solving Module 3

3. Initialization without size


4. String initialization

1. Initializing all elements of array:


 Arrays can be initialized at the time of declaration when their initial values are known in advance.
 In this type of array initialization, initialize all the elements of specified memory size.
 Example:
int a[5]={10,20,30,40,50};
10 20 30 40 50

2. Partial array initialization


 If the number of values to be initialized is less than the size of array then it is called as partial
array initialization.
 In such a case elements are initialized in the order from 0th element.
 The remaining elements will be initialized to zero automatically by the compiler.
 Example:
int a[5]={10,20};

10 20 0 0 0

3. Initialization without size


 In the declaration the array size will be set to the total number of initial values specified.
 The compiler will set the size based on the number of initial values.
 Example:
int a[ ]={10,20,30,40,50};
 In the above example the size of an array is set to 5

4. String Initialization
 Sequence of characters enclosed within double quotes is called as string.
 The string always ends with NULL character(\0)

char s[5]=”SVIT”; We can observe that string length is 4,but size


is 5 because to store NULL character we need
one more location.

So pictorial representation of an array s is as follows:

Nivesh Balyan 3
C programming and problem solving Module 3

S V I T \0
S[0] S[1] S[2] S[3] S[4]

3.1.2 Assigning values to arrays


Using assignment operators, we can assign values to individual elements of arrays.
For example:
int a[3];
a[0]=10;
a[1]=20;
a[2]=30;

10 20 30

a[0] a[1] a[2]

Reading and writing single dimensional arrays.


To read array elements from keyboard we can use scanf() function as follows:

To read 0th element: scanf(“%d”,&a[0]);


To read 1st element: scanf(“%d”,&a[1]);
To read 2nd element: scanf(“%d”,&a[2]);
……
…….
To read n element : scanf(“%d”,&a[n-1]);
th

In general
To read ith element:
scanf(“%d”,&a[i]); where i=0; i<n; i++

To print array elements we can use printf() function as follows:

To print 0th element: printf(“%d”,a[0]);


To print 1st element: printf(“%d”,a[1]);
To print 2nd element :printf(“%d”,a[2]);
……..
……..

To nth element : printf(“%d”,&a[n-1]);

Nivesh Balyan 4
C programming and problem solving Module 3

Two Dimensional arrays:


 In two dimensional arrays, elements will be arranged in rows and columns.
 To identify two dimensional arrays we will use two indices(say i and j) where I index indicates row
number and j index indicates column number.

Declaration of two dimensional array:

data_type array_name[exp1][exp2];
Or
data_type
array_name[row_size][column_size];

 data_type can be int,float,char,double.


 array_name is the name of the array.
 exp1 and exp2 indicates number of rows and columns

For example:
int a[2][3];
 The above statements allocates memory for 3*4=12 elements i.e 12*2=24 bytes.

Initialization of two dimensional array


Assigning or providing the required values to a variable before processing is called initialization.
Data_type array_name[exp1][exp2]={

{a1,a2,. .... an}


{b1,b2,. ... bn}
..............
{z1,z2. ...... zn}

Nivesh Balyan 7
C programming and problem solving Module 3

 Data type can be int,float etc.


 exp1 and exp2 are enclosed within square brackets .
 both exp1 and exp2 can be integer constants or constant integer expressions(number of rows and
number of columns).
 a1 to an are the values assigned to 1st row ,
 b1 to bn are the values assigned to 2nd row and so on.
 Example:
int a[3][3]={
{10,20,30},
{40,50,60},
{70,80,90}
};

10 20 30

40 50 60

70 80 90

Partial Array Initialization


 If the number of values to be initialized is less than the size of array, then the elements are
initialized from left to right one after the other.
 The remaining locations initialized to zero automatically.
 Example:
int a[3][3]={
{10,20},
{40,50},
{70,80}
};
10 20 0

40 50 0

70 80 0

Nivesh Balyan 8
C programming and problem solving Module 3

1. Write a c program to read & print 2d array as a Array.

#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“eneter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“array elements are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
}

Nivesh Balyan 9
C programming and problem solving Module 3

Strings

Definition:
 A string is a sequence of characters within double quotes. A string constant is always terminated y null character.
 A string is pictorially represented as follows:

a S V I T \0
0 1 2 3 4

String Declaration:
 Like all other variable a string variable a string variable also has to be declared before it is used.

Syntax: char string_name[size];

Example: char s[10];

The above declaration statement allocates 10 bytes of memory to string s as follows:

0 1 2 3 4 5 6 7 8 9

String Initialization:
Initialization is a process of assigning values to a string, before doing manipulation.
Strings are initialized in 4 ways:
1. Initializing character by character
2. Partial Array Initialization
3. Initialization without size
4. Initialization of Array with string

Nivesh Balyan Page 1


1.Initializing character by character 2. Partial Array Initialization
 Consider following declaration and initialization  If the number of characters to be initialized is less than
char b[5]={ „S‟,‟V‟,‟I‟,‟T‟}; the size of array then the remaining locations will be
 The complier allocates 5 memory locations and these initialized to NULL as follows:
locations are initialized with the character in the order Char b[5]={ „H‟,‟I‟};
specified.
b S V I T \0 b H I \0 \0 \0
0 1 2 3 4 0 1 2 3 4

3.Initialization without Size 4.Initialization of array with string


 If a string is declared without size then compiler will set
the array size to the total number of initialized values. char b[]=”SVIT”;
char b[]={ „S‟,‟V‟,‟I‟,‟T‟};
In the above initialization the string length is 4 bytes but size is
b H I \0 \0 \0 5 bytes.
0 12 3 4 b S V I T \0
Size of b is 4 0 1 2 3 4

String Input and Output functions:


 The strings can be read from the keyboard and can be displayed onto the monitor using various functions:

[Type text] [Type text] [Type text]


C programming and problem solving

Formatted Input Function: scanf() Formatted Output Function: printf()


 The formatted input function is scanf().  The formatted output function is printff().
 It reads a string from the keyboard  It prints/displays a string which is stored on memory
 The format specifier is %s locations on monitor
 The string is terminated by NULL character(\0) Syntax: printf(“%s”,str);
Syntax: scanf(“%s”,str);  Example:
 Example: char str[5]=”SVIT”;
char str[5]=”SVIT”; printf(“%s”,str);
scanf(“%s”,str);

b S V I T \0
0 1 2 3 4
NOTE: scanf() cannot read spaces and any special symbols i.e
conversion code cannot read spaces, it will terminated as soon
as space appear.
Write a program to read and print an string using scanf() and printf()
#include<stdio.h>
void main()
{
char str[20];
printf(“enter the string\n”);
scanf(“%s”,str);
printf(“The entered string is \n”);
printf(“%s”,str);
}

Nivesh Balyan Page 3


C programming and problem solving

UnFormatted Input Function: scanf() UnFormatted output Function: puts()


 The Unformatted input function is gets().  The Unformatted output function is puts().
 It reads a sequence of characters(line) from the keyboard  This function displays all the character(line) stored in
with spaces in between and store them in memory variable str on the monitor till it encounters \0(Null
locations. Character)
Syntax: gets(str); Syntax: gets(str);
 Example:  Example:
char str[20]; char str[20]=”HELLO”;
printf(“enter the string\n”); printf(“the string is \n”);
gets(str); puts(str);

Write a program to read and print an string using gets() and puts()
#include<stdio.h> OutPut:
#include<string.h>
void main() Enter the string
{ HELLO HOW R U
char str[20]; The entered string is
printf(“enter the string\n”); HELLO HOW R U

gets(str);
printf(“The entered string is \n”);
puts(str);
}
H E L L O H O W R U \0

Nivesh Balyan Page 4


C programming and problem solving

Based on the kind of data processed, the I/O function are classified into
1. Token Oriented I/O functions:
2. Line Oriented I/O functions
3. Character Oriented I/O functions

1. Token Oriented I/O functions:


 The I/O functions processes individual units such as characters,integers,double values,float values and are separated by
whitespaces characters. Since these individual units are called tokens,the functions that perform these kind of operations are
called Token Oriented I/O functions.
 The functions scanf() and printf() are Token Oriented I/O functions.
2. Line Oriented I/O functions
 The I/O functions that process entire line are called line oriented I/O functions.
 The functions gets() and puts() are Line Oriented I/O functions.
3. Character Oriented I/O functions
a) getchar() and putchar()
 To read a character from the keyboard and store this character into memory location, getchar() function is used.
 We have to press the ENTER KEY after typing character.
Syntax: ch=getchar();
 To display a character stored in the memory on the screen ,putchar() function is used.
Syntax:putchar(ch);

Write a C program to Find the section of student.


#include<stdio.h>
#include<string.h>
void main()
{
char sec; OUTPUT
printf(“Enter your section\n”); Enter Your Section
scanf(“%d”,&sec); B

Nivesh Balyan Page 5


C programming and problem solving

sec=getchar(); Your section is


printf(“Your section is \n”); B
putchar(sec);
}
b) getch(),getche(),putch()
 The getch() function reads a character from the keyboard and copies it into specified memory location identified by ch.
 Syntax: ch=getch()
 The typed character will not be echoed(displayed) on the screen if we use getch() function.
 No arguments are required for this function
 The getche() function reads a character from the keyboard and copies it into specified memory location identified by ch.
 Syntax: ch=getche()
 The typed character will be echoed(displayed) on the screen if we use getche() function. No arguments are required for this
function
 The putchar() displays a character stored in memory location identified by variable ch on the screen.
 Syntax: putch(ch)

Nivesh Balyan Page 6


C Programming and Problem Solving (18PCD23)

String handling Functions


SL. Name Syntax Example Explanation
No
1 strlen int strlen (char str[ ]); char str[15]=”SVIT”; -This function returns the length of
int count; the string str.
count=strlen(str); -It counts all the characters until
S V I T \0 null character is encountered.
0 1 2 3 4
The example str variable contains 4
characters S,V,I,T , hence count is 4

2 strcpy strcpy(char dest[ ] , char src[ ]); char src[5] =”SVIT”;  This function copies content
char dest[5]; from source string to
strcpy(dest ,src); destination string including \0.
src[0] src[1] src[2] src[3] src[4]  Size of dest string should be
s V I T \0 greater or equal to the size of
source string src to store the
S V I T \0 entire source string.

dest[0] dest [1] dest [2] dest [3] dest [

Nivesh Balyan Page 7


C programming and problem solving

3. strncpy strcpy(char dest[ ] , char src[ ],int n); char src[5] =”SVIT”;  This function copies n
char dest[5]; characters from source string to
strcpy(dest ,src,2); destination string .
src[0] src[1] src[2] src[3] src[4]  In thisexample only 2
S V I T \0 characters are copied from src
to dest.
S V \0

dest[0] dest [1] dest [2] dest [3] dest [4]

4 strcat strcat(char s1[ ] , char s2[ ]); char s1[5]=”SVIT”;


char s2[5]=”ECE”;  This function copies the all
strcat(s1,s2); characters of s2 string to the
S V I T \0 end of s1 string.
0 1 2 3 4  The delimiter of s1 is replaced
by first character of s2.
E C E \0  Size of s1 string should be
0 1 2 3 4 greater or store the contents of
both the string
S1 S V I T E C E \0
0 1 2 3 4 4 6 7 8 9

5 strncat strncat(char s1[ ] , char s2[ ],n); char s1[5]=”SVIT”;  This function copies the n
char s2[5]=”ECE”; characters of s2 string to the
strncat(s1,s2,2); end of s1 string.
 The delimiter of s1 is replaced
S V I T \0 by first character of s2.
0 1 2 3 4

Page 8
C programming and problem solving

E C E \0
0 1 2 3 4

S1 S V I T E C \
0
0 1 2 3 4 4 6 7 8 9

In the above example only 2 characters(EC)


from string s2 copies to string s1.

6 strcmp int strcmp( char s1[ ] , char s2[ ]); 1) Strings are equal where:
S1[4]=”RAM”; s1 is first string
S2[4]=”RAM”; s2 is second string
Strcmp(S1,S2);  This function used to
compare two strings.
R == S2[0] R  The comparison starts with
S1[0] first character of each
S1[1] A == S2[1] A string.
S1[2] M == S3[2] M  This comparison continues
S1[3] \0 == S4[3] \0 till the corresponding
character differ or until the
S1[0]==S2[0] end of the character is
R==R(ASCII value of R is compared) reached.
similarly for other characters.  The strcmp Returns 3values
S1[3]==S2[3] Possibly:
\0==\0(ASCII value of \0 is compared and it returns 0 if both strings are equal.
is 0.) returns positive value ,if s1>s2
2)String S1 is Lesser than String S2 returns negative value if s1<s2

Nivesh Balyan Page 9


C programming and problem solving

S1[4]=”ABC”;
S2[4]=”BAC”;
Strcmp(S1,S2);

S1[0] A == S2[0] B
S1[1] B == S2[1] A
S1[2] C == S3[2] C
S1[3] \0 == S4[3] \0

S1[0]==S2[0]
A==B(ASCII value of A is compared with
ASCII value of B)
i.e 65==66 returns S1<S2

3)String S1 is Greater than String S2


S1[4]=”BBC”;
S2[4]=”ABC”;
Strcmp(S1,S2);

S1[0] B == S2[0] A
S1[1] B == S2[1] B
S1[2] C == S3[2] C
S1[3] \0 == S4[3] \0

S1[0]==S2[0]
A==B(ASCII value of A is compared with
ASCII value of B)
i.e 66==65 returns S1>S2

Nivesh Balyan Page 10


C programming and problem solving

7 strncmp int strcmp( char s1[ ] , char s2[ ], n); 1) Strings are equal where:
S1[4]=”RAM”; s1 is first string
S2[4]=”RAM”; s2 is second string
strcmp(S1,S2,2);  This function used to
comparen number of
R == S2[0] R characters two strings.
S1[0]  The comparison starts with
S1[1] A == S2[1] A first character of each
S1[2] M == S3[2] M string.
S1[3] \0 == S4[3] \0  This comparison continues
till the corresponding
Only 2 characters from each S1 and S2 is character differ or until the
compared. end of the character is
Other function is similar to strcmp(). reached or specified number
of characters have been
tested..
 The strcmp Returns 3values
Possibly:
returns 0 if both strings are equal.
returns positive value ,if s1>s2
returns negative value if s1<s2

8 strrev( ) void strrev(char str[ ]); Given string  This function reverse all
S1 S V I T E C E \0 characters in the S1 except
0 1 2 3 4 5 6 7 89 Null character.
strrev(s1  The original string is lost.
Reverse String
S1 E C E T I V S \0
0 1 2 3 4 5 6 7 8 9

Nivesh Balyan Page 11


C programming and problem solving

S1[6]==S1[0]
S1[5]==S1[1]
S1[4]==S1[2]
S1[3]==S1[3]
S1[2]==S1[4]
S1[1]==S1[5]
S1[0]==S1[6]

Example Programs for string handling functions

strlen() strrev()
#include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> void main()
void main() {
{ char name[15]; char str[]=”INDIA”;
int len; strrev(str);
printf(“Enter the string\n”); printf(“string=%s”,str);
gets(name); }
len=strlen(name);
printf(“\n The string length is %d”,len); OUTPUT
} String=AIDNI

OUTPUT
Enter the string
COMPUTER
The string length is 8

Nivesh Balyan Page 12


C programming and problem solving

SCOPE OF VARIABLE
There are two types of Variables on the basis of Scopes:
A. Local Variable
B. Global Variable

Local Variable: The variable that is declared in a function or code is called a local variable. The scope of Local variables is within the defined
function only. You cannot use a local variable outside the function (in which it is declared).

Program for Local Variable:

#include <stdio.h>

void person()
{
// Local Variables of the function

int age = 20;


float height = 5.6;

printf("age is %d \n", age);

printf("height is %f", height);

int main()
{

person();

return 0;

}
C programming and problem solving

Global Variable: The scope of the global variable is the entire program. They are not defined inside any function and can be used in any function.

Program for Global Variable:

#include <stdio.h>

// Declaring global variable

int a = 23;

void function1()
{

// Function using global variable a

printf("The number is %d \n", a);

void function2()
{
// Function using global variable a

printf("The number is %d \n", a);

int main()
{
// Calling functions

function1();
function2();

return 0;

}
C programming and problem solving
Program Output
HOW TO CALL C FUNCTIONS IN A PROGRAM?
There are two ways that a C function can be called from a program. They are,

1. Call by value
2. Call by reference
1. CALL BY VALUE:
 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter can not be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:

 Actual parameter – This is the argument which is used in function call.


 Formal parameter – This is the argument which is used in function definition
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
 In this program, the values of the variables “m” and “n” are passed to the function “swap”.
 These values are copied to formal parameters “a” and “b” in swap function and used.
1 #include<stdio.h>
2 // function prototype, also called function declaration
3 void swap(int a, int b);
4
5 int main()
6 {
7 int m = 22, n = 44;
8 // calling swap function by value
9 printf(" values before swap m = %d \nand n = %d", m, n);
10 swap(m, n);
11 }
12
13 void swap(int a, int b)
14 {
15 int tmp;
16 tmp = a;
17 a = b;
18 b = tmp;
19 printf(" \nvalues after swap m = %d\n and n = %d", a, b);
20 }
COMPILE & RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
2. CALL BY REFERENCE:
 In call by reference method, the address of the variable is passed to the function as parameter.
 The value of the actual parameter can be modified by formal parameter.
 Same memory is used for both actual and formal parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
 In this program, the address of the variables “m” and “n” are passed to the function “swap”.
 These values are not copied to formal parameters “a” and “b” in swap function.
 Because, they are just holding the address of those variables.
 This address is used to access and change the values of the variables.
1 #include<stdio.h>
2 // function prototype, also called function declaration
3 void swap(int *a, int *b);
4
5 int main()
6 {
7 int m = 22, n = 44;
8 // calling swap function by reference
9 printf("values before swap m = %d \n and n = %d",m,n);
10 swap(&m, &n);
11 }
12
13 void swap(int *a, int *b)
14 {
15 int tmp;
16 tmp = *a;
17 *a = *b;
18 *b = tmp;
19 printf("\n values after swap a = %d \nand b = %d", *a, *b);
20 }
COMPILE & RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22

Difference between Call by Value and Call by Reference


Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of
values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by function are called formal
parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two
types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual
parameters of caller.
Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside the function are
actually reflected in actual parameters of caller.

CALL BY VALUE CALL BY REFERENCE

While calling a function, instead of passing the values of

While calling a function, we pass values of variables to it. variables, we pass address of variables(location of variables) to

Such functions are known as “Call By Values”. the function known as “Call By References.

In this method, the value of each variable in calling In this method, the address of actual variables in the calling

function is copied into corresponding dummy variables of function are copied into the dummy variables of the called

the called function. function.

With this method, the changes made to the dummy With this method, using addresses we would have an access to

variables in the called function have no effect on the the actual variables and hence we would be able to manipulate

values of actual variables in the calling function. them.

In call by values we cannot alter the values of actual In call by reference we can alter the values of variables through

variables through function calls. function calls.

Pointer variables are necessary to define to store the address

Values of variables are passes by Simple technique. values of variables.

You might also like