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

UNIT 3

This document covers arrays and functions in C programming, explaining scalar and aggregate types, including 1D, 2D, and multidimensional arrays. It discusses string handling, function definitions, recursion, storage classes, and enumerations, highlighting their uses and advantages. The document provides code examples to illustrate concepts such as calculating averages with arrays and the implementation of functions.

Uploaded by

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

UNIT 3

This document covers arrays and functions in C programming, explaining scalar and aggregate types, including 1D, 2D, and multidimensional arrays. It discusses string handling, function definitions, recursion, storage classes, and enumerations, highlighting their uses and advantages. The document provides code examples to illustrate concepts such as calculating averages with arrays and the implementation of functions.

Uploaded by

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

UNIT 3 - ARRAYS AND

FUNCTIONS
1D Arrays– 2D Arrays – Multidimensional Arrays –
Strings – String handling functions – Functions –
Recursion – Array as function arguments – Storage
Classes – Enumerations.
Arrays
Scalar Variables
A scalar variable is like a simple container that holds
one single value. When you declare a variable, like int
n; or float price;, you're creating a scalar variable. This
variable holds one value at a time, and it is atomic,
meaning it can't be split into smaller values. For
instance:
int n; can store just one integer value.
float price; can store just one floating-point value.
Aggregate Types and Arrays
In contrast, aggregate types are more complex structures that
can hold multiple values that are related in some way. This
allows us to work with groups of data. One example of an
aggregate type is an array.
An array is a data structure that can store multiple values of the
same type, arranged in a specific order. This makes it useful for
handling lots of related data without having to create separate
variables for each value. Arrays have two key properties:
Data type: All values in an array must be of the same type, like
all integers or all floats.
Size: The number of elements (or items) in the array is fixed
when the array is created.
In C, you declare an array like this:
int numbers[5]; // This array can store 5 integers
Each item in the array is accessed by an index, which starts at 0.
So, numbers[0] is the first element, numbers[1] is the second,
and so on.
Use of an Arrays
•Arrays are especially useful when you need to work with a
lot of values.
•For instance, if you want to write a program that prints
numbers in reverse order, doing so with individual variables
(like int v1, v2, v3;) would only work for a small, fixed
number of values.
•But if you need to handle 100 values, an array makes it
possible to store and access each one by its index without
writing separate variables for each.
Example: Calculating an Average

#include <stdio.h>
int main()
{
int n, count, s = 0, num;
float avg;
printf("How many numbers? ");
scanf("%d", &n);

for (count = 1; count <= n; ++count) {


printf("Enter the number: ");
scanf("%d", &num);
s += num; // Sum of numbers
}

avg = (float)s / n; // Calculate average


printf("Average is %f", avg);
return 0;
}
Solution with Arrays

#include <stdio.h> // Calculate the average


int main() { int sum = 0;
int n, i; for (i = 0; i < n; i++) {
printf("How many numbers? "); sum += numbers[i];
scanf("%d", &n); }
float avg = (float)sum / n;
int numbers[n]; // Declare an array to store n printf("Average is %f\n", avg);
numbers
// Print numbers greater than average
for (i = 0; i < n; i++) { printf("Numbers greater than the average:
printf("Enter the number: "); ");
scanf("%d", &numbers[i]); for (i = 0; i < n; i++) {
} if (numbers[i] > avg) {
printf("%d ", numbers[i]);
}
}
return 0;
}
Benefits of Arrays provide:
1. Efficient storage for multiple items.
2. Easy access through indices.
3. Reduced redundancy with loops.
4. Flexibility for variable-sized data.
5. Better memory management for organized data handling.
Multidimensional Arrays:
 More than one dimension
Declaration of a Two-dimensional Array
data_type array_name[size1][size2];
Eg. int arr[8][8];
#include <stdio.h>
int main() {
int arr[2][3] = { printf("\n");
{1, 2, 3}, }
{4, 5, 6}
}; return 0;
}
// Printing the 2D array
printf("2D Array Elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
Declaration of a Three-dimensional Array
data_type array_name[size1][size2][size3]
Eg. int non_cube[2][6][8];

#include <stdio.h> printf("\n");


}
int main() { printf("\n");
int arr[2][2][3] = { }
{{1, 2, 3}, {4, 5, 6}},
{{7, 8, 9}, {10, 11, 12}} return 0;
}; }

// Printing the 3D array


