C Programming for Beginners: Practice Problem and Step-by-Step Solution.
Q1.Write a C program to illustrate the comparison of two structure variables and print equal or not taking individual members.
SOLUTION:-
#include <stdio.h>
typedef struct {
int num1;
float num2;
char ch;
} MyStruct;
int main() {
MyStruct data1 = {10, 3.14, 'A'};
MyStruct data2 = {10, 3.14, 'A'};
int all_equal = 1; // Flag to track overall equality
// Compare entire structures using memcmp (for basic data types)
if (memcmp(&data1, &data2, sizeof(data1)) != 0) {
all_equal = 0;
printf("Structures are NOT equal\n");
}
// If overall equality hasn't been determined as false yet,
// compare individual members for confirmation
if (all_equal) {
if (data1.num1 != data2.num1) {
all_equal = 0;
printf("num1 values differ\n");
}
if (data1.num2 != data2.num2) {
all_equal = 0;
printf("num2 values differ\n");
}
if (data1.ch != data2.ch) {
all_equal = 0;
printf("ch values differ\n");
}
}
if (all_equal) {
printf("Structures are equal\n");
}
return 0;
}
Explanation:
- We define a structure named
MyStructwith three members:num1(integer),num2(float), andch(character). - In
main, we create two instances ofMyStruct(data1anddata2) and initialize them with the same values. - We introduce a flag
all_equalinitialized to 1, assuming equality initially. - We use
memcmpto compare the entire memory representation of the two structures. If any byte differs,memcmpreturns a non-zero value, indicating they are not equal. We setall_equalto 0 and print a message. - If
memcmpdidn't find a difference yet (all_equalis still 1), we proceed to compare individual members using member access operators (data1.num1, etc.) and print specific messages if any member differs. - Finally, based on the
all_equalflag, we print a message indicating whether the structures are entirely equal or not.
This program demonstrates both approaches:
- Comparing the entire structure using
memcmp(suitable for basic data types) - Comparing individual members for more detailed information
Note:
memcmpmight not be suitable for structures containing pointers or complex data types due to potential padding by the compiler. In such cases, individual member comparison is necessary.
Q2.Write a program to add two times using structure.
#include <stdio.h>
struct Time {
int hours;
int minutes;
int seconds;
};
struct Time add_times(struct Time time1, struct Time time2) {
struct Time result;
// Add hours, handling overflow
result.hours = time1.hours + time2.hours;
if (result.hours >= 24) {
result.hours %= 24;
}
// Add minutes, handling overflow
result.minutes = time1.minutes + time2.minutes;
if (result.minutes >= 60) {
result.minutes %= 60;
result.hours++; // Carry over to hours if minutes overflow
}
// Add seconds, handling overflow
result.seconds = time1.seconds + time2.seconds;
if (result.seconds >= 60) {
result.seconds %= 60;
result.minutes++; // Carry over to minutes if seconds overflow
}
return result;
}
int main() {
struct Time time1, time2, total_time;
// Get input for time1
printf("Enter time1 (hours minutes seconds): ");
scanf("%d %d %d", &time1.hours, &time1.minutes, &time1.seconds);
// Get input for time2
printf("Enter time2 (hours minutes seconds): ");
scanf("%d %d %d", &time2.hours, &time2.minutes, &time2.seconds);
// Add the times using the add_times function
total_time = add_times(time1, time2);
// Display the result
printf("Sum of times: %02d:%02d:%02d\n", total_time.hours, total_time.minutes, total_time.seconds);
return 0;
}
Explanation:
- We define a structure named
Timewith three members:hours,minutes, andsecondsto represent time. - We define a function
add_timesthat takes twoTimestructures as arguments and returns a newTimestructure containing the sum. - Inside
add_times:- We create a new
Timestructure namedresultto store the sum. - We add the
hours,minutes, andsecondsoftime1andtime2and store them inresult. - We handle overflow for each unit (hours, minutes, seconds):
- If
hoursexceed 23, we take the modulo by 24 to keep the result within the 0-23 hour range. - If
minutesexceed 59, we take the modulo by 60 and incrementhoursby 1 to carry over the overflow. - If
secondsexceed 59, we take the modulo by 60 and incrementminutesby 1 to carry over the overflow.
- If
- We create a new
- In
main:- We declare three
Timestructures:time1,time2, andtotal_time. - We prompt the user to enter the values for
time1andtime2. - We call the
add_timesfunction to calculate the sum and store it intotal_time. - We use
%02dformat specifier inprintfto ensure two-digit display for hours, minutes, and seconds.
- We declare three
This program effectively adds two times represented by structures, handling potential overflows for each unit.
Q3.Write a program to create a pointer variable and display the address and value using pointer variable.
#include <stdio.h>
int main() {
int num = 10; // Create an integer variable
int *ptr; // Declare a pointer variable of type 'int'
// Assign the address of 'num' to the pointer 'ptr'
ptr = #
printf("Address of num: %p\n", ptr); // Print the address stored in ptr
printf("Value stored at address pointed by ptr: %d\n", *ptr); // Print the value using dereferencing
return 0;
}
Explanation:
- We include the
stdio.hheader for standard input/output functions likeprintf. - In
main, we declare an integer variablenumand initialize it with the value 10. - We declare a pointer variable
ptrof typeint. A pointer variable stores memory addresses, in this case, addresses of integer variables. - We use the address-of operator (
&) to get the memory address ofnumand assign it toptr. Now,ptrpoints to the memory location wherenumis stored. - We use the
printffunction to display the address stored inptrusing the%pformat specifier, which is used for pointers. - To access the value stored at the memory location pointed to by
ptr, we use the dereference operator (*). So,*ptris equivalent to the value ofnum. We useprintfagain to display this value using the%dformat specifier for integers.
This program demonstrates the basic concepts of pointers in C:
- Declaring a pointer variable
- Assigning an address to a pointer
- Dereferencing a pointer to access the value it points to
