0% found this document useful (0 votes)
4 views60 pages

Module_3-1

Copyright:

© All Rights Reserved

Available Formats

Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
4 views60 pages

Module_3-1

Copyright:

© All Rights Reserved

Available Formats

Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 60

ARRAYS

Array is a collection of similar data item that share a common name and
stores in continuous memory locations.
Array is a variable that can store multiple values.
Why Arrays:
 we can use variables for small number of objects. In case if you want 1000
variables, you have to use 1000 scanf statements to read those values and 1000
printf values to print output.
 Then it becomes difficult to manage. In this case Arrays are useful.

Ex: int a[1000] ( square bracket [ ] – subscript )

1
 Here array is a group of elements with similar datatypes or same datatype
either it could be int,char,float or double (fundamental datatypes)
 Numerical array
 Character array
 The rules we applied while creating variable name is followed in arrays also
[no keywords matching ,maximun of 32 keywords etc,.]
 int marks[3];

if you try to access marks[3] it will not give any error but it will result in
inappropriate output.(if you go beyond the maximum)

2
3
Types of Arrays:
1. One dimensional arrays a[i]
2. Two dimensional arrays a[i][j]
3. Multi dimensional arrays a[ ][ ][ ]…[ ]
One Dimensional Array (Single Subscript array)
It is a linear array, in which accessing elements is done by using single
subscript.we need to place the subscript by seeing the subscript itself we know
whetger it is one or two or multi array.
Declaration:
syntax: type array_name[ size ];

4
Ex: int a[5]; // creates an array of integer type with size 5
float b[5];
char c[5]; // strings

5
Advantages of Arrays :
 Arrays can represent multiple data items of same type using a single name.
 Elements in arrays can be easily accessed by using index number.
 Matrices can be implemented by using 2 Dimensional arrays.
 Using arrays we can also implement data structures like Linked Lists,
Stacks, Queues, Graphs etc.
 Searching and sorting can be done efficiently.

Disadvantages of Arrays :
 The number of elements to be used in array have to be declared before.
 Arrays are static data type. Once the size of array is declared, we can’t
modify it again.
 Insertion and deletion of elements are slightly difficult as they are stored in
continuous memory locations.
 More memory allocation leads to wastage of memory.

6
Array Declaration:
Before making use of an array in C, it must be declared just like any other
variable. An array can be declared by giving it a name, indicating the kind of
elements it contains, and defining its dimensions. In C, the compiler assigns
the array name to a memory block of the specified size when we declare an
array.
Syntax: datatype Array_name[size];

7
Array Initialization :
Initialization in C is the process to assign some initial value to the variable. Using
each element's index to initialize an array is the most simplest method. The index
allows us to initialize every value in the array.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

8
Array Initialization with Declaration
We initialize the array and declare it in this procedure. To initialize numerous
array elements, we utilize an initializer list. A list of values separated by
commas and enclosed in braces {} known as an initializer list.
Syntax: datatype Array_name[size]={value1,value2,…};

9
Array Initialization with Declaration without Size
When we initialise an array with an initializer list, the compiler can determine the
size of the array automatically, so we don't need to declare it.
Syntax: datatype Array_name[]={value1,value2,…};

Array Initialization after Declaration (Using Loops)


Following the declaration, we initialise the array by giving each element its initial
value. Each element of the array can have a value assigned to it using the for,
while, or do-while loops.
Syntax:
for (int i = 0; i <= n; i++) {
array_name[i]=value i;
}

10
C program to declare and initialize the array in c.

#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}

11
Accessing the array elements:
We can access any element of an array in C using the array subscript
operator [ ] and the index value i of the element.
Syntax: array_name[index];
To access the array element it refers to its index number.Array indexes starts with 0:
[0] is the first element [1] is the second element etc,.

12
Write a program to print array elements with index positions

