assignment of c programming
assignment of c programming
Assignment-3
For example:
int myArray[5]; // Declares an integer array named
myArray with 5 elements
Initialisation:
int main() {
// Declare and initialize an array of integers
int myArray[5] = {1, 2, 3, 4, 5};
return 0;}
Sri Valli .K 2024-B-17122006A B-tech Divison B
Assignment 3 Btech section = B
Output Explanation
When you run this program, it will display the initial values
of myArray, followed by the updated values after modifying one of
its elements. This illustrates how to effectively work with one-
dimensional arrays in C.
Example C Program:
Here’s a simple C program that demonstrates how to read and print
all elements of an array using a for loop
#include <stdio.h>
int main() {
int n, i;
return 0;
Explanation of the Code:
• The program starts by including the standard input-output
library.
• It prompts the user to enter the number of elements they want
to store in the array.
• An integer array arr is declared with size n.
• A for loop is used to read n integers from user input and store
them in arr.
• Another for loop then iterates through arr to print each
element.
Output Example:
If a user enters 5 as the number of elements and then
inputs 10, 20, 30, 40, and 50, the output will be
Array elements are:
10
20
30
40
50
This program effectively demonstrates how to traverse a one-
dimensional array using loops in C.
int main() {
// Declare and initialize a one-dimensional array
int numbers[] = {10, 20, 30, 40, 50};
int length = sizeof(numbers) / sizeof(numbers[0]); //
Calculate the number of elements in the array
6
int k = 0;
do {
printf("Element at index %d: %d\n", k, numbers[k]);
k++;
} while (k < length);
return 0;
}
Explanation of the Program
1. Include Header Files
#include <stdio.h>
The for loop iterates over each index of the array from 0 to length
- 1, printing each element.
5. Traverse Using a While Loop
c
int j = 0;
Sri Valli .K 2024-B-17122006A B-tech Divison B
Assignment 3 Btech section = B
The while loop achieves the same result but uses a different
structure. It continues until j is no longer less than length.
6. Traverse Using a Do-While Loop
c
int k = 0;
do {
printf("Element at index %d: %d\n", k,
numbers[k]);
k++;
} while (k < length);
The do-while loop ensures that the body executes at least once
before checking the condition.
Conclusion
This program effectively demonstrates how to traverse a one-
dimensional array in C using different types of loops. Each method
has its use cases depending on specific programming needs. Feel
free to modify the values in the array or add more elements to see
how it works with different data!
Ans:
Traversal Mechanism:
• The outer loop typically iterates over the rows of the array,
while the inner loop iterates over the columns within each row.
This structure allows you to access every element in a
systematic manner.
• For example, if you have a 2D array defined as array[row]
[column], you can use nested loops to traverse it like this:
Efficiency:
• Each iteration of the outer loop triggers a complete cycle of
the inner loop. If there are m rows and n columns, the total
number of iterations will be m×n
• m×n, making it efficient for processing all elements.
C Program to Traverse a 2D Array and Calculate the Sum
Below is a simple C program that demonstrates how to traverse a
2D array and calculate the sum of all its elements.
c
#include <stdio.h>
int main() {
int rows, columns;
int array[rows][columns];
int sum = 0;
return 0;
}
Explanation:
1. Input Dimensions: The program first prompts the user to
input the number of rows and columns.
2. Array Declaration: It declares a 2D array based on user
input.
3. Element Input: The program uses nested loops to fill the
array with user-provided values.
4. Sum Calculation: Another set of nested loops traverses the
array to compute the total sum of its elements.
5. Output: Finally, it prints out the computed sum.
This program effectively illustrates how nested loops work in
conjunction with multidimensional arrays to perform operations
such as summation.
10
Ans:
Function prototypes, data types in function declarations, and the
methods of passing arguments are foundational concepts in
programming, particularly in languages like C. Understanding these
elements is crucial for writing efficient and error-free code.
Importance of Function Prototypes
Function prototypes serve as declarations that inform the compiler
about a function's name, return type, and parameters before the
function is defined. This is essential for several reasons:
• Error Checking: Prototypes allow the compiler to verify that
functions are called with the correct number and types of
arguments. If a mismatch occurs, the compiler generates an
error, preventing potential runtime issues12.
• Modularity: They enable modular programming by allowing
functions to be defined in separate files. This separation
facilitates easier maintenance and organisation of code12.
• Type Safety: By specifying data types in prototypes,
programmers can avoid type-related errors that may arise
during execution. For example, if a function expects an
integer but receives a float, the compiler can catch this
mistake early24.
Example of a Function Prototype
c
float calculateArea(float length, float width);
11
This declaration indicates that add takes two integers as input and
returns an integer result.
Passing Arguments: By Value vs. By Reference
When it comes to passing arguments to functions, two primary
methods are used: by value and by reference.
Passing by Value
When arguments are passed by value, copies of the actual values
are made. This means that modifications within the function do not
affect the original variables.
• Advantages:
• Simplicity: It is straightforward and avoids side effects.
• Safety: The original data remains unchanged15.
• Disadvantages:
• Performance: For large data structures (like arrays or
structs), copying can be inefficient.
• Memory Usage: More memory is consumed due to
duplicate data.
Example of Passing by Value
Sri Valli .K 2024-B-17122006A B-tech Divison B
Assignment 3 Btech section = B
12
int main() {
int x = 5;
increment(x); // x remains 5
}
int main() {
int x = 5;
increment(&x); // x becomes 6
}
13
Conclusion
Function prototypes are vital for ensuring type safety and
modularity in programming. The specification of data types within
these prototypes helps prevent errors during compilation.
Moreover, understanding how arguments are passed—by value or
by reference—enables developers to write more efficient and
effective code while managing memory usage appropriately. These
concepts form the bedrock of robust programming practices in
languages like C.
Example:
2. Returning Arrays
14
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size = 5;
int* myArray = createArray(size); // Get the
pointer to the array
printf("Array Elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}
printf("\n");
15
Example:
#include <stdio.h>
int* createStaticArray() {
static int array[5]; // Static array
for (int i = 0; i < 5; i++) {
array[i] = i * 3; // Initialize with
multiples of three
}
return array; // Return pointer to the static
array
}
int main() {
int* myArray = createStaticArray(); // Get the
pointer to the static array
printf("Static Array Elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", myArray[i]);
}
printf("\n");
16
Example:
#include <stdio.h>
typedef struct {
int arr[5];
} ArrayStruct;
ArrayStruct createArrayStruct() {
ArrayStruct myStruct;
for (int i = 0; i < 5; i++) {
myStruct.arr[i] = i * 4; // Initialize
with multiples of four
}
return myStruct; // Return the structure
containing the array
}
int main() {
ArrayStruct myArrayStruct =
createArrayStruct(); // Get the structure
containing the array
printf("Structure Array Elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", myArrayStruct.arr[i]);
}
printf("\n");
return 0;
}
17
Conclusion
Returning arrays from functions in C requires careful management
of memory and understanding of pointers. Dynamic memory
allocation allows flexibility but necessitates manual management
using malloc() and free(). Static arrays provide simplicity without
needing explicit deallocation but have limitations regarding their
lifecycle. Structures offer a clean way to encapsulate arrays while
avoiding some complexities associated with pointers. Each
method has its use cases depending on the requirements of your
program.