C : What is the purpose of the 'union programmingLang' in this C program ?

Programmer Portfolio
2 min readNov 1, 2023

--

Program :

#include<stdio.h>

union programmingLang
{
char pName[50];
int rank;
};

int main()
{
union programmingLang prm[5];

printf("Enter your 5 favourite programming languages :\n");

for(int i=0; i<5; i++) {
scanf("%s", &prm[i].pName);
}

printf("\nList of favourite programming languages : \n");

for(int i=0; i<5; i++) {
printf("%s\n", prm[i].pName);
}

return 0;
}

Output :

Explanation :

This C program allows a user to input their 5 favorite programming languages and then displays the list of these languages. Here’s a step-by-step explanation:

1. The program includes the standard input/output library (`#include <stdio.h>`).

2. It defines a union named "programmingLang," which can store either an array of 50 characters (for the name of a programming language) or an integer (for the rank of a programming language).

3. In the `main()` function:
- It declares an array `prm` of five `programmingLang` unions. This array will hold the input data.
- It prompts the user to enter their 5 favorite programming languages using `printf`.

4. It then uses a `for` loop to iterate five times, and within each iteration:
- It uses `scanf` to read a string (the name of a programming language) from the user and store it in the `pName` field of the `programmingLang` union. The `&` operator is used because `scanf` expects a pointer to the variable where it should store the input.
- The user's input is stored in `prm[i].pName`.

5. After collecting the input, the program displays the list of favorite programming languages using another `for` loop:
- It prints each of the stored language names (in `prm[i].pName`) using `printf`.

6. Finally, the program returns 0, indicating successful execution.

Note: This program uses a `union` to store either a string (array of characters) or an integer for each entry in the array, but it doesn't use the `rank` field in this code. Also, it doesn't provide any error handling for input exceeding the 50-character limit, which may lead to buffer overflow issues.

(explanation and title credit goes to CHAT GPT)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Programmer Portfolio
Programmer Portfolio

Written by Programmer Portfolio

Code enthusiast. Learning, practicing, and sharing my journey through various programming languages, one code at a time. 🚀💻

No responses yet

Write a response