Search code examples
cstore

C, how to store values in a for loop , can it be done without arrays?


The assignment asks :

The program must calculate the surface of the house The user must input the number of rooms he has, and then the program must ask the lenght and witdh of each room. After that the program must show the surface of the house. No formula is provided, but the surface of a room is lenght*width.

The problem with my application is that in the for loop the value of the sum of all lenghts and withs of each room is not remembered. So the output is wrong. Can it be done without arrays? Because i haven't reached that lesson yet and have alot of other assignments i need to complete. Thanks alot.

#include <stdio.h>
#include <stdlib.h>

main()
{
int camere,lungime,latime,scamere,i,scamera,scameratotal,scasa,total;


printf("Acest program calculeaza suprafata casei\n");    //this program lists the surface of the house
printf("Cate camere are casa?\n");  // how many rooms do you have?
scanf("%d",&camere);

for(i=0;i<camere;i++)
{

printf("Introduceti lungimea si latimea camerei %d\n",i);   //enter the lenght and width of room %d

scanf("%d %d",&lungime,&latime);


scamera=lungime*latime;    //surface of room %d is lenght*width

printf("Suprafata camerei %d este %d\n",i,scamera);  //states the surface of room %d (1 , 2 or 3 etc.)


total = total + (lungime*latime);   // total that i want the program to remember
scasa=total*camere;                 //surface of the house is total*number of rooms


}

printf("\nSuprafata casei este de %d metri",scasa);  //the surface of the house , bad output , it's not  total(sum of surfaces of each room)*number of rooms
}

Solution

  • declare another int called total

    at the end of your for loop update the total

    total += lungime*latime;
    

    total will have the total floor space at the end after the loop