0% found this document useful (0 votes)
89 views15 pages

C Programs for Arrays, Structures, and Pointers

The document contains a series of C programming tasks, including array manipulation, pointer arithmetic, structure usage, and file handling. Each task is accompanied by a complete code example demonstrating the required functionality, such as calculating sums, sorting arrays, and managing student records. The document serves as a comprehensive guide for practicing various programming concepts in C.
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)
89 views15 pages

C Programs for Arrays, Structures, and Pointers

The document contains a series of C programming tasks, including array manipulation, pointer arithmetic, structure usage, and file handling. Each task is accompanied by a complete code example demonstrating the required functionality, such as calculating sums, sorting arrays, and managing student records. The document serves as a comprehensive guide for practicing various programming concepts in C.
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

1. Write a C program to add all the integer elements present in an array of size “n”.

#include <stdio.h>

int main() {
int n, sum = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; ++i) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum of array elements: %d\n", sum);
return 0;
}

2. Write a C program to store the elements in two dimensional array


#include <stdio.h>
int main() {
int rows = 2;
int columns = 2;
int A[rows][columns];
printf("Enter elements for the 2D array (%dx%d):\n", rows, columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &A[i][j]);
}
}
printf("\nThe 2D array elements are:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d\t", A[i][j]);
}
printf("\n");
}
return 0;
}

3. Write a C program to illustrate pointer arithmetic with an example.

#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers;
printf("Array elements using pointer arithmetic: ");
for (int i = 0; i < 5; ++i) {
printf("%d ", *ptr);
}
printf("\n");
return 0;

4. Write a C program to access array elements using pointer.


#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers;
printf("Array elements accessed using a pointer: ");
for (int i = 0; i < 5; ++i) {
printf("%d ", *(ptr + i));
}\
printf("\n");
return 0; }
5. Write a C program which records the following details during the last 50 years (100 records):
Region name, rainfall in mm and duration. Display the region with highest rainfall and lengthy
duration.
#include <stdio.h>
struct Region {
char name[50];
float rainfall;
int duration;
};
int main() {
const int numRecords = 100;
struct Region records[numRecords];
for (int i = 0; i < numRecords; ++i) {
printf("Enter details for Record %d:\n", i + 1);
printf("Region Name: ");
scanf("%s", records[i].name);
printf("Rainfall (mm): ");
scanf("%f", &records[i].rainfall);
printf("Duration (years): ");
scanf("%d", &records[i].duration);
printf("\n");
}
int maxIndex = 0;
for (int i = 1; i < numRecords; ++i) {
if (records[i].rainfall > records[maxIndex].rainfall ||
(records[i].rainfall == records[maxIndex].rainfall &&
records[i].duration > records[maxIndex].duration)) {
maxIndex = i;
}
}
printf("\nRegion with the highest rainfall and lengthy duration:\n");
printf("Region Name: %s\n", records[maxIndex].name);
printf("Rainfall: %.2f mm\n", records[maxIndex].rainfall);
printf("Duration: %d years\n", records[maxIndex].duration);

return 0;
}

6. Write a C program for swapping of two numbers by passing an address to the function.
#include <stdio.h>
void swapNumbers(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1, num2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Original numbers: %d, %d\n", num1, num2);
swapNumbers(&num1, &num2);
printf("Swapped numbers: %d, %d\n", num1, num2);
return 0;
}

7. Develop a C program to get 5 students information like Rollno, Name and marks using structure
and display the details.
#include <stdio.h>
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
const int numStudents = 2;
struct Student students[numStudents];
for (int i = 0; i < numStudents; ++i) {
printf("Enter details for Student %d:\n", i + 1);
printf("Roll No: ");
scanf("%d", &students[i].rollNo);
printf("Name: ");
scanf("%s", students[i].name);
printf("Marks: ");
scanf("%f", &students[i].marks);
printf("\n");
}
printf("Student details:\n");
for (int i = 0; i < numStudents; ++i) {
printf("Student %d:\n", i + 1);
printf("Roll No: %d\n", students[i].rollNo);
printf("Name: %s\n", students[i].name);
printf("Marks: %.2f\n", students[i].marks);
printf("\n");
}

return 0;
}

8. Write a C program to add two numbers using call-by-value.


#include <stdio.h>
int addNumbers(int a, int b) {
return a + b;
}
int main() {
int num1, num2, sum;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum = addNumbers(num1, num2);
printf("Sum of %d and %d is: %d\n", num1, num2, sum);
return 0;
}

9. Develop a C program which reads name, register number, physics mark, chemistry mark and
mathematics mark using a structure. Calculate the Engineering cut-off using structures.
#include <stdio.h>
struct Student {
char name[50];
int regNumber;
float physicsMark;
float chemistryMark;
float mathMark;
};
float calculateCutOff(struct Student student) {
return (([Link] + [Link]) / 2.0)+[Link] ;
}
int main() {
struct Student student;
printf("Enter student details:\n");
printf("Name: ");
scanf("%s", [Link]);
printf("Register Number: ");
scanf("%d", &[Link]);
printf("Physics Mark: ");
scanf("%f", &[Link]);
printf("Chemistry Mark: ");
scanf("%f", &[Link]);
printf("Mathematics Mark: ");
scanf("%f", &[Link]);
float cutOff = calculateCutOff(student);
printf("\nEngineering Cut-off for %s (Reg No: %d): %.2f\n", [Link], [Link],
cutOff);

return 0;
}

10. Develop a C program to create struct employee that contains members employee name and
address. Store the address of the employee into a separate structure and nest the struct address
into the structure employee.
#include <stdio.h>
struct Address {
char street[50];
char city[50];
char state[50];
int zipCode[15];
};
struct Employee {
char name[50];
struct Address address;
};
int main() {
struct Employee employee;
printf("Enter employee details:\n");
printf("Name: ");
scanf("%s", [Link]);

printf("Address details:\n");
printf("Street: ");
scanf("%s", [Link]);
printf("City: ");
scanf("%s", [Link]);
printf("State: ");
scanf("%s", [Link]);
printf("Zip Code: ");
scanf("%s", [Link]);

printf("\nEmployee Details:\n");
printf("Name: %s\n", [Link]);
printf("Address: %s, %s, %s, %s\n", [Link], [Link],
[Link], [Link]);

return 0;
}

11. Write a C program which prints only the odd positioned alphabets from the given string
“ELEPHANT” using array of characters
#include <stdio.h>
int main() {
char str[] = "ELEPHANT";
int length = 0;
while (str[length] != '\0') {
length++;
}
printf("Odd-positioned Alphabets: ");
for (int i = 0; i < length; i += 2) {
printf("%c ", str[i]);
}
printf("\n");
return 0;
}

12. Identify the element 8 and its index from the given array {10, 2, 8, 5, 17} using linear search.
#include <stdio.h>
int linearSearch(int arr[], int size, int target, int *index) {
for (int i = 0; i < size; ++i) {
if (arr[i] == target) {
*index = i;
return 1;
}
}
return 0;
}

int main() {
int arr[] = {10, 2, 8, 5, 17};
int target = 8;
int index;
int found = linearSearch(arr, sizeof(arr) / sizeof(arr[0]), target, &index);

if (found) {
printf("Element %d found at index %d.\n", target, index);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;

13. Write a C program which accepts two strings of equal length and clubs them together using the
following pattern. String1: abcd, String2: 1234, output: a1b2c3d4
#include <stdio.h>
#include <string.h>
int main() {
char string1[50], string2[50], result[100];
printf("Enter the first string: ");
scanf("%s", string1);
printf("Enter the second string: ");
scanf("%s", string2);
if (strlen(string1) != strlen(string2)) {
printf("Error: Strings must have equal length.\n");
return 1;
}
int index = 0;
for (int i = 0; i < strlen(string1); ++i) {
result[index++] = string1[i];
result[index++] = string2[i];
}
result[index] = '\0';
printf("Clubbed String: %s\n", result);
return 0;
}

14. Write a C program to calculate area of the square using user- defined function.
#include <stdio.h>
float calculateSquareArea(float side) {
return side * side;
}
int main() {
float side, area;
printf("Enter the side length of the square: ");
scanf("%f", &side);
area = calculateSquareArea(side);
printf("Area of the square with side %.2f is: %.2f\n", side, area);
return 0;
}

15. Given different prices of a vegetable which is varying through the day (from morning to
evening), find out the best buy price and sell price for the maximum profit. Eg. For the prices [33,
35, 28, 36, 39, 25, 22, 31], best buy is at 28 and best sell is at 39
#include <stdio.h>
void findBestBuySellPrices(int prices[], int n, int *bestBuy, int *bestSell) {
if (n < 2) {
printf("Insufficient prices to calculate profit.\n");
return;
}
*bestBuy = prices[0];
*bestSell = prices[1];
int maxProfit = *bestSell - *bestBuy;
for (int i = 1; i < n; ++i) {
int currentProfit = prices[i] - *bestBuy;
if (currentProfit > maxProfit) {
*bestSell = prices[i];
maxProfit = currentProfit;
}
if (prices[i] < *bestBuy) {
*bestBuy = prices[i];
}}}
int main() {
int prices[] = {33, 35, 28, 36, 39, 25, 22, 31};
int n = sizeof(prices) / sizeof(prices[0]);
int bestBuy, bestSell;
findBestBuySellPrices(prices, n, &bestBuy, &bestSell);
if (bestBuy < bestSell) {
printf("Best Buy Price: %d\n", bestBuy);
printf("Best Sell Price: %d\n", bestSell);
printf("Maximum Profit: %d\n", bestSell - bestBuy);
} else {
printf("No profitable buying and selling opportunities.\n");
}
return 0;
}
16. Write a C program to sort the given array ‘a’ using insertion sort. a[5]={4,3,5,6,7}
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int a[] = {4, 3, 5, 6, 7};
int n = sizeof(a) / sizeof(a[0]);
printf("Original array: ");
printArray(a, n);
insertionSort(a, n);
printf("Sorted array: ");
printArray(a, n);
return 0;
}
17. Write a C program to find the factorial of a number “8” using recursion.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}}
int main() {
int number = 8;
printf("Factorial of %d is: %d\n", number, factorial(number));
return 0;
}