#include <stdio.h>
int main() {
int array[] = {10, 20, 30, 40, 50};

printf("array[0] = %d\n", array[0]);


printf("array[1] = %d\n", array[1]);
printf("array[2] = %d\n", array[2]);
printf("array[3] = %d\n", array[3]);
printf("array[4] = %d\n", array[4]);

return 0;
}
13
//Run-time
#include<stdio.h>
int main()
{
char name[4];
int i;
for(i=0;i<4;i++)
{
scanf("%c",&name[i]);
}
for(i=0;i<4;i++)
{
printf("%c",name[i]);
}
}
14
//initialization of an array at compile time.
#include<stdio.h>
int main()
{
char name[5]={'H','e','l','l','o'};
int i;
for(i=0;i<5;i++)
{
printf("%c",name[i]);
}
}

15
#include <stdio.h>
int main() {
char name[6];
name[0] = 'H';
name[1] = 'e';
name[2] = '1';
name[3] = '1';
name[4] = 'o';
name[5] = '\0'; // Null-terminate the string
printf("%c%c\n", name[4], name[5]);
// Print all elements in the array
for (int i = 0; i < 6; i++) {
printf("%c", name[i]);
}
return 0; 16
Write a C program sum of array in One-dimensional Array:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[30],i,size,sum;
printf("enter no.of values");
scanf("%d",&size);
printf("enter %d numbers",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
sum=0;
for(i=0;i<size;i++)
{
sum=sum+a[i];
}
printf("sum of elements is %d",sum);
17
}
Min and Max of array
#include<stdio.h>
int main()
{
int a[50],n,i,max,min;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
min = a[0], max = a[0];
for(i=0;i<n;i++){
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
printf("min %d, max %d",min,max);
18
}
2 DIMENSIONAL ARRAYS
 The 2-dimensional array is also known as array of arrays.
 It is used for matrices which can be represented as rows and columns.
 It consists of two indices ( two subscripts ).

Declaration :
type array_name[size] [size];
Ex: int a[3][3];
INITIALIZATION :
int a[2][3] = { {1, 2, 3} , { 4, 5, 6} };
int a[2][3] = { 1, 2, 3, 4, 5, 6 };

19
 Read operation of 2D array:

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


for( j=0; j<c ; j++ ) {
scanf(“%d”, &a[i][j] );
}
}
 Write operation of 2D array:

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


for( j=0; j<c ; j++ ) {
printf(“%d”, &a[i][j] );
}
printf(“ \n “);
}
20
Addition of Two Matrices:
#include <stdio.h>
int main() {
int m, n, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
printf("Enter the elements of matrix A: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix B: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &b[i][j]);
}
21
}
// add the matrices
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
// print the result
printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
22
}
MULTI-DIMENSIONAL
ARRAYS
 A multidimensional array is basically an array of arrays.
 Arrays can have any number of dimensions.
 To create a multidimensional array in C, you need to specify the number
of dimensions and the size of each dimension.
datatype array_name[size1][size2]...[sizeN];

23
STRINGS
 A string is a sequence of characters terminated with a null character – ‘\
0’
 The compiler appends null character by default when it founds a sequence
of characters ( which are enclosed within double quotations ).
 string.h is the header file which consists of string manipulation functions.

Syntax : char a[10];


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

Input and output :


scanf(“%s”, a) ; (or) gets(a); // read input
printf(“%s”, a) ;(or) puts(a); // write or to print output 24
STRING HANDLING FUNCTIONS
 Sometimes we need to manipulate strings in order to solve the problem.
 C provides some set of predefined string handling functions in the library
string.h
1. strlen( ) :
It returns the length of the string.
Syntax : strlen(variable);
Eg:
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));

o/p:26

