help me with basics

+1 nikhil kumar · February 15, 2015
guys new to c language having problems with arrays plss help ......point out the errors in it



    int i,n[22];

printf("enter marks of 20 students");

Post a Reply


Oldest  Newest  Rating
+1 Homer Simpson · February 16, 2015
No bro n[22] starts at n[0] and ends with n[21] 
0 Ivo Ferro · February 15, 2015
Hey @nikhil

When you define an array with 22 indexes as u did, the first position is 0 and the last is 21.
To read an array position, you need to point out what is the index that you want to read.
If you want to read the 3rd position of the array, you would do scanf("%d", &n[2]);

So, the correct way to do it, is to make a for that starts on 0 and ends on 21. And dont forget to indicate what is the position that you want to read: scanf("%d", &n);
If u want to make a for that starts on 1 and ends on 22, like u did it, you need to decrement a value from "i" when you reading it: scanf ("%d", &n[i-1]);

Exemple for 5 marks:

#include <stdio.h>

int main()
    int i,n[5];

    for(i=0 ; i<5 ; i++)
        printf("what is the mark of %d student?\n", i+1);
    for(i=0 ; i<5 ; i++)
        printf("The mark of %d student is %d\n", i+1, n);

0 Lazar Bulic · February 15, 2015
Ok there are 2 mistakes, both related to arrays.

so when u declare your array int n[22] you just reserved 22 spaces for your int values inside the array.

So it goes like this:


Other thing is how to add values to int. You started good, with for(){} but it needs some work. So here is the code. I hope you understand it if not please tell me and I will explain it: 
0 Homer Simpson · February 15, 2015
Unless I'm mistaken. You only want to enter in 20 students. So why are you allocating memory for 22?
n[22] = 22 spaces not 23.

You didn't really explain what issue it was you were having. 

A simple program that prompts the user to enter in the marks
of 20 students.


#define NUM_OF_STUDENTS 20 /* Total number of students in class. */

int main(void)
    int i, n[NUM_OF_STUDENTS];

    for(i = 0; i < NUM_OF_STUDENTS; i++){
        printf("Enter in the mark for student #%d: ", i + 1); /* Prompt the user. */
        scanf("%d", &n{i}); /* Store results */

    return 0;

Edit: If your scanf("%d", &n) was really an array like this scanf("d", &n{i}) and the site just removed them then thats your issue. Arrays start at element 0.
n[0] ... n[19]. = 20 elements. You're initiating i = 1. so when u loop through you're skipping the first element.
0 Lazar Bulic · February 16, 2015
Yup my mistake :(
0 Homer Simpson · February 16, 2015
Lol it's all good. :) 
0 nikhil kumar · February 16, 2015
thanks a lot guys..............mind if i ask some more questions later ??
0 Lazar Bulic · February 16, 2015
nope, we are here to help :)
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator