Arrays and Loops
Arrays and Loops
Arrays and Loops
• You can loop through the array elements with the for loop.
• int main() {
• string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
• for (int i = 0; i < 5; i++) {
• cout << cars[i] << "\n";
• }
• return 0;
• }
output
• Volvo
BMW
Ford
Mazda
Tesla
This example outputs the index of each
element together with its value:
• #include <iostream>
• #include <string>
• using namespace std;
• int main() {
• string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
• for (int i = 0; i < 5; i++) {
• cout << i << " = " << cars[i] << "\n";
• }
• return 0;
• }
• 0 = Volvo
1 = BMW
2 = Ford
3 = Mazda
4 = Tesla
• #include <iostream>
• using namespace std;
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• for (int i = 0; i < 5; i++) {
• cout << myNumbers[i] << "\n";
• }
• return 0;
• }
• 10
20
30
40
50
Omit Elements on Declaration
• It is also possible to declare an array without specifying the elements on declaration, and add them later:
#include <iostream>
• #include <string>
• using namespace std;
• int main() {
• string cars[5];
• cars[0] = "Volvo";
• cars[1] = "BMW";
• cars[2] = "Ford";
• cars[3] = "Mazda";
• cars[4] = "Tesla";
• for(int i = 0; i < 5; i++) {
• cout << cars[i] << "\n";
• }
• return 0;
• }
output
• Volvo
BMW
Ford
Mazda
Tesla
Check Vowel or consonant using switch case statements without the
break
• #include <iostream>
• #include <conio.h>
• using namespace std;
• int main()
• {
• char ch;
• cout<<"Enter any Alpabet\n"; //input alphabet from user
• cin>>ch;//store the Entered Alphabet in ch
• switch(ch){
• //check lower case vowel letters
• case 'a':
• case 'e':
• case 'i':
• case 'o':
• case 'u':
• //check upper case vowel letters
• case 'A':
• case 'E':
• case 'I':
• case 'O':
• case 'U':
• cout<<ch<<" is a vowel";
• break;
• default:
• cout<<ch<<" is a consonant";
• break;
• }
• getch();
• return 0;
• }
When the above code is executed, it produces the following result
case 1
Enter any Alphabet i i is a vowel
case 2
Enter any Alphabet U U is a vowel
case 3
Enter any Alphabet H H is a consonant