25
2. strrev( ) :
It reverses the string.
Syntax: strrev(variable);
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
26
3. strcpy( ) :
It copies a string and stores it into another string.
Syntax: strcpy(destination_variable, source_variable );
#include<stdio.h>
#include<string.h>
int main(){
char ch[20]={'s','t','r','i','n','g','\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}

27
4. strcat( ) :
It concatenates or adds two strings.
Syntax: strcat(destination_variable, source_variable );
// concatenates and assigns it to destination_variable
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'A','I','M','L','\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
28
5. strcmp( ) :
It compares two strings equal or not. If they are equal it returns 0.
Syntax: strcmp( v1, v2 );
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
29
}
6. strlwr( ) :
It converts the given string into lower case.
Syntax :
strlwr (variable );

7. strupr( ) :
It converts the given string into upper case.
Syntax :
strupr (variable );

30
//Palindrome in characters
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
if (str[left] != str[right]) {
return 0; // Not a palindrome
}
left++;
right--;
}
return 1; // It is a palindrome
31
}
int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

if (isPalindrome(str)) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}

return 0;
}
32
FUNCTION
 A function is a block of code which only runs when it is called.
 The function can reduce the repetition of the same statements in the program.
 The function makes code readable by providing modularity to our program.
 There is no fixed number of calling functions it can be called as many times as you want.
Types of functions
Standard library functions

 The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.
 These functions are defined in the header file. When you include the header file, these functions
are available for use.
 The printf() is a standard library function to send formatted output to the screen (display output on
the screen). This function is defined in "stdio.h" header file.

 There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(),
getchar() etc. Once you include "stdio.h" in your program, all these functions are available for use.
User-defined functions :

 These functions are created by programmer according to their requirement for example suppose
you want to create a function for add two number then you create a function with name sum() this
type of function is called user defined function.
Functions
Function

Function call Function definition Function


declaration
Function Declarations :

 A function declaration is the process of tells the compiler about a function name. The actual body of
the function can be defined separately.
return_type function_name(parameter);
Defining a function :
 Defining of function is nothing but give body of function that means write logic inside function
body.
return_type function_name(parameter)
{
function body;
}
1. Return type: A function may return a value. The return_type is the data type of the value the

function returns.Return type parameters and returns statement are optional.

2. Function name: Function name is the name of function it is decided by programmer or you.

3. Parameters: This is a value which is pass in function at the time of calling of function A

parameter is like a placeholder. It is optional.

4. Function body: Function body is the collection of statements.


Calling a function :

 When we call any function control goes to function body and execute entire code. For call any
function just write name of function and if any parameter is required then pass parameter.
function_name();
or
variable=function_name(argument);
// declaring a function
void myFunction()
{
printf(“Welcome");
}

int main()
{
myFunction();
// call the function
return 0;
}
#include<stdio.h>
#include<conio.h>
void sum(); // declaring a function
int a=10,b=20, c;
void sum() // defining function
{
c=a+b;
printf("Sum: %d", c);
}
void main()
{
sum(); // calling function
}
ADVANTAGES OF FUNCTION

1.Code Re-usability
2.Develop an application in module format.
3.Easily to debug the program.
4.Code optimization: No need to write lot of code.
Call by value
* The call by value method of passing arguments to
a function copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function have
no effect on the argument.
CATEGORIZATION OF FUNCTIONS
1. Function with no arguments and no return value :
In this type we don’t pass any arguments to the function. And it does not
return any value to the main function.
2. Function with arguments and no return value :
In this type we pass some arguments to the function. And it does not return
any value to the main function.
3. Function with no arguments and return value :
In this type we don’t pass any arguments to the function. And it returns
some value to the main function.
4. Function with arguments and return value :
In this type we pass some arguments to the function. And it returns some
value to the main function.

46
Without Argument Without
Return Type
Without Argument with int sub()
Return Type {
#include <stdio.h>
int a, b;
void add();
printf("Enter two
int sub();
numbers: ");
int main()
scanf("%d %d", &a,
{
&b);
add();
int result = sub();
return a - b;
printf("Subtraction: %d\n", result);
}
return 0;
}
void add()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum: %d\n", a + b);
}
With Argument without Return Type
With Argument with Return Type
#include <stdio.h>
void add(int x, int y);
int sub(int x, int y);
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
add(a, b);
int result = sub(a, b);
printf("Subtraction: %d\n", result);
return 0;
}
void add(int x, int y)
{
printf("Sum: %d\n", x + y);
}
int sub(int x, int y)
{
return x - y;
}
Adding elements in array using functions
#include <stdio.h>
void add();
int sub();
int main
{
int numbers[2];
printf("Enter two numbers: ");
scanf("%d %d", &numbers[0], &numbers[1]);
add(numbers);
int result = sub(numbers);
printf("Subtraction: %d\n", result);
return 0;}
void add(int numbers[])
{
printf("Sum: %d\n", numbers[0] + numbers[1]);
}
int sub(int numbers[])
{
return numbers[0] - numbers[1];
}
Recursive Function
 A function calling itself is known as recursion. The corresponding function is
