पिछले topic में आपने C++ में array के बारे में पढ़ा और समझा कि कैसे array को define करते हैं single elements को access करते हैं। इस topic में आप सीखेंगे कि for loop और while loop की help से कैसे array को traverse कर सकते हैं।


C++ में Array को आप for loop और while loop दोनों से traverse कर सकते हो।

c++ array traversal with while loop

CopyFullscreenClose FullscreenRun
#include <iostream>  
using namespace std;  
int main()  
{  
  string users[5] = {"Rahul", "Ravi", "Raju", "Ram", "Shyam"};
  int index=0;
  while( index < 5) {
    cout << "Index " << index << " : " << users[index] << endl;
    index++;
  }
  return 0;
} 
Output
Index 0 : Rahul
Index 1 : Ravi
Index 2 : Raju
Index 3 : Ram
Index 4 : Shyam

Note - Example में endl का use line break करने के लिए किया गया है।

c++ array traversal with for loop

ठीक इसी तरह आप for loop का use करके array traversing कर सकते हैं।

CopyFullscreenClose FullscreenRun
#include <iostream>  
using namespace std;  
int main()  
{  
  string users[5] = {"Rahul", "Ravi", "Raju", "Ram", "Shyam"};
  for(int index=0; index < 5; index++) {
    cout << "Index " << index << " : " << users[index] << endl;
  }
  return 0;
} 
Output
Index 0 : Rahul
Index 1 : Ravi
Index 2 : Raju
Index 3 : Ram
Index 4 : Shyam

c++ access array element

हालाँकि आप for loop की help से directly array element को भी access कर सकते हैं।

CopyFullscreenClose FullscreenRun
#include <iostream>  
using namespace std;  
int main()  
{  
  string users[5] = {"Rahul", "Ravi", "Raju", "Ram", "Shyam"};
  for(string name : users) {
    cout << name << endl;
  }
  return 0;
} 
Output
Rahul
Ravi
Raju
Ram
Shyam

I Hope, अब आपके अच्छे से समझ आ गया होगा कि C++ में किस तरह से Array Traversing करते हैं।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers