docs
docs
Program
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
printf("Sum: %d\n", sum);
return 0;
}
Output
Sum: 15
Simple Explanation:
1. Array Definition:
• We define an array arr[] containing 5 numbers: {1, 2, 3, 4, 5}.
2. Sum Calculation:
• We start with a sum of 0 (int sum = 0;).
• Then, we use a for loop to go through each number in the array. For each number,
we add it to the sum.
3. Printing the Result:
• Once the loop is done, the sum (which is now 15) is printed out using printf.
What Happens:
• The program adds all the numbers in the array (1 + 2 + 3 + 4 + 5 = 15), and then
prints "Sum: 15" on the screen.
Question 2
A structure in C is a user-defined data type that allows you to group different types of variables
under one name.
#include <stdio.h>
struct Book {
char title[100];
char author[100];
float price;
int year;
};
int main() {
struct Book book1 = {"C Programming", "Dennis Ritchie", 29.99, 1978};
printf("Title: %s\n", book1.title);
printf("Author: %s\n", book1.author);
printf("Price: %.2f\n", book1.price);
printf("Year: %d\n", book1.year);
return 0;
}
Output
Title: C Programming
Author: Dennis Ritchie
Price: 29.99
Year: 1978
Explanation:
1. Defining the Structure:
• struct Book defines a structure named Book that has 4 members:
• title: A string for the book's title.
• author: A string for the book's author.
• price: A floating-point number for the book's price.
• year: An integer for the year of publication.
2. Declaring a Structure Variable:
• struct Book book1; declares a variable book1 of type Book.
• We can assign values to the members directly when initializing, as shown in the
book1 initialization.
3. Accessing Structure Members:
• We access the individual members of the structure using the dot (.) operator, like
book1.title, book1.author, etc.
Question 3
In C, functions can return different types of values. The return type of a function indicates what
kind of value the function will give back after it finishes. Here's a simple explanation of the
common return types:
1. void:
A pointer in C is a variable that stores the memory address of another variable. Instead of holding
a direct value like an integer or a character, a pointer holds the address of where that value is stored
in memory.
Pointers allow you to work with memory addresses, which is powerful for passing large data to
functions, manipulating data directly, and allocating memory dynamically.
• They are essential for efficient memory management and help in managing resources like
arrays, structures, and dynamic memory.