# For loop over histograms

**URL:** <https://root-forum.cern.ch/t/for-loop-over-histograms/33645>\
**Category:** Newbie\
**Created:** [April 17, 2019, 1:29pm UTC](https://root-forum.cern.ch/t/for-loop-over-histograms/33645 "2019-04-17T13:29:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Marta](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/marta/32/18269_2.png) [@Marta](https://root-forum.cern.ch/u/Marta)\
**Post date:** [April 17, 2019, 1:29pm UTC](https://root-forum.cern.ch/t/for-loop-over-histograms/33645/1 "2019-04-17T13:29:36Z")

</div>

Hello.  
I have a problem with creating hstack. I have a bunch of histograms in different .root files and I want to add them. I know how to do that, but because there is so many of them and they all look like zmumu1.root, zmumu2.root etc, I would like to make a for loop. As I am fairly new to programming, I found a piece of program from [stackoverflow.com](http://stackoverflow.com) that should work, I got some ideas from couple posts here, and tried to make it work for me:

```auto
   char zmumu[14];                                                         
   for(Int_t i=1; i<13; i++){
    sprintf(zmumu, "%s%d","zmumu",i);
   TFile *zmumu = TFile::Open("zmumu[i].root");
   TH1F *h = (TH1F*)gDirectory->Get("h_muon0_pt");                                             
   h0->Add(h);
  }

```

(Not that I would really understand it. To be honest, I have no idea what sprintf ought to do.) I keep getting error message “Error in TFile::TFile: file zmumu[i].root does not exist”. Apparently, it does not do anything. Any ideas how to solve this?  
Thank you very much.

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [April 17, 2019, 1:37pm UTC](https://root-forum.cern.ch/t/for-loop-over-histograms/33645/2 "2019-04-17T13:37:11Z")

</div>

Try:

```auto
THStack *h0 = new THStack("h0", "my stack");
for(Int_t i = 1; i < 13; i++) {
  TFile *f = TFile::Open(TString::Format("zmumu%d.root", i));
  if ((!f) || f->IsZombie()) { delete f; continue; } // just a precaution
  TH1F *h; f->GetObject("h_muon0_pt", h);
  if (!h) { delete f; continue; } // just a precaution
  h0->Add(h);
}

```

---

<div class="post-metadata">

**Author:** ![Marta](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/marta/32/18269_2.png) [@Marta](https://root-forum.cern.ch/u/Marta)\
**Post date:** [April 18, 2019, 12:07pm UTC](https://root-forum.cern.ch/t/for-loop-over-histograms/33645/3 "2019-04-18T12:07:00Z")

</div>

Thank you very much, that’s perfect!