18. Write a C program that takes input for a base number - 8 and an exponent 2, and calculate the
power of the base number using recursion.
#include <stdio.h>
double power(int base, int exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power(base, exponent - 1); // Recursive case
}}
int main() {
int base, exponent;
printf("Enter the base number: ");
scanf("%d", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
printf("%d^%d is: %.0f\n", base, exponent, power(base, exponent));
return 0;
}
19. Create a C program that prompt the user to get input, calculates the sum of n numbers stored
in a file using sequentially access method.
#include <stdio.h>
int main() {
FILE *file;
int n, number, sum = 0;
printf("Enter the number of elements (n): ");
scanf("%d", &n);
file = fopen("[Link]", "r");
if (file == NULL) {
perror("Error opening the file");
return 1;
}
for (int i = 0; i < n; ++i) {
// Read each number from the file
if (fscanf(file, "%d", &number) == 1) {
sum += number;
} else {
printf("Error reading number from the file.\n");
fclose(file);
return 1;
}}
fclose(file);
printf("Sum of the first %d numbers in the file: %d\n", n, sum);
return 0;
}

20. Develop a C program that performs the transaction processing using random access files.
(notes)
21. Develop a C program that writes the data 'I Love India' to a file using random access file
operations. After writing the data, display the position of the file pointer in the file.
#include <stdio.h>
int main() {
FILE *file;
char data[] = "I Love India";
file = fopen("random_access_file.txt", "wb+");
if (file == NULL) {
perror("Error opening the file");
return 1;
}
fwrite(data, sizeof(char), sizeof(data) - 1, file);
long currentPosition = ftell(file);
printf("Position of the file pointer after writing: %ld\n", currentPosition);
fclose(file);
return 0;
}

Common questions

Powered by AI

Swapping two integers in C can be effectively achieved through the use of pointers in a function. The method involves writing a function that accepts pointers to two integers and swaps their values using a temporary variable. This approach leverages the direct memory access provided by pointers, allowing changes made within the function to affect the original variables. By passing the addresses of the integers to be swapped, the function can directly alter the memory locations of the values, thus swapping them outside the local function scope .

In C, structures can be used to store and manipulate records by defining a structure type containing fields for each piece of data required, and then creating instances of this structure to represent records. An example application involves managing student records: define a structure `Student` with fields for roll number, name, and marks. Populate an array of `Student` structures with data and use loops to process or display this data. This allows for organized storage and easy access of related data characteristics, essential for applications like managing databases, complex data processing, or communicating data sets within memory-limited environments .

Using structures in C allows bundling of related data, facilitating organized storage and complex computations such as calculating an Engineering cut-off for student marks. Define a `Student` structure containing fields for student name, registration number, and marks for physics, chemistry, and math. Compute the cut-off by applying a formula using the structure fields, treating physics and chemistry marks as components of average and math as a standalone addition. Utilizing structures simplifies data management, enhancing readability, and enabling direct manipulation and calculations of complex operations on structured data sets .

To calculate the sum of an array of integers in C, you can implement a program that initializes an array, iterates through its elements, and accumulates their values in a sum variable. Key components include declaring an integer array, using a loop to iterate through the array elements, and using a sum variable to keep track of the accumulated sum. A typical implementation utilizes a for loop for iteration and the += operator to add each element to the sum variable .

The insertion sort algorithm in C sorts an array by selecting one element at a time and inserting it into its correct position within the already sorted part of the array. The algorithm involves iterating over the elements of the array starting from the second element. For each element, compare it with the elements before it, then shift any elements larger than it to the right, creating the correct position to insert the current element. This process continues until all elements are placed in sorted order, achieving in-place sorting with a time complexity of O(n^2).

Pointer arithmetic in C allows for direct manipulation of memory addresses. It is demonstrated by using a pointer to traverse and access elements of an array. Operations include incrementing or decrementing a pointer, which moves it to the next or previous memory location as defined by the data type size. Additional operations involve adding or subtracting integers to or from pointers to access different array elements. The pointer arithmetic accesses array elements in sequence, demonstrating how pointers provide a powerful means for efficient memory traversal and manipulation .

The primary components of a C program that merges two strings of equal length using an interleaving pattern include accepting input strings, checking for equal length, and then iterating over the strings to interleave characters into a result array. Use a loop to alternate appending characters from each string to the result. Utilize standard string functions such as `strlen` to determine and verify string lengths. This approach efficiently combines characters from both strings into a single interleaved sequence by maintaining an index to track and append elements to the resultant output .

To identify the best buy and sell prices for maximum profit given a series of daily vegetable prices in C, you can utilize an algorithm that iteratively checks potential profits between pairs of prices. Initialize variables to track the best buy and sell prices, and iterate through the array of prices once. For each price, calculate the potential profit by subtracting the current minimum price seen (best buy) from the current price (potential sell). If this profit exceeds the maximum profit calculated so far, update the best sell price and the maximum profit. Adjust the best buy price whenever a new lower price is encountered. This approach efficiently finds the maximum profit using a single traversal of the array .

File handling in C allows programs to read, write, and manipulate files on a storage device. To calculate the sum of numbers stored in a file, a program can open a file for reading, use a sequential access method to read numbers one by one into memory, and accumulate these values using a loop. Proper functions like `fopen` for opening the file, `fscanf` for formatted input, and arithmetic operations to maintain a running total of read values are critical. Accurate error handling is also necessary when opening or reading files to ensure robust execution .

Random access files in C enable direct access to any part of a file without the need to read sequentially through data, allowing you to read or write starting from any point. This is accomplished using file functions such as `fseek` to move the file pointer to a desired location in the file. An advantage of random access is improved performance for applications needing frequent updates or reads of scattered data points, as compared to sequential access methods which require processing data linearly, often involving impractical amounts of reading or writing for large or complex data tasks .

You might also like