0

Why do we use structures in c if we can run a program just by declaring datatypes n relevent variables

Just like given code #include <stdio.h> int main() { char info[100]; char dept[ ] = "HR"; int emp = 75; sprintf(info, "The %s dept has %d employees.", dept, emp); printf("%s\n", info); return 0; }

20th Jan 2020, 1:17 PM
Farjana Shaik
Farjana Shaik - avatar
8 Respuestas
+ 5
Use structure when there's a need to group various types of data into, or as an entity. For example, taking your code, you can create a structure named "department", having a C-String as <name> and int as <emp>. Then you can create an array of that structure, each with different name, and number of employees.
20th Jan 2020, 1:28 PM
Ipang
+ 4
what would you do if you have 20 or more employees? would you write 20 of those variables for each emp?
20th Jan 2020, 1:22 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 4
AZTECCO I'm glad no one asked what entity means. I think it will be hard for me to explain, I just read something like that somewhere before bro 😂
21st Jan 2020, 1:10 PM
Ipang
+ 3
An example: I have just written a permutations function that is based on an algorithm where each element in the list will be shifted around, but also each element has a direction, in which it wants to move next. (I have linked an article about the algorithm in the code.) So by making a struct DirectedInteger that has both the original index and the direction stored, I can put several of them into an array, and at each point of the back and forth shifting access the number and its direction of every element. https://code.sololearn.com/cjnQHfjKjZm5/?ref=app
20th Jan 2020, 1:36 PM
HonFu
HonFu - avatar
+ 3
Ipang +1 for using 'entity' 👍
21st Jan 2020, 12:26 PM
AZTECCO
AZTECCO - avatar
+ 3
Don't worry it's not a complicated concept.. they are essentially everything we declare. Take a look at the docs https://en.cppreference.com/w/cpp/language/basic_concepts
21st Jan 2020, 1:39 PM
AZTECCO
AZTECCO - avatar
+ 3
Funny, I didn't even think about the word 'entity', I thought it's roughly synonymous with object. Now after that link, I'm not so sure anymore. 😅
21st Jan 2020, 1:47 PM
HonFu
HonFu - avatar
+ 2
AZTECCO Thanks again bro 🙏
21st Jan 2020, 1:41 PM
Ipang