C programming arrays
C programming arrays
Structured LANGUAGE-
and MODULE-2
Object
Oriented By,
Dr. S. Vinila Jinny,
Programming ASP/SCOPE
SYLLABUS
ARRAY IN C:-
➢ Array in C language is a collection or group of
elements (data). All the elements of array
are homogeneous(similar). It has contiguous
memory location.
Declaration of array:-
data_type array_name[array_size];
Eg:-
➢ int marks[7];
Types of array:-
1) 1-D Array
2) 2-D Array
EXAMPLE-1D ARRAY
#include <stdio.h>
int main() {
int values[5];
return 0;
}
ADVANTAGE OF ARRAY:-
1) Code Optimization
2) Easy to traverse data
3) Easy to sort data
4) Random Access
2-D ARRAY IN C:-
➢ 2-d Array is represented in the form of rows
and columns, also known as matrix. It is also
known as array of arrays or list of arrays.
Declaration of 2-d array:-
➢ data_type array_name[size1][size2];
INITIALIZATION OF 2-D ARRAY:-
int arr[3][4]={{1,2,3,4},{2,3,4,5},{3,4,5,6}};
C1 C2 C3 C4
R1 1 2 3 4
R2 2 3 4 5
R3 3 4 5 6
VARIATIONS OF DECLARATION
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify
second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same
reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
EXAMPLE-2D ARRAY for (int i = 0; i < 2; ++i)
#include <stdio.h> for (int j = 0; j < 2; ++j)
int main() {
{
result[i][j] = a[i][j] + b[i][j];
float a[2][2], b[2][2], result[2][2];
}
printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
printf("\nSum Of Matrix:");
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1); for (int i = 0; i < 2; ++i)
scanf("%f", &a[i][j]); for (int j = 0; j < 2; ++j)
} {
printf("Enter elements of 2nd matrix\n"); printf("%.1f\t", result[i][j]);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) if (j == i)
{
printf("\n");
printf("Enter b%d%d: ", i + 1, j + 1);
}
scanf("%f", &b[i][j]);
return 0;
}
OUTPUT
Enter elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
STRINGS
A string in C is like an array of
characters, pursued by a NULL
character.
For example: char c[] = “c string”
Syntax to Define the String in C
char string_variable_name
[array_size];
char c[] = “c string”
STRING DECLARATION
two ways to declare a string in C language.
By char array
By string literal
1. By Char Array
char greeting[6] = {‘T’, ‘a’, ‘b’, ‘l’, ‘e’, ‘\0’};
2. By String Literal
char greeting[] = “Table”;
FUNCTIONS OF STRING
strcpy(s1, s2); – used to copy string s2
into string s1.
strcat(s1, s2); – used to concatenate
string s2 onto the end of string s1.
strlen(s1); – It is used to return the length
of string.
strcmp(s1, s2); – It is used to analyse and
compare the strings s1 and s2. Returns 0
if s1 and s2 are the same; less than 0 if
s1<s2; greater than 0 if s1>s2.
FUNCTIONS OF STRING
strchr(s1, ch); – It is used to discover the
foremost event or occurrence of a
specified character within the actual
string.
strstr(s1, s2); – It is used to return a
pointer to a character at the first index
strrev(s); - reverses a given string
strlwr(s); - Converts string to lowercase
strupr(s); - Converts string to uppercase
STRING EXAMPLE
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
Output:
Greeting message: Hello
#include <stdio.h>
#include <string.h>
for (i = 0; i < length; i++)
void main()
{
{
if (reverse_string[i] == string[i])
char string[25], flag = 1;
reverse_string[25] = {'\0'};
else
int i, length = 0, flag = 0;
{
printf("Enter a string: \n"); flag = 0;
gets(string); break;
for (i = 0; string[i] != '\0'; i++) }
{ }
length++; if (flag == 1)
} printf("%s is a palindrome \n", string);
for (i = length - 1; i >= 0; i--) else
{ printf("%s is not a palindrome \n",
string);
reverse_string[length - i - 1]
= string[i]; }
}
FUNCTIONS IN C LANGUAGE:-
A function is a block of code which only runs
when it is called.
we can pass data, known as parameters, into
a function.
Functions are used to perform certain
actions, and they are important for reusing
code: Define the code once, and use it many
times.
Advantage of function:-
1) Code Resuability
2) Code optimization
SYNTAX TO DECLARE FUNCTION:-
Function Declaration:
return_type function_name(data_type paramet
er);
Function Definition
return_type function_name(data_type parameter)
{
//code to be executed
}
Function Invocation
➢ Syntax to call function:-
variable=function_name(arguments...);
Calling function (Caller)
Called function (Callee) parameter
20
PARAMETER PASSING
parameter passing
int main ()
{ ... double area (double r)
double circum; {
... return (3.14*r*r);
area1 = area(circum); }
...
}
21
Example of function definition
Return-value Formal parameters
type
int gcd (int A, int B)
{
int temp;
while ((B % A) != 0) {
temp = B % A;
B = A;
A = temp; BODY
}
return (A);
Value returned
}
22
RETURN VALUE
A function can return a value
Using return statement
Like all values in C, a function return value has a type
The return value can be assigned to a variable in the
caller
int x, y, z;
scanf(“%d%d”, &x, &y);
z = gcd(x,y);
printf(“GCD of %d and %d is %d\n”, x, y, z);
23
LOCAL VARIABLES
24
POINTS TO NOTE
Theidentifiers used as formal parameters
are “local”.
Not recognized outside the function
Names of formal and actual arguments may
differ
A value-returning function is called by
including it in an expression
A function with return type T (≠ void) can be
used anywhere an expression of type T
25
SOME MORE POINTS
A function cannot be defined within another
function
All function definitions must be disjoint
Nested function calls are allowed
A calls B, B calls C, C calls D, etc.
The function called last will be the first to return
A function can also call itself, either directly
or in a cycle
A calls B, B calls C, C calls back A.
Called recursive call or recursion
26
EXAMPLE: MAIN CALLS NCR, NCR CALLS
FACT
int ncr (int n, int r)
int ncr (int n, int r); {
int fact (int n); return(fact(n) /(fact(r) *fact(n-r)));
}
void main()
{ int fact (int n)
int i, m, n, sum=0; {
scanf (“%d %d”, &m, &n); int i, temp=1;
for (i=1; i<=m; i+=2) for (i=1; i<=n; i++)
sum = sum + ncr (n, i); temp *= i;
printf (“Result: %d \n”, return (temp);
sum); }
}
27
TYPES OF FUNCTIONS
Userdefined Predefined
User writing own getch()
functions scanf()
ASSIGNMENT
Write a C Program to perform Arithmetic
Calculations
1.Addition
2.Subtraction
3.Multiplication
4.Division
Use While, switch, and function concept.
SAMPLE OUTPUT
Artithmetic Calculator
1.ADD
2.SUB
3.MUL
4.DIV
Enter your Choice: 2
SUBTRACTION
Enter two numbers : 5 3
SUB = 2
Need to continue(Y/N):N
CALL BY VALUE IN C LANGUAGE:-
➢ In call by value, value being passed to the
function is locally stored by the function
parameter in stack memory location.
➢ If you change the value of function
parameter, it is changed for the current
function only.
➢ It will not change the value of variable
inside the caller method such as main().
EXAMPLE OF CALL BY VALUE:-
#include <stdio.h>
#include <conio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
clrscr();
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
getch();
return 0;
}
OUTPUT WINDOW :-
int main() {
int x=100;
clrscr();
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
getch();
return 0;
}
OUTPUT WINDOW:-
}
FACTORIAL OF A NUMBER USING RECURSION
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
TYPE MODIFIERS
A type modifier alters the meaning of the
base type to more precisely fit a specific
need.
signed
unsigned
long
short
The int base type can be modified by signed,
short, long, and unsigned.
The char type can be modified by unsigned
and signed.
TYPE MODIFIERS
TYPE QUALIFIERS
C defines type qualifiers that control how
variables may be accessed or modified.
const and volatile.
The type qualifiers must precede the type
names that they qualify.
CONST
Variables of type const may not be changed
by our program.
A const variable can be given an initial
value.
The compiler is free to place variables of this
type into read-only memory
(ROM).
For example,
const int a=10;
creates an integer variable called a with an
initial value of 10 that your program may not
modify.
VOLATILE
The modifier volatile tells the compiler that
a variable's value may be changed in ways
not explicitly specified by the program.
can use const and volatile together
STORAGE CLASSES
These specifiers tell the compiler how to
store the subsequent variable.
storage class represents the visibility and a
location of a variable.
It tells from what part of code we can access
a variable.
The location where the variable will be
stored.
The initialized value, life time and
accessibility of a variable.
TYPES OF STORAGE CLASSES IN C
Storage Storage Default Scope Lifetime
Classes Place Value
auto RAM Garbage Local Within function
Value
extern RAM Zero Global Till the end of the main program
Maybe declared anywhere in the
program
static RAM Zero Local Till the end of the main program,
Retains value between multiple
functions call
Output
REGISTER
we can use the register storage class when
we want to store local variables within
functions or blocks in CPU registers instead
of RAM to have quick access to these
variables.
It is similar to the auto storage class. The
variable is limited to the particular block.
The only difference is that the variables
declared using register storage class are
stored inside CPU registers instead of a
memory. Register has faster access than that
of the main memory.
EXAMPLE
output
SUMMARY
THANK
YOU
55