Warning Disclaimer Notice:
The below answers and discussions are directly prepared by copy-paste from www.google.com, Googole AI Overview, https://gemini.google.com/app , https://chatgpt.com/,etc,
These are only for understanding to improve the concept only; not for answers. We have not checked these clearly. Some mistakes may be happened. We are not responsible for any wrong information and answers. Please check yourself, yourselves and discuss with your expert teachers for the final approval or accepted the answers.
Example 6.1 A C program to declare and display array elements.
Answer:
#include<stdio.h>
int main()
{
int num[7] = {2,3,4,5,6,7,8};
printf("\n Initial values of the first array elements are:
");
for(int index=0; index<7; index++)
printf("%d ", num[index]);
char state[5] = {'A', 'S', 'S', 'A', 'M'};
printf("\n Initial values of the second array elements are:
");
for(int index=0; index<5; index++)
printf("%c ", state[index]);
return 0;
}
MEANING
The provided C code
initializes an integer array num with seven elements and a character array state with five elements, then prints the
values of both arrays to the console.
The expected output
when this code is compiled and executed is:
Initial values of the first array elements
are: 2 3 4 5 6 7 8
Initial values of the second array elements
are: A S S A M
Code Analysis
·
#include<stdio.h>: This line includes the standard input/output library,
necessary for using functions like printf.
·
int main(): This is the main
function, the entry point of every C program.
·
int num[7] = {2,3,4,5,6,7,8};: This declares an integer array named num capable of holding 7 elements and
initializes it with the specified values.
·
printf("\n Initial values of the first array elements are:
");: This prints the
introductory text for the first array, including a newline character (\n) to move the cursor to the next line.
·
for(int index=0; index<7; index++): This is a for loop that iterates seven times
(from index 0 to 6).
·
printf("%d ", num[index]);: Inside the loop, this prints the integer
value of the current element in the num array, followed by a space.
·
char state[5] = {'A', 'S', 'S', 'A', 'M'};: This declares a character array named state capable of holding 5 elements and
initializes it with the given characters.
·
printf("\n Initial values of the second array elements are:
");: This prints the
introductory text for the second array, again using a newline character.
·
for(int index=0; index<5; index++): This for loop iterates five times (from index 0 to 4).
·
printf("%c ", state[index]);: Inside the loop, this prints the character
value of the current element in the state array, followed by a space.
·
return 0;: This indicates
successful execution and terminates the main function.
Example 6.2 A C program to take input to an array from the
keyboard.
Answer:
#include<stdio.h>
int main()
{
int num[7] = {2,3,4,5,6,7,8};
printf("\n Initial values of the array elements are:
");
for(int i=0; i<7; i++)
printf("%d ", num[i]);
printf("\n Taking fresh input to the array elements:
");
for(int i=0; i<7; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &num[i]);
}
printf("\n New array elements are: ");
for(int i=0; i<7; i++)
printf("%d ", num[i]);
return 0;
}
Meaning
The
provided C code is a complete and functional program. This code declares and
initializes an integer array named num with
seven elements.
Code
Explanation
1.
Initialization: The array num is initialized with values {2, 3, 4, 5, 6, 7, 8}.
2.
First Loop (Display Initial Values): A for loop
iterates from i = 0 to i = 6 (7
times) and prints the initial values of each array element.
3.
Second Loop (User Input): Another for loop prompts the user to enter a new
value for each of the seven elements. The scanf function
reads the user's input and stores it back into the array, overwriting the
initial values.
4.
Third Loop (Display New Values): A final for loop
prints the new values of the array elements that were entered by the
user.
Working Program
Here
is the program exactly as provided, which will compile and run correctly in a C
environment:
he
program is an interactive C program that first displays the initial values of
an array, then prompts the user to enter new values for each element, and
finally displays the updated array values. The exact output depends on the
values the user enters during the program's execution.
Here
is a step-by-step breakdown of the execution and a potential output example:
Program
Execution Steps
1.
Initialization and Initial Output: The program defines an integer array num with initial values {2, 3, 4, 5, 6, 7, 8} and prints them.
2.
User Input Loop: The program enters a loop where it asks the user to input
seven new integer values, one by one. The scanf function
reads these new values from standard input and overwrites the initial values in
the num array.
3.
Final Output: After all inputs are received, the program prints the newly
entered values.
Example Output
If
the user enters the numbers 10, 20, 30, 40, 50, 60, 70 when
prompted, the output will look like this:
Initial values of the array elements
are: 2 3 4 5 6 7 8
Taking fresh input to the array
elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Enter element 6: 60
Enter element 7: 70
New array elements are: 10 20 30 40
50 60 70
Note: The user's input is shown in a separate
line here for clarity. The program will pause after each "Enter element
X:" prompt, waiting for the user to type a number and press Enter.
Example 6.3 A
C program to find the summation of a series of numbers using an array.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle, sum=0;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
for(int i=0; i<totalEle; i++)
{
sum = sum + number[i];
}
printf("\n Summation is: %d", sum);
return 0;
}
MEANING
This C code calculates the sum of
user-entered numbers by first taking the total count, then looping to read each
number into an array, and finally looping again to add them up, printing the
final sum, effectively demonstrating basic array
handling and summation in C programming.
#include<stdio.h> // Includes the
Standard Input/Output library
int main() // Main function where program
execution begins
{
int number[20]; // Declares an array to hold up to 20 integers
int totalEle, sum=0; // Declares variables for total elements and sum
(initialized to 0)
// Prompts user for the number of elements they want to enter
printf("\n Enter total number of elements in the series: ");
scanf("%d", &totalEle); // Reads the integer input and
stores it in totalEle
// Informs the user that input for array elements is expected
printf("\n Taking input to the array elements: ");
// Loop to get input for each element
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d:
", (i+1) ); // Prompts for the specific element
scanf("%d", &number[i]); // Reads the element and stores
it in the array at index 'i'
}
// Loop to calculate the sum of all elements in the array
for(int i=0; i<totalEle; i++)
{
sum = sum + number[i]; // Adds the current array element to the running
sum
}
// Prints the final calculated sum
printf("\n Summation is: %d", sum);
return 0; // Indicates successful program execution
}
How it Works:
1.
#include<stdio.h>: Brings in functions like printf (to print)
and scanf (to read input).
2.
int
number[20];: Creates an array
named number that can store 20 integers.
3.
User
Input (totalEle): Asks the user how many numbers they want to sum and stores it
in totalEle.
4.
Input
Loop (for(int i=0;
i<totalEle; i++)):
1.
Runs totalEle times.
2.
In each iteration, it
prompts for an element and uses scanf("%d",
&number[i]); to store it in
the number array.
Summation
Loop (for(int i=0;
i<totalEle; i++)):
0.
Also runs totalEle times.
1.
sum = sum + number[i]; adds each element from the array to
the sum variable, as explained in source.
printf("\n
Summation is: %d", sum);: Displays the final total.
The output of this C
code is dynamic: it first prompts the user for the number of elements,
then for each element, and finally prints the sum of those elements, so the
exact output depends on user input; for example, if the user enters 3 and then 10, 20, 30, the output would
be Enter total number of
elements in the series: 3, Taking input to the array elements: Enter element 1: 10 Enter
element 2: 20 Enter element 3: 30, followed by Summation
is: 60.
Here's a sample
interaction showing the process:
Enter total number of elements in the series:
3
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Summation is: 60
Explanation:
1.
scanf("%d",
&totalEle);: Reads the total
number of elements (e.g., 3) from the user.
2.
for(int
i=0; i<totalEle; i++) (Input
Loop): Prompts for each
element and stores it in the number array.
1.
Enter element 1: 10
2.
Enter element 2: 20
3.
Enter element 3: 30
for(int
i=0; i<totalEle; i++) (Summation
Loop): Adds each element to
the sum variable (10 + 20 + 30 = 60).
printf("\n
Summation is: %d", sum);: Prints the final calculated sum, which is 60.
Example 6.3 A
C program to find the summation of a series of numbers using an array.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle, sum=0;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
for(int i=0; i<totalEle; i++)
{
sum = sum + number[i];
}
printf("\n Summation is: %d", sum);
return 0;
}
Quick Activity:
Modify the above C program to calculate the average of the numbers.
Answer: To calculate the average, we need to divide
the total sum by the count of elements. Since the average is often a decimal
value (e.g., the average of 5 and 10 is 7.5), we should use a float or double data type for the result.
Here is the modified C
program:
C
#include
<stdio.h>
int
main() {
int number[20];
int totalEle, sum = 0;
float average; // Use float to handle
decimal points
printf("Enter total number of elements
(max 20): ");
scanf("%d", &totalEle);
if (totalEle > 20 || totalEle <= 0) {
printf("Invalid input. Please
enter a number between 1 and 20.\n");
return 1;
}
for(int i = 0; i < totalEle; i++) {
printf("Enter element %d: ",
(i + 1));
scanf("%d", &number[i]);
sum = sum + number[i];
}
// Type casting 'sum' to float to ensure
floating-point division
average = (float)sum / totalEle;
printf("\n--- Results ---");
printf("\nSummation: %d", sum);
printf("\nAverage: %.2f\n", average); // %.2f limits
output to 2 decimal places
return 0;
}
Key Changes Explained
1.
Variable
Type: We added float average.
If we used an int, a result like 7.5 would be truncated to
7.
2.
Type
Casting: In the line average = (float)sum / totalEle;, we temporarily treat sum as a float. This is crucial in C because
dividing an integer by an integer always results in an integer (e.g., $15 / 2 =
7$). By casting, we get the precise answer ($15 / 2 = 7.5$).
3.
Format
Specifier: In printf, we used %.2f. The .2 tells the computer to
show only two digits after the decimal point for a cleaner look.
Logic Overview
The program follows a
linear flow to arrive at the final calculation:
|
Step |
Operation |
Formula |
|
1 |
Accumulate |
Sum = x1
+ x2 + ... + xn |
|
2 |
Count |
n = totalEle |
|
3 |
Divide |
Average = |
Would you like to see
how to modify this further to identify which numbers in your list are above the average?
The output depends entirely on the numbers you enter. Let’s walk through a concrete example to see exactly how the program behaves in your terminal.
Example Scenario
Assume you want to find the average of 3 numbers: 10, 15, and 22.
Terminal Interaction:
Enter total number of elements (max 20): 3
Entering input for the array elements:
Enter element 1: 10
Enter element 2: 15
Enter element 3: 22
--- Results ---
Summation: 47
Average: 15.67
Example 6.4 A
C program to find the largest number among a series of numbers using an array.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
int largest = number[0];
for(int i=1; i<totalEle; i++)
{
if ( number[i] > largest )
largest = number[i];
}
printf("\n Largest element is: %d", largest);
return 0;
}
Meaning:
This C code finds the largest number in
a user-defined series by taking inputs into an array, initializing a largest variable
with the first element, and then iterating through the rest of the array,
updating largest whenever a bigger element is found, finally printing
the result. It uses stdio.h for input/output (printf, scanf), declares an
array number[20] to store values, gets the count totalEle, loops to get
numbers, finds the max, and prints it.
#include<stdio.h> // Includes
standard input/output library [3]
int main() // Main function where
execution begins
{
int number[20]; // Declares an array to hold up to 20 integers
int totalEle; // Variable to store the
actual number of elements to enter
// Prompt user for the number of elements
printf("\n Enter total number of elements in the series: ");
scanf("%d", &totalEle); // Reads the count from the user
// Prompt for array elements
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++) // Loop to get each element
{
printf( "\n Enter element %d: ", (i+1) ); // Prompt for
specific element
scanf("%d", &number[i]); // Reads the element into the
array [7]
}
// Find the largest element
int largest = number[0]; // Assume the first element is the largest
for(int i=1; i<totalEle; i++) // Loop from the second element onwards
{
if ( number[i] > largest ) // If current element is greater than
current largest
largest = number[i]; // Update
largest
}
// Print the result
printf("\n Largest element is: %d", largest); // Displays the
found largest number
return 0; // Indicates successful execution [4]
}
Example Interactive
Session & Output:
Enter total number of elements in the series:
5
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 50
Enter element 3: 20
Enter element 4: 30
Enter element 5: 40
Largest element is: 50
Explanation:
1.
The program first asks
how many numbers you'll enter.
2.
Then, it prompts you
to enter each number one by one.
3.
After all numbers are
entered, it iterates through them, keeping track of the biggest one found so
far.
4.
Finally, it prints the
largest number you provided, illustrating how scanf captures user
input for processing.
Example 6.5 A
C program to find all the even numbers in a series of numbers.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
for(int i=0; i<totalEle; i++)
{
if ( number[i] %2 == 0 )
printf("\n %d is an even number", number[i]);
}
return 0;
}
Meaning
This C code takes user
input for a series of numbers (up to 20), then iterates through them, printing
only the numbers that are even (divisible by 2), demonstrating basic C
input/output, arrays, loops, and conditional statements. It prompts for the
count, reads elements into an array, and uses a for loop with an if condition (number[i] % 2 == 0) to identify and display even numbers.
Code Explanation:
1.
#include<stdio.h>: Includes the Standard Input/Output library for functions
like printf and scanf.
2.
int number[20];:
Declares an integer array number to store up to
20 elements.
3.
int totalEle;:
Declares an integer to store how many numbers the user wants to enter.
4.
Input
Section:
1.
Prompts the user
for totalEle.
2.
Uses a for loop (from i=0 to totalEle-1) to get each number and store it in number[i].
Processing
Section:
0.
Uses another for loop to check each entered number.
1.
if (number[i] % 2 == 0): Checks if the remainder when divided by 2 is 0 (meaning it's
even).
2.
If even, it prints the
number with the message " is an even number".
return 0;: Indicates successful
program execution.
Example Execution:
Enter total number of elements in the series:
5
Taking input to the array elements:
Enter element 1: 12
Enter element 2: 7
Enter element 3: 4
Enter element 4: 9
Enter element 5: 10
12 is an even number
4 is an even number
10 is an even number
Example 6.5 A
C program to find all the even numbers in a series of numbers.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
for(int i=0; i<totalEle; i++)
{
if ( number[i] %2 == 0 )
printf("\n %d is an even number", number[i]);
}
return 0;
}
Quick activity: Modify the above program to display the positions
(indices) along with the numbers.
Answer:
To show the positions
of the even numbers, we simply need to print the loop variable i alongside the value
stored at number[i].
In programming, remember
that indices usually start at 0. However, for a regular
user, you might want to show the "Position" starting from 1. I have
included both below so you can see the difference.
Modified C Program
C
#include
<stdio.h>
int main() {
int number[20];
int totalEle;
printf("\n Enter total number of elements in the
series: ");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements:
");
for(int i = 0; i < totalEle; i++) {
printf("\n Enter element %d: ", (i + 1));
scanf("%d", &number[i]);
}
printf("\n--- Even Numbers Found ---");
for(int i = 0; i < totalEle; i++) {
if (number[i] % 2 == 0) {
// Printing both the index (i) and the value
(number[i])
printf("\n Index [%d] (Position %d): %d is
even",
i, i + 1, number[i]);
}
}
printf("\n");
return 0;
}
Understanding the Output
If you enter the
numbers 10, 15, 20, the output will look like this:
Plaintext
--- Even Numbers Found
---
Index [0] (Position 1): 10 is even
Index [2] (Position 3): 20 is even
Why show both?
·
Index
[i]: This is the "Computer's address."
It is vital for debugging and understanding how the array actually stores data
in memory (starting from 0).
·
Position
i + 1: This is "Human counting." It is
more intuitive for a user to hear that the "1st number" is even
rather than the "0th number."
Important Note on Formatting
In the printf statement:
·
%d acts as a placeholder.
·
The variables i, i + 1, and number[i] fill those
placeholders in the order they are listed.
Would you like to
modify this further to sum up only the even numbers found
at these positions?
Example 6.6 A
C program to calculate total number of even numbers in a series of numbers.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle, count;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
count =0;
for(int i=0; i<totalEle; i++)
{
if ( number[i] %2 == 0 )
{
printf("\n %d is an even number", number[i]);
count = count + 1;
}
}
printf("\n Total number of even numbers: %d", count);
return 0;
}
Meaning
This program
introduces a Counter, which is a variable used to keep track of how
many times a specific event occurs—in this case, how many even numbers are
found.
The logic is simple:
every time the computer finds a number that satisfies the condition number[i] % 2 == 0, it increments the count variable by 1.
Key Components of the Program
1.
Initialization: count
= 0;
o It is vital to start the counter at zero.
Without this, the variable might contain "garbage values" from the
computer's memory, leading to an incorrect total.
2.
The
Increment: count = count + 1; (also written as count++;)
o This line only runs if the if condition is true. It
acts like a "tally mark."
3.
Final
Output: The printf is placed outside the loop.
o If you put it inside the loop, it would print
the total after every single even number it finds. Placing it after the loop
ensures you get the final result once.
Example Execution
User Input:
·
Total elements: 5
·
Numbers: 2, 4, 7, 8, 11
How the Computer
"Thinks":
| Number | Even? | Calculation
| New Count |
| :--- | :--- | :--- |
:--- |
| 2 | Yes | 0 + 1 | 1
|
| 4 | Yes | 1 + 1 | 2
|
| 7 | No | (Skip) | 2
|
| 8 | Yes |2 + 1 | 3 |
| 11 | No | (Skip) | 3
|
Result:
Total number of even
numbers: 3
Programming Tip: The count++ Shorthand
In professional C
programming, you will rarely see count
= count + 1. Instead, programmers
use the increment operator:
C
count++; // This does exactly
the same thing as count = count + 1
Would you like to see
how to modify this program to calculate the percentage of even
numbers in the series (e.g., "60% of the numbers were even")?
The output of the
program depends entirely on the user's input during execution. Assuming the
user enters 5 for the total number of elements and the
series 10, 3, 4, 7, 8, the program produces the following output:
Output
Enter total number of elements in the series:
Enter element 1:
Enter element 2:
Enter element 3:
Enter element 4:
Enter element 5:
10 is an even number
4 is an even number
8 is an even number
Total number of even numbers: 3
Example 6.7 A
C program to search a number from a series of numbers.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of elements in the series: ");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
printf("\n Enter the number you want to search: ");
scanf("%d", &item);
int index = 0;
while ( index < totalEle )
{
if (number[index] = = item )
{
printf("\n The given number is found in the array at index
%d", index);
return 0;
}
index = index + 1;
}
printf("\n Given number is NOT present");
return 0;
}
Meaning
The provided C program
has one critical syntax error that will cause it to fail compilation or produce
incorrect results.
The Error
In your while loop, you used
an assignment operator (=) instead of a equality comparison operator (==).
Incorrect Line:
c
if
(number[index] = item ) // This assigns item to
number[index] rather than comparing them
Correct Line:
c
if
(number[index] == item ) // This correctly
checks for equality
Corrected Code
Here is the functional
code with the necessary fix and proper formatting:
c
#include<stdio.h>
int
main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of
elements in the series: ");
scanf("%d", &totalEle);
printf("\n Taking input to the array
elements: ");
for(int
i=0; i<totalEle; i++)
{
printf( "\n
Enter element %d: ", (i+1) );
scanf("%d",
&number[i]);
}
printf("\n Enter the number you want to
search: ");
scanf("%d", &item);
int index = 0;
while ( index < totalEle )
{
//
FIXED: Changed = to ==
if
(number[index] == item )
{
printf("\n
The given number is found in the array at index %d", index);
return
0; // Exit
program if found
}
index = index + 1;
}
printf("\n Given number is NOT
present");
return 0;
}
Key Changes
1. Fixed Logical Error: Changed if (number[index] = item) to if
(number[index] == item). In C, = is assignment,
while == is comparison.
2. Formatting: Cleaned up the indentation for better readability.
How it Works
·
The program takes the
number of elements and the array elements themselves.
·
It then takes the
number to search for.
·
The while loop traverses
the array from index 0 up to totalEle - 1.
·
If number[index] == item is true, it prints the index and exits using return 0.
·
If the loop finishes
without finding the item, it prints "Given number is NOT
present".
Here is the expected
output based on the provided C code.
Scenario 1: Item is found
text
Enter total number of elements in the series:
5
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Enter the number you want to search: 30
The given number is found in the array at
index 2
Scenario 2: Item is not found
text
Enter total number of elements in the series:
3
Taking input to the array elements:
Enter element 1: 5
Enter element 2: 15
Enter element 3: 25
Enter the number you want to search: 100
Given number is NOT present
Code Behavior Notes:
·
The code correctly
implements a linear search.
·
Because of the return 0; inside the if statement, it
will stop searching after finding the first occurrence of the
number.
It
correctly handles the "not found" scenario by printing "Given
number is NOT present" only after the while loop finishes.
Example 6.7 A
C program to search a number from a series of numbers.
Answer:
#include<stdio.h>
int
main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of
elements in the series: ");
scanf("%d", &totalEle);
printf("\n Taking input to the array
elements: ");
for(int
i=0; i<totalEle; i++)
{
printf( "\n
Enter element %d: ", (i+1) );
scanf("%d",
&number[i]);
}
printf("\n Enter the number you want to
search: ");
scanf("%d", &item);
int index = 0;
while ( index < totalEle )
{
//
FIXED: Changed = to ==
if
(number[index] == item )
{
printf("\n
The given number is found in the array at index %d", index);
return
0; // Exit
program if found
}
index = index + 1;
}
printf("\n Given number is NOT
present");
return 0;
}
Quick
activity: Run the above program with inputs such that the
searching element appears more than once in the series of numbers. For example,
take array elements as {4, 5, 6, 9, 8, 7, 4, 5} and search for 5.
Answer:
If you run your
current program with those inputs, it will behave like a "First Occurrence" search. As soon as it
finds the first 5, the return
0; command will force
the entire program to exit immediately.
Execution Trace (Current Program)
Input Array: {4, 5, 6,
9, 8, 7, 4, 5}
Search Item: 5
1.
Checks index 0 (Value 4): No match.
2.
Checks index 1 (Value 5): Match!
3.
Output: The
given number is found in the array at index 1
4.
Program
terminates. It never sees the
second 5 at index 7.
How to Find ALL Occurrences
To find every instance
of the number, we need to make two changes:
1.
Remove
return 0; from inside the loop so it keeps looking.
2.
Use
a "Flag" or "Counter" to keep track of whether we found it at least once.
Modified Program for Multiple Results
C
#include <stdio.h>
int main() {
int number[20] = {4, 5, 6, 9, 8, 7, 4, 5}; // Using your example
int totalEle = 8;
int item = 5;
int foundCount = 0; // To track how many times it appears
printf("Searching for %d in the series...\n", item);
int index = 0;
while (index < totalEle)
{
if (number[index] ==
item) {
printf("Found at index %d\n", index);
foundCount++; // Increment every time we find a match
}
index++;
}
if (foundCount == 0) {
printf("Given number is NOT present\n");
} else {
printf("Search complete. Total occurrences: %d\n", foundCount);
}
return 0;
}
New Output for your Example:
Plaintext
Searching for 5 in the series...
Found at index 1
Found at index 7
Search complete. Total occurrences: 2
Why this works better:
By replacing return 0; with foundCount++,
the loop is allowed to finish its journey through the entire array. This is the
difference between a Targeted Search (stop at first sight)
and an Audit/Filter (check everything).
Would you like me to
show you how to modify this so it also tells you the total
count of how many times the number appeared?
Example 6.8 A
C program to search a number from a series of numbers.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
printf("\n Enter the number you want to search: ");
scanf("%d", &item);
int index = 0, flag = 0;
while ( index < totalEle )
{
if (number[index] = = item )
{
printf("\n The given number is found in the array at index
%d", index);
flag = 1;
}
index = index + 1;
}
if ( flag = = 0 )
printf("\n Given number is NOT present");
return 0;
}
MEANING:
The
provided C code has syntax errors in the if conditions
that prevent it from running correctly. Specifically, spaces within the
equality operator (= =) are invalid, and the flag check uses a
single = instead of ==.
Here
is the corrected code:
c
#include<stdio.h>
int main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of
elements in the series: ");
scanf("%d", &totalEle);
printf("\n Taking input to the array
elements: ");
for(int
i=0; i<totalEle; i++)
{
printf( "\n
Enter element %d: ", (i+1) );
scanf("%d",
&number[i]);
}
printf("\n Enter the number you want to
search: ");
scanf("%d", &item);
int index = 0,
flag = 0;
while ( index < totalEle )
{
// FIX:
Changed "= =" to "=="
if
(number[index] == item )
{
printf("\n
The given number is found in the array at index %d", index);
flag = 1;
break;
// Good practice to break once found
}
index = index + 1;
}
// FIX: Changed "= =" to
"=="
if ( flag == 0
)
printf("\n
Given number is NOT present");
return 0;
}
Key Corrections:
1.
if
(number[index] = = item ) changed to if (number[index] == item ): The equality operator must be written without spaces as ==.
2.
if
( flag = = 0 ) changed
to if ( flag == 0 ): Corrected the equality operator here as
well.
3.
Added break;: Inside the if statement, adding break; ensures
the loop stops immediately after finding the first instance of the item.
Example Output
text
Enter total number of elements in
the series: 3
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter the number you want to search:
20
The given number is found in the
array at index 1
Example 6.8 A
C program to search a number from a series of numbers.
Answer:
#include<stdio.h>
int
main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of
elements in the series: ");
scanf("%d", &totalEle);
printf("\n Taking input to the array
elements: ");
for(int
i=0; i<totalEle; i++)
{
printf( "\n
Enter element %d: ", (i+1) );
scanf("%d",
&number[i]);
}
printf("\n Enter the number you want to
search: ");
scanf("%d", &item);
int index = 0,
flag = 0;
while ( index < totalEle )
{
// FIX:
Changed "= =" to "=="
if
(number[index] == item )
{
printf("\n
The given number is found in the array at index %d", index);
flag = 1;
break;
// Good practice to break once found
}
index = index + 1;
}
// FIX: Changed "= =" to
"=="
if ( flag == 0
)
printf("\n
Given number is NOT present");
return 0;
}
Quick
Activity: Write and execute the above program using a for
loop in place of the while loop.
Answer:
To convert a while loop into a for loop, we consolidate
the three essential parts of iteration—initialization, condition, and increment—into a
single line. This often makes the code cleaner and less prone to errors like
infinite loops.
Here is the program
rewritten using a for loop.
The C Program (Using a for loop)
C
#include <stdio.h>
int main() {
int number[20];
int totalEle, item;
int flag = 0;
printf("\n Enter total number of elements in the series: ");
scanf("%d",
&totalEle);
printf("\n Taking input to the array elements: ");
for(int i = 0; i < totalEle;
i++) {
printf(" Enter element %d: ", (i + 1));
scanf("%d",
&number[i]);
}
printf("\n Enter the number you want to search: ");
scanf("%d",
&item);
// --- Search Logic using for loop ---
for (int index = 0; index < totalEle;
index++) {
if (number[index] ==
item) {
printf("\n The given number is found in the array at index
%d", index);
flag = 1;
break; // Stop searching once the first match is found
}
}
if (flag == 0) {
printf("\n Given number is NOT present");
}
printf("\n");
return 0;
}
Key Differences in Execution
While the behavior of
the program remains the same as the while loop version, the structure changes as
follows:
1.
Consolidated
Syntax: In the while version, index = 0 was outside the loop
and index = index + 1 was at the bottom. In the for loop, these are all
contained in for(int index = 0;
index < totalEle; index++).
2.
Scope: By declaring int index inside the for loop header, that
variable is only accessible within the loop. This is generally considered
"safer" programming.
3.
Readability: Most programmers prefer the for loop for searching
arrays because it clearly defines the boundaries of the search at the very
start of the block.
Example Trace
If you enter 5
elements: {10, 20, 30, 40, 50} and search for 30:
·
Iteration
0: number[0] is 10. No match. index becomes 1.
·
Iteration
1: number[1] is 20. No match. index becomes 2.
·
Iteration
2: number[2] is 30. Match!
o flag becomes 1.
o break exits the loop
immediately.
·
The if(flag == 0)
check fails, so the "NOT present" message is skipped.
Would you like to see
how to modify this to count how many times a number appears instead of stopping
at the first one?
Example 6.9:
A C program to display array elements in reverse order.
Answer:
#include<stdio.h>
int main()
{
char char_array [ ]
= {'G', 'U', 'W', 'A', 'H', 'A', 'T', 'I'};
printf("Elements in the reverse order are: \n");
int index = 7;
while(index >= 0)
{
printf("%c ", char_array[index]);
index = index - 1;
}
return 0;
}
Meaning:
Based on the code
provided, the program aims to reverse a character array (string) containing
"GUWAHATI". However, the code as written will likely cause compilation
errors due to missing single quotes around the character
literals.
Here is the corrected
code and its output:
Corrected Code
c
#include<stdio.h>
int
main() {
// Characters must be enclosed in single
quotes ' '
char char_array [ ] = { 'G' , 'U' , 'W' , 'A' , 'H' , 'A' , 'T' , 'I' };
printf("Elements in the reverse order
are:\n");
// The array has 8 elements, so the last
index is 7 (size - 1)
int index = 7;
// Loop runs from index 7 down to 0
while(index >= 0) {
printf("%c",
char_array[index]);
index = index - 1;
}
printf("\n");
return 0;
}
Output
text
Elements in the reverse order are:
ITAHAWUG
Explanation
1.
Initialization: char_array stores { 'G' , 'U' , 'W' , 'A' , 'H' , 'A' , 'T' ,
'I' }.
2.
Indexing: The elements are at index 0 (G) through 7
(I).
3.
Loop: The while loop starts at index = 7 and prints characters in descending order (char_array[7], char_array[6], ...), reversing the string.
Quick
Activity: Write a similar C program for an integer type of
array where the array elements are taken from the user as input and display
them in reverse order.
Answer:
To create this
program, we combine the input logic from your previous examples with the
reverse traversal logic we just discussed.
The main difference
here is that we ask the user for the size of the array first, so we know
exactly where the "last index" should be.
C Program: Reverse Integer Array
C
#include
<stdio.h>
int main() {
int number[50]; // Array can hold up to 50 integers
int totalEle;
printf("Enter the total number of elements:
");
scanf("%d", &totalEle);
// 1. Taking input from the user
printf("\n--- Input Phase ---\n");
for(int i = 0; i < totalEle; i++) {
printf("Enter element %d: ", (i + 1));
scanf("%d", &number[i]);
}
// 2. Displaying in reverse order
printf("\n--- Reverse Order ---\n");
/* Logic: If totalEle is 5, indices are
0,1,2,3,4.
The last index is (totalEle - 1).
*/
for(int i = (totalEle - 1); i >= 0; i--) {
printf("%d ", number[i]);
}
printf("\n");
return 0;
}
How the Logic Works
1.
The
Starting Index: We set the loop to
start at totalEle - 1. If the user enters 5 numbers, the loop starts at index 4.
2.
The
Condition: We use i >= 0. This ensures the
loop keeps running until it has processed the very first element (index 0).
3.
The
Decrement: Instead of i++, we use i-- (or i = i - 1) to move one step to
the left in the array with every iteration.
Example Execution
If you provide the
following input:
·
Total
elements: 4
·
Elements: 10,
20, 30, 40
Step-by-Step Output:
1.
The computer
calculates the starting index: $4 - 1 = 3$.
2.
It prints number[3] (40).
3.
It prints number[2] (30).
4.
It prints number[1] (20).
5.
It prints number[0] (10).
6.
i becomes -1, the condition i >= 0 is now false, and the
loop ends.
Final Result: 40
30 20 10
Would you like to see
how to actually swap the elements inside the array
so they are permanently stored in reverse order?
Example 6.10:
A C program to display the elements of the odd positions.
Answer:
#include<stdio.h>
int main()
{
char char_array [ ] = {'G', 'U', 'W', 'A', 'H', 'A', 'T', 'I'};
printf("Elements in the odd position are: \n");
int index = 0;
while(index < 8)
{
printf("%c ", char_array[index]);
index = index + 2;
}
return 0;
}
Meaning:
The provided C code
attempts to print elements in odd positions from a character array but contains
syntax errors that prevent it from compiling and running correctly.
Corrected C Code
Here is the corrected
version of the code:
#include
<stdio.h>
int main() {
// Character literals must be enclosed in
single quotes.
char char_array[] = {'G', 'U', 'W', 'A',
'H', 'A', 'T', 'I'};
printf("Elements in the odd position
are: \n");
// The index starts at 0, representing the
first element (position 1).
int index = 0;
// Loop through the array, incrementing by
2 to hit every second element.
// The size 8 should ideally be calculated
dynamically for better practice.
while (index < 8) {
printf("%c ",
char_array[index]); // Add a space for readability
index = index + 2;
}
printf("\n"); // Add a newline at
the end for clean output
return 0;
}
Explanation of Errors and
Corrections
1.
Missing
Single Quotes: In the original
code, char
char_array [ ] = { G , U , W , A , H , A , T , I };, the characters G, U, etc., were treated as undefined variables instead of character
literals. In C, single quotes (e.g., 'G') must enclose single characters.
2.
Missing
Quotes in printf: The line printf( Elements in
the odd position are: \n ); was
missing the required double quotes around the string literal. It should
be printf("Elements
in the odd position are: \n");.
3.
Missing
Format Specifier Quotes: The
line printf(
%c , char_array[index]); was missing the
required double quotes around the format specifier. It should be printf("%c",
char_array[index]);.
Output of the Corrected Code
When the corrected
code is compiled and run, the output will be:
Elements in the odd position are:
G W H T
Note on "Odd Position": In programming,
array indices start at 0. The elements at indices 0, 2, 4, and 6 correspond to
the 1st, 3rd, 5th, and 7th "odd positions" in human-readable
terms.
Quick Activity:
Write a similar C program for an integer type of array where the array elements
are taken from the user as input and display only the even positioned elements.
Answer:
To display the even positioned elements (the 2nd, 4th, 6th, etc.), we
need to start our loop at index 1 and
increment the index by 2 in each step.
Here is the C program
to achieve this:
C
#include
<stdio.h>
int main() {
int number[50];
int totalEle;
printf("Enter total number of elements: ");
scanf("%d", &totalEle);
// Input Phase
printf("\n--- Input Phase ---\n");
for(int i = 0; i < totalEle; i++) {
printf("Enter element %d: ", (i + 1));
scanf("%d", &number[i]);
}
// Displaying Even Positioned Elements
printf("\n--- Even Positioned Elements (2nd,
4th, etc.) ---\n");
/* Logic:
Position 2 is index 1
Position 4 is index 3
We start at index 1 and jump by 2.
*/
for(int i = 1; i < totalEle; i = i + 2) {
printf("Position %d (Index %d): %d\n", i + 1, i, number[i]);
}
return 0;
}
Logic Breakdown
In C, the relationship
between the human "Position" and the computer "Index" is
always shifted by one.
·
Position
1 = Index 0 (Odd
Position)
·
Position
2 = Index 1 (Even Position)
·
Position
3 = Index 2 (Odd
Position)
·
Position
4 = Index 3 (Even Position)
By setting the loop to
int i = 1 and using i = i +
2, we effectively
"hop" over the odd positions and only land on the even ones.
Example Run
If you enter 5 elements: 10,
20, 30, 40, 50
|
Loop Iteration |
Index (i) |
Position (i+1) |
Value |
|
1st |
1 |
2 |
20 |
|
2nd |
3 |
4 |
40 |
|
3rd |
5 |
6 |
(Stops because 5 is not <
5) |
Output:
Plaintext
Position 2 (Index 1):
20
Position 4 (Index 3):
40
Would you like to see
how to calculate the sum of only these even-positioned
elements?
OUTPUT:
Enter total number of elements: 5 --- Input Phase ---Enter element 1: 10Enter element 2: 20Enter element 3: 30Enter element 4: 40Enter element 5: 50 --- Even Positioned Elements (2nd, 4th, etc.) ---Position 2 (Index 1): 20Position 4 (Index 3): 40
Example 6.11:
A C program to replace an array element given by an index.
Answer:
#include<stdio.h>
int main()
{
int number[20];
int totalEle, item, pos;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
printf("\n Now elements of the array are: ");
for(int i=0; i<totalEle; i++)
{
printf("%d ", number[i]);
}
printf("\n Replacing elements... ");
printf("\n Enter the new number: ");
scanf("%d", &item);
printf("\n Enter the index of the new number: ");
scanf("%d", &pos);
number[pos] = item;
printf("\n Now elements of the array are: ");
for(int i=0; i<totalEle; i++)
{
printf("%d ", number[i]);
}
return 0;
}
Meaning:
This C program allows
a user to define the size of an integer array, input elements, and subsequently
replace an element at a specific index with a new value.
Code Analysis
1.
Declaration: int number[20]; creates an array capable of holding up to 20 integers.
2.
Input
Loop: A for loop takes totalEle input values from the user.
3.
Display: The code prints the array using
another for loop.
4.
Replacement: The user provides a new item and a pos (index).
5.
Modification: number[pos] = item; updates the array at the specified
0-based index.
6.
Output: The modified array is printed.
Expected Output Example
text
Enter total number of elements in the series:
3
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Now elements of the array are: 10 20 30
Replacing elements...
Enter the new number: 99
Enter the index of the new number: 1
Now elements of the array are: 10 99 30
Key Considerations
·
Zero-based
Indexing: Array indices in
C start at 0. To replace the first element, the user must enter 0.
·
Memory
Safety: The program does
not check if pos is within the range 0 to totalEle-1. Entering a pos >= 20 or >= totalEle will cause undefined behavior or memory corruption.
·
Array
Size: The maximum
capacity is 20. If totalEle > 20, the
program will malfunction.
Example 6.12:
A C program to replace all the occurrences of a number in an array.
Answer:
#include<stdio.h>
#include<stdio.h>
int main()
{
int number[20];
int totalEle, item, old_num;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
printf("\n Now elements of the array are: ");
for(int i=0; i<totalEle; i++)
{
printf("%d ", number[i]);
}
printf("\n Replacing elements... ");
printf("\n Enter the old number you want to replace:
");
scanf("%d", &old_num);
printf("\n Enter the new number: ");
scanf("%d", &item);
for(int index = 0; index <totalEle; index++)
{
if(number[index] == old_num)
{
printf("\n Existing number is found at index %d",
index);
number[index] = item;
printf("\n Number is replaced");
}
}
printf("\n Now elements of the array are: ");
for(int i=0; i<totalEle; i++)
{
printf("%d ", number[i]);
}
return 0;
}
Meaning
This
C program efficiently replaces all occurrences of a specific "old"
number with a "new" number within a user-defined array. It operates
by taking the size and elements of an array, allowing the user to specify which
value to replace, and updating the array in place.
Code Breakdown
·
Initialization: Sets up an integer array with a maximum size of 20 (int number[20]).
·
Input Phase: Prompts the user to enter the total number of elements (totalEle) and the elements themselves, storing them in the number array.
·
Replacement Phase:
·
Asks for the old_num (number to be replaced).
·
Asks for the item (new number).
·
Iterates through the array using a for loop, searching for old_num.
·
If found, the program updates that index: number[index] = item;.
Output Phase: Displays the updated array.
Sample Execution
text
Enter total number of elements in
the series: 5
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 10
Enter element 4: 30
Enter element 5: 10
Now elements of the array are: 10 20
10 30 10
Replacing elements...
Enter the old number you want to
replace: 10
Enter the new number: 99
Existing number is found at index 0
Number is replaced
Existing number is found at index 2
Number is replaced
Existing number is found at index 4
Number is replaced
Now elements of the array are: 99 20
99 30 99
Key Features
·
Replaces all occurrences: If the old number appears multiple times, every instance
is replaced.
·
Direct Modification: The array is updated directly, and the new values are
printed immediately afterward.
User Interaction: Clearly prompts for inputs, making the
process intuitive.
Example 6.13:
A C program to count number of occurrences of given in an array.
Answer:
#include<stdio.h>
#include<stdio.h>
int main()
{
int number[20];
int totalEle, item;
printf("\n Enter total number of elements in the series:
");
scanf("%d", &totalEle);
printf("\n Taking input to the array elements: ");
for(int i=0; i<totalEle; i++)
{
printf( "\n Enter element %d: ", (i+1) );
scanf("%d", &number[i]);
}
printf("\n Now elements of the array are: ");
for(int i=0; i<totalEle; i++)
{
printf("%d ", number[i]);
}
printf("\n Enter the element you want to count: ");
scanf("%d", &item);
int count = 0;
for(int index = 0; index <totalEle; index++)
{
if(number[index] == item)
{
count = count + 1;
}
}
printf("\n %d is present %d number of times in the
array", item, count);
return 0;
}
Meaning:
This C program takes a
set of numbers from the user, stores them in an array, and then counts how many
times a specific, user-defined number appears in that array.
Here is a step-by-step
explanation of the code:
1. Initialization and Input
·
int
number[20];: Defines an integer
array named number that can hold up to 20 elements.
·
scanf("%d",
&totalEle);: Asks the user how
many elements they want to enter (up to 20).
·
The
first for loop: Iterates totalEle times to take input for each array
element using scanf("%d",
&number[i]);.
2. Display Array
·
The
second for loop: Iterates through the array and prints all the elements the
user just entered to confirm the input.
3. Counting Occurrences
·
scanf("%d",
&item);: Asks the user which
specific number (item) they want to search for in the array.
·
int
count = 0;: Initializes a
counter variable to zero.
·
The
third for loop (for(int index = 0; index <totalEle; index++)):
o
It checks every
element in the array (number[index]) against the target number (item).
o
if(number[index]
== item): If the current
element matches the target, the count variable is incremented by 1 (count = count + 1;).
4. Output Result
·
printf("\n
%d is present %d number of times...", item, count);: Finally, the program prints the number of
times the item was found.
Based on the code
provided, here is an example of the input and the resulting output.
Example Scenario
·
Total
Elements: 5
·
Array
Inputs: 10, 20, 10, 30,
10
·
Element
to Count: 10
Output
text
Enter total number of elements in
the series: 5
Taking input to the array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 10
Enter element 4: 30
Enter element 5: 10
Now elements of the array are: 10 20 10 30 10
Enter the element you want to count: 10
10 is present 3 number of times in the array
Key Logic
·
The code asks for the
size of the array (totalEle).
·
It populates number[20] with user input.
·
It prints all stored
elements.
It
asks for an item and compares it
against every element in the array to count the total occurrences.
Example 6.14:
A C program to handle a char array as string.
Answer:
#include<stdio.h>
#include<string.h>
int main()
{
char name[20];
printf("\n Enter your name: ");
gets(name);
printf("\n Your name is: ");
puts(name);
return 0;
}
Meaning:
The provided C code
demonstrates the use of the gets() and puts() functions for
input and output.
Code Analysis
·
#include <stdio.h>: Includes the standard input/output library for functions
like printf(), gets(), and puts().
·
#include <string.h>: Includes the string library, though no functions from this
specific library are used in the main logic of this simple example.
·
char name[20];:
Declares a character array name with a size of 20 to store the input string.
·
printf("\n Enter your name: ");: Prompts the user to enter their name.
·
gets(name);:
Reads a line of text from standard input (keyboard) and stores it in the name array.
·
printf("\n Your name is: ");: Prints a message before displaying the name.
·
puts(name);:
Prints the string stored in name to standard output, automatically adding a newline
character at the end.
·
return 0;: Indicates successful
execution of the program.
Output
When this code is
compiled and run, the output would be:
Enter your name: [User enters a name, e.g.,
John Doe]
Your name is: John Doe
Important Security Note:
The gets() function is highly discouraged in
modern C programming due to security vulnerabilities. It does not perform
bounds checking and can lead to a buffer overflow if the user input
exceeds the allocated size of the name array (20 characters in this case).
A safer alternative is
to use fgets(), which allows you to specify the maximum
number of characters to read, preventing overflows:
c
#include
<stdio.h>
int
main() {
char name[20];
printf("\n Enter your name: ");
// Use fgets for safer input
if (fgets(name, sizeof(name), stdin) != NULL) {
printf("\n
Your name is: ");
puts(name);
}
return 0;
}
Example 6.15:
A C program to display the string characters.
Answer:
#include<stdio.h>
#include<string.h>
int main()
{
char name[20];
printf("\n Enter your name: ");
gets(name);
printf("\n Your name is: ");
puts(name);
printf("\n Displaying the string character wise: ");
for(int index = 0; index < strlen(name); index++)
{
printf(" %c ",name[index]);
}
return 0;
}
Meaning:
The provided C program
correctly displays string characters one by one using a for loop, after
accepting input using gets() and displaying the full string
using puts().
Here is the full code:
c
#include<stdio.h>
#include<string.h>
int
main()
{
char name[20];
printf("\n Enter your name: ");
gets(name); // Note: gets() is unsafe and
deprecated.
printf("\n Your name is: ");
puts(name);
printf("\n Displaying the string
character wise: ");
// Iterate through the string until the
end (null terminator is implied by strlen)
for(int
index = 0; index < strlen(name); index++)
{
printf("
%c ",name[index]);
}
return 0;
}
Key Components Explained:
·
#include<stdio.h>: Includes the standard input/output library
for functions like printf, gets, and puts.
·
#include<string.h>: Includes the string library, necessary for
the strlen() function, which calculates the length of
the string.
·
char
name[20];: Declares a character
array (string) named name with a maximum size of 20 characters.
·
gets(name);: Reads a line of text from standard input
(keyboard) and stores it in the name array.
o Caution: The gets() function is highly discouraged in modern
C programming because it doesn't check the buffer size, which can lead to
buffer overflows and security vulnerabilities. Use safer alternatives
like fgets() or scanf() with size
limits.
·
puts(name);: Prints the string name to the console
followed by a newline character.
·
for loop:
o int index = 0;:
Initializes the loop counter to 0 (the index of the first character).
o index < strlen(name);: The loop continues as long as the index is less than the total
length of the string.
o index++: Increments the index
after each iteration.
o printf(" %c ", name[index]);: Prints the character at the current index using the %c format
specifier.
The C program prompts
the user to enter their name, displays it, and then shows each character of the
name separately.
c
#include<stdio.h>
#include<string.h>
int
main()
{
char name[20];
printf("\n Enter your name: ");
// Prompts user for input
gets(name); // Reads the input (e.g.,
"Alice")
printf("\n Your name is: ");
puts(name); // Prints the name as a whole
string (e.g., Alice)
printf("\n Displaying the string
character wise: ");
for(int
index = 0; index < strlen(name); index++)
{
printf("
%c ",name[index]); // Prints each
character with spaces (e.g., A l i c e )
}
return 0;
}
Example Output (if the
user enters "Alice")
Enter your name: Alice
Your name is: Alice
Displaying the string character wise:
A
l i c e
Exercise
1. Define array. Why do we use arrays in computer programs?
Answer:
An array is a
fundamental data structure in computer programming used to store a
collection of elements of the same data type in contiguous memory
locations.
Definition of an Array
An array can be
defined as:
·
A
collection of data: It holds
multiple pieces of data under a single variable name.
·
Homogeneous: Typically, all elements within an array
must be of the same type (e.g., all integers, all floating-point numbers, or
all strings).
·
Indexed: Each element in the array is identified
by a unique index or subscript, which is used to access or modify specific
elements. In most programming languages, indexing starts at zero.
·
Contiguous
memory: The elements are
stored in adjacent memory locations, which allows for efficient, direct access
to any element via its index.
For example, an array
of four integers might look like this in memory:
| 10 |
20 | 30 | 40 |
Indices: 0 1 2 3
Reasons for Using Arrays
Arrays are a cornerstone
of programming due to their efficiency and utility in managing and processing
structured data. Key reasons for their use include:
·
Efficient
Data Organization: They allow
programmers to store and manage a large number of related variables as a single
unit rather than declaring thousands of individual variables.
·
Direct
Access and Retrieval: Because elements
are stored in contiguous memory and accessed by index, retrieving an element is
a very fast operation (known as O(1) time complexity). This is useful for rapid
lookups and calculations.
·
Implementing
Algorithms: Many common and
powerful algorithms, such as sorting algorithms (like bubble sort or quicksort)
and search algorithms (like binary search), are built upon arrays.
·
Managing
Sequential Data: Arrays are ideal
for situations where the order of data matters, such as storing a list of
student grades, sensor readings over time, or a sequence of characters in a
string.
·
Memory
Efficiency: The contiguous
nature of array storage is memory efficient, especially when dealing with large
datasets, as there is minimal overhead between elements.
Foundation for Other Data Structures: More complex
data structures, such as strings, matrices (2D arrays), stacks, queues, and
even linked lists, are often implemented using arrays as a foundational
component.
2. Can we store both integer and
float types of data in a single array? Demonstrate this by writing a simple C
program.
Answer:
Yes,
it is possible to store both integer and float types of data in a single array
in C by declaring the array type as a common base type that can accommodate
both, such as float or double [1].
This works because C performs implicit type conversion when a smaller data type
(like int) is assigned to a larger one (like float or double).
However,
the most straightforward and flexible way to store different data types in
the same array is by using a union or by declaring an array of pointers to void (void*), with the latter being more common for
arrays where each element may be a completely different type.
Here
is a C program demonstrating how to achieve this using a union and a simple float array.
Method 1: Using a float array
(implicit type conversion)
This
is the simplest approach, as C automatically converts the integer 10 into a floating-point number 10.0 when stored in the float array.
#include
<stdio.h>
int
main() {
// Declare an array of float, which can
also store integers
float mixed_data[4];
// Store integer (will be converted to
10.0f)
mixed_data[0] = 10;
// Store another integer (converted to
25.0f)
mixed_data[1] = 25;
// Store float
mixed_data[2] = 3.14f;
// Store another float
mixed_data[3] = 9.99f;
printf("Storing integer and float in a
single float array:\n");
printf("Index 0 (int): %.2f\n",
mixed_data[0]);
printf("Index 1 (int): %.2f\n",
mixed_data[1]);
printf("Index 2 (float): %.2f\n",
mixed_data[2]);
printf("Index 3 (float): %.2f\n",
mixed_data[3]);
return 0;
}
Method 2: Using a union for genuine mixed storage
A union allows a single
memory location to be used to hold different data types at different times. To
track which type is currently stored in each array element, we use a struct to wrap
the union and an enum type
identifier.
#include
<stdio.h>
//
Define an enum to track the type stored in each element
typedef
enum {
TYPE_INT,
TYPE_FLOAT
}
DataType;
//
Define a union to hold either an int or a float
typedef
union {
int i_val;
float f_val;
}
DataValue;
//
Define a struct to hold the value AND its type identifier
typedef
struct {
DataType type;
DataValue data;
}
MixedElement;
int
main() {
// Declare an array of the MixedElement
struct
MixedElement mixed_array[4];
// Store an integer at index 0
mixed_array[0].type = TYPE_INT;
mixed_array[0].data.i_val = 10;
// Store a float at index 1
mixed_array[1].type = TYPE_FLOAT;
mixed_array[1].data.f_val = 3.14f;
// Store another integer at index 2
mixed_array[2].type = TYPE_INT;
mixed_array[2].data.i_val = 25;
// Store another float at index 3
mixed_array[3].type = TYPE_FLOAT;
mixed_array[3].data.f_val = 9.99f;
printf("Storing integer and float in a
single array using a union:\n");
for (int i = 0; i < 4; i++) {
if (mixed_array[i].type == TYPE_INT) {
printf("Index %d (int):
%d\n", i, mixed_array[i].data.i_val);
} else if (mixed_array[i].type ==
TYPE_FLOAT) {
printf("Index %d (float):
%.2f\n", i, mixed_array[i].data.f_val);
}
}
return 0;
}
3.
Write the indices of the first and last element of the following array
declaration.
char
city [7]={'S', 'I', 'L', 'C', 'H', 'A', 'R', };
Answer:
In the array
declaration char city[7], the number inside the brackets defines the size (total number of elements).
The Indices
In C, array indexing
always begins at 0 and ends at Size - 1.
·
First
Element Index: 0
·
Last
Element Index: 6
Detailed Breakdown
The array stores the
characters of "SILCHAR" as follows:
|
Element |
'S' |
'I' |
'L' |
'C' |
'H' |
'A' |
'R' |
|
Index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
Why is the last index 6?
Since we start
counting from zero, the 7th element is reached at index 6. If you tried to
access city[7], you would be looking at a memory location
outside of your array, which usually leads to a "Buffer Overflow" or
a program crash.
Would
you like to see what happens if you try to store a string longer than 7
characters in this specific array?
4.
Write a C program and declare an integer type array with capacity 7. Take input
to the array from the keyboard. Display the 8th element of the array. Hint:
display num[7] if num is the name of the array. Analyze the output.
ANswer:
#include
<stdio.h>
int
main() {
// Declare an integer array with a capacity
of 7
int num[7];
// Take input from the keyboard
printf("Enter 7 integers:\n");
for (int i = 0; i < 7; i++) {
scanf("%d", &num[i]);
}
// Display the 8th element (index 7)
printf("The 8th element of the array
(num[7]) is: %d\n", num[7]);
return 0;
}
Analysis of the Output
The program will
compile and run, but accessing num[7] represents an out-of-bounds access or buffer
overflow. This leads to undefined behavior in C for the
following reasons:
·
Array
Indices: In C, array
indices are 0-based. An array with a capacity of 7 has valid indices from 0 to 6.
·
Accessing num[7]: The expression num[7] attempts to access the eighth element, which is a memory
location immediately after the space allocated for the array.
·
Undefined
Behavior: The output value
will not be a predictable result of the inputs. The program might print:
o A zero, if the memory location was previously
cleared.
o A "garbage" value (an unexpected
integer) that happens to be stored in that specific memory location at the time
of execution.
o The program might even crash, depending on the
system's memory management and if the accessed memory address is invalid (a
segmentation fault).
The code adheres to
the user's prompt (to display num[7]), but it is a perfect example of a common programming error
that can lead to security vulnerabilities or program instability.
5.
Write a C program and declare an integer type array with 7 elements in it.
Display the address of the individual elements in the array.
Answer:
#include
<stdio.h>
int
main() {
// Declare an integer type array with 7
elements and initialize it
int numbers[7] = {10, 20, 30, 40, 50, 60,
70};
printf("Displaying the addresses of
individual elements in the array:\n\n");
// Loop through the array from the first
element to the last
for (int i = 0; i < 7; i++) {
// Use the address-of operator (&)
to get the memory address of each element.
// The %p format specifier is used to
print pointer values (addresses).
printf("Address of element
numbers[%d] (value: %d): %p\n", i, numbers[i], (void*)&numbers[i]);
}
return 0;
}
Explanation
1.
#include <stdio.h>: This line includes the standard input/output library, which is
necessary for functions like printf.
2.
int numbers[7] = {10, ...};: This declares an integer array named numbers that can hold 7 elements and initializes
it with values.
3.
for (int i = 0; i < 7; i++) { ... }: A for loop is used to iterate through each element of the array.
The index i goes from 0 to 6.
4.
&numbers[i]: The ampersand symbol (&) is the "address-of" operator in C. It returns the
memory address of the variable or array element that follows it.
5.
(void*)&numbers[i]: Casting the address to (void*) is a common and recommended practice when passing pointers
to printf with the %p specifier, as it ensures correct
behavior across different system architectures.
6.
printf("... %p\n", ...): The %p format specifier is specifically used to print pointer
addresses in a hexadecimal format.
6.
Write a C program and declare two integer type arrays, each with capacity 7.
Take input only to the first array. Write a loop to copy the elements of the
first array to the second one. Display the elements of the second array.
Answer:
#include
<stdio.h>
int
main() {
// Declare two integer arrays, each with
capacity 7
int first_array[7];
int second_array[7];
int i;
printf("Enter 7 integers for the first
array:\n");
// Take input only to the first array
for (i = 0; i < 7; i++) {
printf("Element %d: ", i +
1);
// Use the address-of operator (&)
to store input at the correct memory location
scanf("%d",
&first_array[i]);
}
// Loop to copy the elements of the first
array to the second one
for (i = 0; i < 7; i++) {
second_array[i] = first_array[i];
}
printf("\nElements of the second
array:\n");
// Display the elements of the second array
for (i = 0; i < 7; i++) {
printf("Element %d: %d\n", i
+ 1, second_array[i]);
}
return 0;
}
Explanation:
1.
#include <stdio.h>: This line includes the standard input/output library needed
for functions like printf() and scanf().
2.
Array
Declaration: int first_array[7]; and int second_array[7]; declare two arrays named first_array and second_array, each capable of holding 7 integers.
3.
Input
Loop: The first for loop iterates 7 times (from i = 0 to i < 7). Inside the loop, scanf("%d", &first_array[i]); reads an integer from the user and
stores it in the corresponding element of first_array. The & symbol is
crucial as it provides the memory address of the array element.
4.
Copying
Loop: The second for loop also iterates 7 times. second_array[i] =
first_array[i]; assigns the
value of each element in first_array to
the corresponding element in second_array.
5.
Display
Loop: The final for loop prints the values stored in each
element of the second_array to
the console.
6.
return 0;:
This indicates that the program executed successfully.
7.
Write a strategy to find the summation of all the even numbers stored in an
array. Write a C program for the same. If the array elements are {1, 2, 4, 3,
5, 6, 7, 7, 8}, the output of the program will be 20.
Answer:
A strategy to find the
summation of all even numbers in an array involves iterating through the
elements and using the modulo operator. The C program below implements this
strategy and confirms that for the array {1, 2, 4, 3, 5, 6, 7, 7, 8}, the
output is 20.
Strategy to Sum Even Numbers
The process requires a
simple iteration and conditional check:
·
Initialization: A variable, often named sum, is initialized to zero to store the
accumulating result.
·
Iteration: The program iterates through each
element of the input array from the beginning to the end.
·
Condition
Check: For each
element, a modulo operation (using the % operator) checks if the number is evenly divisible by 2.
If element
% 2 == 0, the number is even.
·
Accumulation: If the number is even, it is added to
the sum variable.
·
Result: After the loop completes, the final
value of sum is the total sum of all even numbers in
the array.
C Program
The following C program implements the
strategy described above using the example array provided.
c
#include
<stdio.h>
int
main() {
int arr[] = {1,
2, 4, 3, 5, 6, 7, 7, 8};
int n = sizeof(arr)
/ sizeof(arr[0]);
int sum_even = 0;
// Iterate through the array elements
for (int
i = 0; i < n; i++) {
// Check
if the current element is even
if
(arr[i] % 2 == 0)
{
sum_even += arr[i]; // Add even number to the sum
}
}
printf("The summation of all even
numbers in the array is: %d\n", sum_even);
return 0;
}
8.
Write a strategy to find the summation of all the even positioned numbers
stored in an array. Write a C program for the same. If the array elements are
{1, 2, 4, 3, 5, 6, 7, 7, 8}, the output of the program will be 18.
Answer:
The sum of all the
even-positioned numbers stored in the array {1, 2, 4, 3, 5, 6, 7, 7, 8}
is 18.
Step 1: Define the Strategy
To find the summation of all the
even-positioned numbers in an array (assuming 1-based indexing for positions),
the following strategy can be used:
1.
Initialize an integer
variable, for example sum_even, to zero.
2.
Iterate through the
array using a loop. The loop variable i should represent the 0-based index. Start i at 1 (the index of the second element,
which is the first even position) and increment i by 2 in each subsequent iteration.
3.
Inside the loop, add
the value of the array element at the current index i (e.g., array[i]) to sum_even.
4.
After the loop
finishes, the sum_even variable will
contain the total summation of all even-positioned numbers.
Step 2: Write the C Program
A C program implementing this strategy would
include the standard input/output library. The main function int main() would declare an integer array,
calculate its size, initialize a sum variable, use a for loop to iterate through the odd indices,
accumulate the sum, and finally print the result to the console using printf. The program structure without code blocks is
as follows:
#include
<stdio.h>
int main() {
int
array[] = {1, 2, 4, 3, 5, 6, 7, 7, 8};
int n =
sizeof(array) / sizeof(array[0]);
int sum
= 0;
for (int i = 1; i <
n; i += 2) {
sum +=
array[i];
}
printf("The
summation of all even-positioned numbers is: %d\n", sum);
return 0;
}
Answer:
The
summation of all the even-positioned numbers stored in the array {1, 2, 4, 3, 5,
6, 7, 7, 8} is 18.
9.
Write the logic to replace only the first occurrence of an element in an array.
For example, if the array elements are {1, 2, 3, 4, 5, 1, 2, 3} and we want to
replace element 3 by 0, the array content becomes {1, 2, 0, 4, 5, 1, 2, 3}.
Write a complete C program incorporating the logic.
Answer:
The
logic to replace only the first occurrence of an element in an array
involves iterating through the array until the target element is found,
replacing it, and then breaking the loop.
Step 1: Initialize Array and Variables
Initialize an integer array with the given
elements, along with variables to store the target element to
be replaced, the new value, and the size of
the array.
Step 2: Iterate and Find First Occurrence
Use a for loop to traverse
the array from the starting index (0). Inside the loop, use an if condition
to check if the current element arr[i] matches
the target value.
Step 3: Replace the Element and Terminate
Once the condition in Step 2 is met, replace
the value of the current element (arr[i]) with the newValue. Immediately after the replacement, use the break statement
to exit the loop, ensuring that no further occurrences are modified.
Answer:
c
#include <stdio.h>
// Function to replace
only the first occurrence of an element
void replaceFirstOccurrence(int
arr[], int size, int
target, int newValue) {
for (int
i = 0; i < size; i++) {
if
(arr[i] == target) {
arr[i] = newValue;
break;
// Exit loop after first replacement
}
}
}
int main() {
int array[] = {1, 2, 3, 4, 5, 1, 2, 3};
int target = 3;
int newValue = 0;
int size = sizeof(array)
/ sizeof(array[0]);
printf("Original array: ");
for (int
i = 0; i < size; i++) {
printf("%d
", array[i]);
}
printf("\n");
replaceFirstOccurrence(array, size, target, newValue);
printf("Array after replacing the first
occurrence of %d with %d: ", target, newValue);
// The final array contents should be {1,
2, 0, 4, 5, 1, 2, 3}
for (int
i = 0; i < size; i++) {
printf("%d
", array[i]);
}
printf("\n");
return 0;
}
10.
Write the logic to replace only the last occurrence of an element in an array.
For example, if the array elements are {1, 2, 3, 4, 5, 1, 2, 3} and we want to
replace element 3 by 0, the array content becomes {1, 2, 3, 4, 5, 1, 2, 0}.
Write a complete C program incorporating the logic.
Answer:
After replacing the
last occurrence of element 3 with 0 in the array {1, 2, 3, 4, 5, 1, 2, 3}, the
resulting array is {1, 2, 3, 4, 5, 1, 2, 0}.
Step 1: Logic Description
The logic to replace only the last occurrence
of a target element involves iterating through the array in reverse order,
starting from the last index. The first time the target element is encountered
during this reverse iteration, it is replaced with the new value. The process
is then terminated immediately using a break statement to ensure that no earlier occurrences are
modified.
Step 2: C Program Implementation
The following C program incorporates this
logic within a function called replaceLastOccurrence and demonstrates its use with the
example provided.
#include
<stdio.h>
void
replaceLastOccurrence(int arr[], int size, int target, int newValue) {
int i;
// Iterate from the end of the array to the
beginning
for (i = size - 1; i >= 0; i--) {
if (arr[i] == target) {
// Replace the last occurrence
found and break the loop
arr[i] = newValue;
break;
}
}
// If the loop completes without breaking,
the element was not found
}
int
main() {
int arr[] = {1, 2, 3, 4, 5, 1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int newValue = 0;
int i;
printf("Original array: {");
for (i = 0; i < size; i++) {
printf("%d%s", arr[i], (i ==
size - 1) ? "" : ", ");
}
printf("}\n");
replaceLastOccurrence(arr, size, target,
newValue);
printf("Array after replacing the last
occurrence of %d with %d: {", target, newValue);
for (i = 0; i < size; i++) {
printf("%d%s", arr[i], (i ==
size - 1) ? "" : ", ");
}
printf("}\n");
return 0;
}
Answer:
The
resulting array content after the operation is {1, 2, 3, 4, 5, 1, 2, 0}.
11.
Write a C program to replace all the even positioned elements in an integer
array by 0. For example, if the array elements are {1, 2, 3, 9, 5, 5, 7, 1, 9},
it becomes {1, 0, 3, 0, 5, 0, 7, 0, 9}.
Answer:
Step 1: Define the function and array
We include the standard input/output
library and define the main function. We initialize an integer array with the
example values provided:
{1,2,3,9,5,5,7,1,9}the set 1 comma 2
comma 3 comma 9 comma 5 comma 5 comma 7 comma 1 comma 9 end-set
{1,2,3,9,5,5,7,1,9}
.
Step 2: Iterate and modify
elements
We iterate through the array using a
for loop. The "even
positioned" elements in the human-readable list (2nd, 4th, 6th, etc.)
correspond to odd indices in 0-based programming (indices 1, 3, 5, etc.).
Inside the loop, we check if the current index i is odd (i % 2 != 0). If it is, we assign the value 0 to that element.
Step 3: Print the results
We print both the original and
modified arrays to show the transformation clearly.
Answer:
c
#include
<stdio.h>
int
main() {
int arr[] = {1, 2, 3, 9, 5, 5, 7, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: {");
for (int i = 0; i < n; i++) {
printf("%d%s", arr[i], (i ==
n - 1) ? "" : ", ");
}
printf("}\n");
// Replace even-positioned elements (odd
indices in 0-based index) with 0
for (int i = 0; i < n; i++) {
if (i % 2 != 0) {
arr[i] = 0;
}
}
printf("Modified array: {");
for (int i = 0; i < n; i++) {
printf("%d%s", arr[i], (i ==
n - 1) ? "" : ", ");
}
printf("}\n");
return 0;
}
12.
Write a strategy to replace all the odd numbers in an integer array by 0. For
example, if the array elements are {1, 2, 3, 9, 5, 5, 7, 1, 9}, it becomes {0,
2, 0, 0, 0, 0, 0, 0, 0}. Write a C program for the same.
Answer:
Step 1: Iterate Through the Array
Traverse the given integer array
from the first element to the last element using a loop (e.g., a for loop). The index of the current element, say
ii
𝑖
, will range from
00
0
to
n−1n minus 1
𝑛−1
, where
nn
𝑛
is the total number of elements in
the array.
Step 2: Check for Odd Numbers
At each index
ii
𝑖
, check if the current number array[i] is odd. An integer
xx
𝑥
is odd if the remainder when divided
by 2 is not zero. In C programming, this check can be performed using the
modulo operator %
with the condition array[i] % 2 != 0.
Step 3: Replace Odd Numbers
If the condition in Step 2 is true
(the number is odd), modify the value of the current element to zero: array[i]
= 0. If the number is even, leave the
element unchanged and continue to the next iteration of the loop.
Step 4: Complete the Iteration
Repeat Steps 2 and 3 for all
elements in the array until the loop finishes. The array will then contain all
original even numbers and zeros in place of the original odd numbers.
C Program
The following C program implements
the strategy described above. It includes the example array from the problem
description and prints the array before and after the replacement process to
demonstrate the functionality.
c
#include
<stdio.h>
void
replaceOddWithZero(int arr[], int size) {
for (int i = 0; i < size; i++) {
// Check if the number is odd
if (arr[i] % 2 != 0) {
arr[i] = 0; // Replace with 0
}
}
}
int
main() {
int numbers[] = {1, 2, 3, 9, 5, 5, 7, 1,
9};
int size = sizeof(numbers) /
sizeof(numbers[0]);
printf("Original array: {");
for (int i = 0; i < size; i++) {
printf("%d%s", numbers[i], (i
== size - 1) ? "" : ", ");
}
printf("}\n");
replaceOddWithZero(numbers, size);
printf("Modified array: {");
for (int i = 0; i < size; i++) {
printf("%d%s", numbers[i], (i
== size - 1) ? "" : ", ");
}
printf("}\n");
return 0;
}
Answer:
The modified array after replacing
all odd numbers with 0 for the input {1, 2, 3, 9, 5, 5, 7, 1, 9} is {0, 2,
0, 0, 0, 0, 0, 0, 0}.
13. Write a C program to store
your name and your mother’s name in two different strings. Display them one
after another.
Answer:
#include
<stdio.h>
#include
<string.h>
int
main() {
// Declare character arrays (strings) to
store the names.
// Size 50 is an arbitrary choice, ensure
it's large enough for the names.
char name[50];
char mother_name[50];
// Prompt the user to enter their name
printf("Enter your name: ");
// Read the name from standard input. fgets
is safer than scanf for strings
// because it prevents buffer overflows and
reads the entire line including spaces.
// It also reads the newline character,
which we might need to remove.
fgets(name, sizeof(name), stdin);
// Remove the trailing newline character
from the input
name[strcspn(name, "\n")] = 0;
// Prompt the user to enter their mother's
name
printf("Enter your mother's name:
");
// Read the mother's name from standard
input
fgets(mother_name, sizeof(mother_name),
stdin);
// Remove the trailing newline character
mother_name[strcspn(mother_name,
"\n")] = 0;
// Display the stored names
printf("\nYour name is: %s\n",
name);
printf("Your mother's name is:
%s\n", mother_name);
return 0;
}
Key Features of the Program:
·
#include <stdio.h>: This line
includes the standard input/output library, necessary for functions like printf and fgets.
·
#include <string.h>: This line
includes the string manipulation library, necessary for the strcspn function.
·
char name[50];: This declares a
character array (a C-style string) named name that can hold up to 49 characters plus a null terminator (\0).
·
fgets(...): This is used
instead of scanf for safer input handling as it reads the
entire line and prevents buffer overflows.
·
name[strcspn(name, "\n")] = 0;: fgets reads the
newline character (\n) into the string.
This line uses strcspn to find the
position of the newline and replaces it with a null terminator (\0), which properly ends the string for display.
·
printf(...): This function is
used to display prompts to the user and finally to print the stored names.
The %s format specifier is used to indicate a
string should be printed.
14. Write a C program to declare
3 integer type arrays to store the marks of 10 students scored in 3 different
subjects. Take another integer to store the average marks of the students. The
average mark of a student is the average of the marks scored by the student in
3 subjects. This should be calculated and inserted by the program. Then you
should display the average marks of the students. The program should also
display “PASS” or “FAIL” along with the average as per the rule: PASS if
average >= 45, FAIL otherwise.
Answer:
#include
<stdio.h>
#define
NUM_STUDENTS 10
#define
NUM_SUBJECTS 3
int
main() {
// Declare arrays for marks in 3 subjects
int marksSubject1[NUM_STUDENTS];
int marksSubject2[NUM_STUDENTS];
int marksSubject3[NUM_STUDENTS];
// Declare an array to store the average
marks
float averageMarks[NUM_STUDENTS]; // Using
float to handle potential decimal averages
// Input marks for each student
printf("Enter marks for %d students in
3 subjects:\n", NUM_STUDENTS);
for (int i = 0; i < NUM_STUDENTS; i++) {
printf("Student %d:\n", i +
1);
printf("Subject 1 marks: ");
scanf("%d",
&marksSubject1[i]);
printf("Subject 2 marks: ");
scanf("%d",
&marksSubject2[i]);
printf("Subject 3 marks: ");
scanf("%d",
&marksSubject3[i]);
}
// Calculate average marks and store them
for (int i = 0; i < NUM_STUDENTS; i++) {
int totalMarks = marksSubject1[i] +
marksSubject2[i] + marksSubject3[i];
// Cast to float for accurate average
calculation
averageMarks[i] = (float)totalMarks /
NUM_SUBJECTS;
}
// Display average marks and pass/fail
status
printf("\n--- Student Average Marks
and Status ---\n");
for (int i = 0; i < NUM_STUDENTS; i++) {
printf("Student %d: Average Marks
= %.2f, Status: ", i + 1, averageMarks[i]);
// Check for PASS/FAIL condition
if (averageMarks[i] >= 45) {
printf("PASS\n");
} else {
printf("FAIL\n");
}
}
return 0;
}
15. Write any two limitations of
arrays. Can you store your name and roll number in the same aray?
Answer:
Limitations of arrays
include their fixed size and the need for elements to be of the same data
type. You cannot store items of different types, like a string and an integer,
in the same array in most programming languages.
Limitations of Arrays
1.
Fixed
Size: In most languages,
the size of an array is determined at the time of creation and cannot be
changed during runtime. This requires developers to know the maximum number of
elements needed in advance.
2.
Homogeneous
Data Elements: An array is designed
to hold elements of a single, uniform data type. For example, an array declared
as an integer array can only store integers. Attempting to store another data
type will typically result in a compilation error or runtime error.
Storing Name and Roll Number
No, you cannot store
your name (a string) and roll number (an integer) in the same array in most
strictly-typed programming languages (like C, C++, or Java) due to the
limitation of homogeneous data elements.
To store related but
different types of information, alternative data structures are used, such
as:
·
Structures or Classes (in C, C++,
Java)
·
Objects (in JavaScript, Python)
·
Tuples (in Python, Swift)
·
Dictionaries or Hashmaps (in Python,
Java)