called recursive function.
 While using recursion, be careful to write an exit condition, otherwise it will be
an infinite loop.
Advantages :
 Recursion reduces time complexity.
 Needs less time to code and to debug also.
 It more useful for data structures like trees, graphs etc.

Disadvantages :
 Recursion uses more memory.
 Compared to iteration, recursion can be slow. (as it requires new stacks every
time)
RECURSIVE FUNCTION
#include <stdio.h>
void sum(int num);
int main()
{
int n = 5;
sum(n);
return 0;
}
void sum(int num)
{
if (num != 0)
{
printf("%d\n", num);
sum(num - 1);
}
//Factorial in recursive function
#include <stdio.h>
// Function to calculate factorial recursively
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
int main() {
int result = factorial(5);
printf("Factorial of 5 is: %d\n", result);
return 0;
}
Iteration vs Recursion :

Both iteration and recursion are repetitive process. Both will repeat some
code until a certain condition is met.
Iteration: A function repeats a block of code until the condition fails.
Iteration can be achieved by a loop having a condition that will fail. An
infinite loop for iteration occurs when the condition never fails.
Recursion: Instead of repeating a block of code, the function calls itself
repeatedly until a certain condition is met.
That condition is generally the exit condition of the recursion.
An infinite recursive loop occurs when the function does not reduce its input
in a way that it will reach the base case (exit condition )

54
Scope rules in C
 The scope of a variable in C is the block or the region in the program where a
variable is declared, defined, and used. Outside this region, we cannot access
the variable and it is treated as an undeclared identifier.
• The scope is the area under which a variable is visible.
• The scope of an identifier is the part of the program where the identifier may
directly be accessible.
• We can only refer to a variable in its scope.
Types of Scope Rules in C:
1.Global Scope
2.Local Scope
1. Global Scope in C
 The global scope refers to the region outside any block or function.

• The variables declared in the global scope are called global variables.
• Global variables are visible in every part of the program.
• Global is also called File Scope as the scope of an identifier starts at the
beginning of the file and ends at the end of the file.
#include <stdio.h>
//global variable definition
int z;
int main ()
{
//local variable definition and initialization
int x,y;
//actual initialization
x = 20;
y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}
2. Local Scope in C
 The local scope refers to the region inside a block or a function. It is the space
enclosed between the { } braces.
• The variables declared within the local scope are called local variables.
• Local variables are visible in the block they are declared in and other
blocks nested inside that block.
• Local scope is also called Block scope.
• Local variables have internal linkage.
#include <stdio.h>
int main()
{
//local variable definition and initialization
int x,y,z;
//actual initialization
x = 20; y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y, z);
return 0;
}
STORAGE CLASSES
 A storage class represents the visibility and a location of a variable. It tells
from what part of code we can access a variable. A storage class in C is
used to describe the following things:
• The variable scope.
• The location where the variable will be stored.
• The initial value(default value) of a variable.
• A lifetime of a variable.
TYPE INITIAL MEMORY ACCESSING LIFETIME
VALUE (SCOPE)
Auto Garbage value Main memory Block Block
Static Zero – 0 Static memory Block / multiple Program
files
Register Garbage value Registers Block Block
Extern (global) Zero - 0 Main memory Block program
60

You might also like