printf("3D Array Elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
printf("%d ", arr[i][j][k]);
}
Strings
A string is essentially an array of characters terminated by a null character (\0).
Declaring and Initializing Strings:
1. Using Character Arrays:
char str1[] = "Hello"; // Implicitly adds '\0' at the end
char str2[6] = "Hello"; // Explicit size, must include space for '\0'
char str3[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Manual null termination
2. Using Pointers:
char *str = "Hello"; // Pointer to string literal (read-only)
String Input and Output:
Using scanf()
char name[20];
scanf("%s", name); // Reads a word (stops at space)
Using gets() (Unsafe, use fgets() instead)
// gets(name); // Dangerous, avoid using it
fgets(name, sizeof(name), stdin); // Safer alternative
Using printf() and puts():
printf("%s\n", name); // Prints string
puts(name); // Prints with a newline
String handling functions

Function Description
Returns the length (excluding \
strlen(str)
0).
strcpy(dest, src) Copies src to dest.
strncpy(dest, src, n) Copies first n characters.
Compares two strings (0 if
strcmp(str1, str2)
equal).
strcat(dest, src) Concatenates src to dest.
strncat(dest, src, n) Appends first n characters.
Functions
•A function in C is a block of code designed to perform a specific
task.
•Instead of repeating the same code in multiple places, we create
a function and call it whenever needed. This makes programs
organized, reusable, and easy to understand.
Use of Functions:
Functions provide several benefits:
Code Reusability – Write once, use many times.
Improved Readability – Break a large program into smaller,
manageable parts.
Easy Debugging – Fixing errors in a function is easier than
searching through an entire program.
Data Protection – Variables inside a function (local variables) are
not accessible outside it.
Teamwork – In large projects, different programmers can work on
different functions
Types of Functions
1.Library Functions – Predefined in C (e.g., printf(), scanf(),
strlen()).
2.User-Defined Functions – Created by programmers for specific
tasks.

Parts of a Function:
A function in C has three main parts:
1. Function Prototype (Declaration)
Tells the compiler about the function before using it.
Written at the beginning of the program.
eg : int add(int, int);
2. Function Definition
Contains the actual code to perform the task.
Example:
int add(int a, int b) {
return a + b;
}

3.Function Call
Used to execute the function
Example:
int result = add(5, 3);
printf("%d", result); // Output: 8

Function Prototype
Example
#include <stdio.h>
printf("Sum: %d\n", sum);
return 0;
// Function Prototype
}
int add(int, int);
// Function Definition
int main() {
int add(int a, int b) {
int sum = add(10, 20); // Function Call
return a + b;
}
Recursion
•Recursion in C programming is a technique where a function calls itself to solve
smaller instances of a problem.
•This is commonly used for problems that can be divided into sub-problems of the
same type, like calculating factorials, Fibonacci series, or solving mathematical puzzles

The condition under which the The part of the function where it calls
recursion stops. Without a base itself to work on a smaller or simpler
case, the recursion will run infinitely, problem.
leading to a stack overflow.
Syntax Example
return_type function_name(parameters) #include <stdio.h>
{
if (base_condition) int factorial(int n) {
{ if (n == 0) { // Base case
// Base case logic return 1;
return base_case_value; } else { // Recursive case
} else return n * factorial(n - 1);
{ }
// Recursive case logic }
return
function_name(modified_parameters); int main() {
} int num = 5;
} printf("Factorial of %d is %d\n", num,
factorial(num));
return 0;
}
Advantages of Recursion
•Simplifies code for problems like tree traversals, divide-and-conquer algorithms, and
combinatorial problems.
•Often provides a cleaner and more intuitive solution.

Disadvantages of Recursion
•Consumes more memory due to the function call stack.
•Can be slower than iterative solutions for certain problems.
•Risk of stack overflow for deep recursions.

STORAGE CLASSES:
Storage classes define the scope, lifetime, visibility, and memory location of variables
or functions. These attributes determine how and where variables are stored,
initialized, and accessed in a program.
Types of Storage Classes in C
There are four main storage classes in C:
•Automatic (auto)
•Register (register)
•Static (static)
•External (extern)
1. Automatic (auto)
•Default storage class for local variables (inside functions).
•Exists only inside the function where it is declared.
•Stored in memory (RAM).
•Destroyed after the function ends.
•Cannot be accessed outside the function.
Example:
#include <stdio.h>

void func() {
auto int x = 10; // `auto` is optional
printf("%d\n", x);
}

int main() {
func();
// printf("%d", x); // ❌ Error: x is not accessible here
return 0;
}
2. Register (register)
•Stored in CPU registers instead of RAM (faster access).
•Used for frequently accessed variables (like loop counters).
•Cannot take the address (&) because it may not be in memory.
•Limited size (depends on CPU architecture).
Example:
#include <stdio.h>

int main() {
register int i; // Requests to store `i` in a CPU register
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
return 0;
}
3. Static (static)
•Retains its value between function calls.
•Stored in data segment (not stack).
•Can be used for:
1.Local static variables (scope inside function, retains value).
2.Global static variables (scope limited to the file).

Example: Local Static Variable; Example: Global Static Variable:


#include <stdio.h> #include <stdio.h>

void counter() { static int num = 10; // Accessible only


static int count = 0; // Retains value between calls in this file
count++;
printf("Count: %d\n", count); void display() {
} printf("Num: %d\n", num);
}
int main() {
counter(); int main() {
counter(); display();
counter(); return 0;
return 0; }
}
4. External (extern)
•Used to share variables between multiple files.
•Declares a global variable without defining it (defined elsewhere).
•Stored in memory (RAM).
Example: Using extern Across Files
File 1: file1.c
#include <stdio.h>

int num = 100; // Global variable definition

void display() {
printf("Num: %d\n", num);
}

File 2: file2.c
#include <stdio.h>

extern int num; // Variable declared but not defined

int main() {
printf("Num: %d\n", num); // Access `num` from file1.c
return 0;
}
Storage
Storage Class Scope Lifetime Use Case
Location
Function Default for local
auto Local RAM (stack)
execution variables
Fast access
Function CPU Register (if (loop counters,
register Local
execution available) frequently used
variables)

Retains value
Entire program
static (local) Local Data segment between
execution
function calls

Entire program Limits variable


static (global) File scope Data segment
execution to the same file

Share variables
Entire program RAM (global
extern Global across multiple
execution area)
files
Enumerations (enum):
An enumeration in C is a user-defined data type that allows assigning names to integer
values for better readability and maintainability.
Improves Code Readability – Instead of using magic numbers, you use meaningful
names.
Makes Debugging Easier – Named constants make debugging simpler.
Enhances Maintainability – Changing values in one place updates the entire code.
Syntax of enum
enum enum_name { value1, value2, value3, ... };
The enum_name is optional.
The values are automatically assigned integer constants starting from 0 unless specified.
Example:
#include <stdio.h>

enum Week { SUN, MON, TUE, WED, THU, FRI, SAT };

int main() {
enum Week today;
today = WED;
printf("Value of today: %d\n", today);
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy