C Language | Structure and Union: Basic Programs

Example:4
C program to declare a structure named student with attributes as roll, name, m1, m2, m3, total, and per. Take input for the details, calculate and display total, and per.
Sol:

#include<stdio.h>
struct student
{
    int roll;
    char name[20];
    float m1,m2,m3,total,per;
};
//}s;

//struct bank s;

int main()
{

    struct student s;
    printf("Enter roll,name,m1,m2, and m3 ");
    scanf("%d %s %f %f %f",&s.roll,s.name,&s.m1,&s.m2,&s.m3);
    s.total=s.m1+s.m2+s.m3;
    s.per=s.total/3;
    printf("Total %.3f Per %.2f\n",s.total,s.per);
    return(0);
}
/* Output */
Enter roll,name,m1,m2, and m3 101
Amit
98
95
96
Total 289.000 Per 96.33

Example:5
C program to declare a structure named product with attributes as product number, product name, rate, quantity, and cost. Product:(pno,name,rate,qty,cost). Take input for the details, calculate and display the cost of the product.
Sol:

#include<stdio.h>
struct product
{
  int pno;
  char pname[15];
  float rate,qty,cost;
}p;
//struct product p;
int main()
{
    //struct product p;
    printf("Enter pno,pname,rate and qty ");
    scanf("%d %s %f %f",&p.pno,p.pname,&p.rate,&p.qty);
    p.cost=p.rate*p.qty;
    printf("cost = %.2f\n",p.cost);
    //getch();
    return(0);
}
/* Output */
Enter pno,pname,rate and qty 1001
Lux
45
6
cost = 270.00

Example:6
C program to declare a structure named book with attributes as book code, book title, price , number of copies and total cost. Book (bcode, btitle, price, noc, cost). Take input for the details calculate and display cost of the books.
Sol:

#include<stdio.h>
struct book
{
  int bcode;
  char btitle[15];
  float price,noc,cost;
}b;
//struct book b;
int main()
{
    //struct book b;
    printf("Enter bcode,btitle,price and noc ");
    scanf("%d %s %f %f",&b.bcode,b.btitle,&b.price,&b.noc);
    b.cost=b.price*b.noc;
    printf("cost = %.2f\n",b.cost);
    //getch();
    return(0);
}
/* Output */
Enter bcode,btitle,price and noc 1002
C
256
3
cost = 768.00

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects