In: Computer Science
LANGUAGE C
Code function:
I wanted to create an array, i.e. index[100], and store 3 elements into it.
The elements that i wanted to store is from the same variable, however its value will always change in the while loop
e.g. index[0]=1, index[1]=3, index[2]=5
However it seems that my code has a problem that my compiler warns me that the variable index is set but not used. And also, is it not possible to store the elements into the array using the while loop in my code? As i am not familiar with c language. Can sir/madam fix the codes below and teaches the proper way?
NOTE: i use gcc compiler in unix environment. Any assistance is very much appreciated in advance
#include <stdio.h>
int main(){
int c=0;
int j=2;
int i=0;
int index[100];
int a=1;
while(c<=j){
index[c]=a;
a+=2;
c+=1;
}
for(i=0;i++;i<=j){
printf("%d",index[i]);
}
}
Well you have done everything correct and while loop is working fine to store elements, only fault was in the for loop which you used for printing.
Updated Code:
#include <stdio.h>
int main(){
int c=0;
int j=2;
int i=0;
int index[100];
int a=1;
while(c<=j){
index[c]=a;
a+=2;
c+=1;
}
for(i=0;i<=j;i++){ // I changed here
printf("%d",index[i]);
}
}
Output:
135
Explanation:
The fault was inside for loop your loop statement was for(i=0;i++;i<=j) and based on the syntax of for loop it has to be for(i=0;i<=j;i++)
In simple terms to remember the syntax of for loop you consider it to be as 3 part where
1st part in initialization of loop (i=0)
2nd part is like the condition which will terminate the code or stop the for loop when you need it to be stoped (i<=j)
3rd part is like an increment statement for variable of for loop (i++)
If you ever feel like code is not storing value try printing the value at that index for example you know index[0]=1 so you can write printf("%d",index[0]) just to verify if there is a fault in code which is used for printing or in code for storing data in array .