Array

Make only one change to the program below so that the current output changes to the desired output.

Desired output:
Monday
onday
nday
day
ay
y

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>
using namespace std;

int main() {

    char *weekDays[7] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    
    for (int i=0; i<7; i++){
        cout << weekDays[0][i] << endl;

    }
    
    
	return 0;
}
Last edited on
Hint: What is weekDays[0] by itself print out?

What type is weekDays[0]? It's a pointer to char. In this case, it's a pointer to the first character of a string literal. A pointer to the second character of weekDays[0] would be...?

PS: whatever resource you are reading is outdated, because pointers to string literals should be const char*, not just char*.
Last edited on
A pointer to the second character of weekDays[0] would be weekDays[0][1]?
This seems to work:
1
2
3
4
5
6
7
8
9
10
11
12
13
  #include <iostream>
using namespace std;

int main() {

    const char * weekDays[7] 
 = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    
    for (int i=0; i<7; i++)  cout << weekDays[0]+i << endl;
    
    
	return 0;
}


I also made the char* array to const char*, which is the correct way of using string literals.
yes it works thank u.
No, weekDays[0][1] is an individual character. But I guess you got your answer despite probably not understanding it.

If you used the & (address of) operator, you'd only need to add one character to your original program.

cout << char* type interprets the char* as a pointer to a null-terminated char array.
Last edited on
Topic archived. No new replies allowed.