-4

There is an array of n students( stu[n]).If gender is boy then my code adds

  • for boy b, 2nd,4th,6th,........even position elements of array and
  • for girl g, 1st,3rd,5th....odd position elements of array.

1> Gender of boys denoted by b. 2> Gender of girls denoted by g.

Input info>>

  1. The 1st line contains n, denoting the number of students in the class, hence the number of elements in the array.
  2. Each of the subsequent lines contains the marks of n students .
  3. The last line contains gender b/g;

Output info>>

The output should contain the sum of all the alternate elements of marks as explained above.

#include <stdio.h>

int main() {
int n,i;
scanf("%d",&n);//n denotes number of students.
int stu[n],sum=0;


for(i=1;i<=n;++i)
scanf("%d",&stu[i]);//for accepting input in array.

char gen;
scanf("%s",&gen);//for accepting input gender b/g.


 for(i=1;i<=n;i++){
 if(gen=='g' && i%2!=0){ //girl g adds alternate odd position  elements.
sum=sum+stu[i];
printf("%d",sum);
}

else if(gen=='b' && i%2==0){ //boy b adds alternate even position elements.

sum=sum+stu[i];
printf("%d",sum);
}

}
//code
return 0;
}

Sample Input

3 3 2 5 b

Sample Output 8

explanation>> marks=[3,2,5] and gender = b so it will add 3+5(even position 0,2 alternate elements). If gender in place of b is g then it will produce output = 2.

My code is shows output of 0 in all test cases.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

4 Answers4

1

You have the major problem in

int n,i;
int stu[n],sum=0;

here, n being a uninitialized local scoped variable with automatic storage, the initial value is indeterminate.

Now, since the address of the variable was never taken and it has a type that can have trap representation, attempt to use the value (int stu[n]) will invoke undefined behavior.

You need to scan in the value into n first, then use that to define the VLA stu. Something like

int n,i;
scanf("%d",&n);//n denotes number of students.
 // **Note: please check for errors in input with scanf return value.**
int stu[n],sum=0;   // here, n has the scanned value.

That said,

char gen;
scanf("%s",&gen);

is also horribly wrong, you want to scan in a char, not a string, and with the address of a plain char variable, %s conversion specification would be UB, again. You should use %c and discard any whitespaces which is present in buffer altogether.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Even after edit it shows no output.Please help again. –  Jul 18 '19 at 13:06
  • @AYUSHAZAD Can you please show after reading the answer what you tried and how it failed? – Sourav Ghosh Jul 18 '19 at 13:07
  • I placed scanf on the right place and also changed !== to != which i saw later but still compiler shows no output.The positions of brackets may be wrong,but i dont think so.I ran it both on code chef and geeks compiler.I am a beginner and i don't deal much with pointers as i feel lack of practice and too early to apply>>like int *marks ,so i used vla and for loop. –  Jul 18 '19 at 13:22
  • @AYUSHAZAD It's not about pointers or not, whatever you use, make sure you're using them correctly. – Sourav Ghosh Jul 18 '19 at 13:25
  • Still not showing any output (%s was changed to %c) –  Jul 18 '19 at 13:37
  • I think i should try another question and not waste time on this problem. –  Jul 18 '19 at 13:40
0

You're making things more complicated than they need to be. Here is how you can possibly do:

#include <stdio.h>

int main(void)
{
    int mark;
    int b = 0;
    int g = 0;
    char students_marks[5];

    for (int i=0; i<5; i++) {
        scanf("%d", &mark);
        students_marks[i] = mark;
    }
    for (int i=0; i<5; i++) {
        if (i%2 == 0) b += students_marks[i];
        if (i%2 == 1) g += students_marks[i];
    }
    printf("Boys: %d\nGirls: %d\n", b, g);
    return 0;
}
ooj-001
  • 180
  • 9
  • We can not add input {4,5,6,7,8} as the problem says we have to accept input by user using scanf and array size can be random n;So can you please suggest some more improvement .I am a beginner and trying it to get it right from many hours. –  Jul 18 '19 at 13:51
  • Loop over a `scanf` and add the value scanned to your array and you're done. – ooj-001 Jul 18 '19 at 13:59
  • Ok I looped over scanf but still b and g are char values why did you used it in int?? –  Jul 18 '19 at 14:09
  • Note that you don't need these `char` because the condition is whereas it's even or uneven; you pick one, the other is useless. Also in your nested `if-else` condition in your `for` loop, you do exactly the same thing. – ooj-001 Jul 18 '19 at 14:17
  • I have to write b or g gender as input char in haker rank compiler then only the if else statement will run accordingly as even or odd?? Can you read the question again and please help me again ?Here is the link for proper explanation https://hackerrank-challenge-pdfs.s3.amazonaws.com/66953-students-marks-sum-English?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1563463575&Signature=O%2FrKil3th2w7YHhoZYQRZ9Z8j5s%3D&response-content-disposition=inline%3B%20filename%3Dstudents-marks-sum-English.pdf&response-content-type=application%2Fpdf –  Jul 18 '19 at 14:28
  • I have to get b or g gender as an input in the hakerank compiler and then if else satement will run accordingly .You should please read the question again and see the test cases and then try again. –  Jul 18 '19 at 14:32
  • The last line of input info says>>last line contains gender b/g; –  Jul 18 '19 at 14:34
0

You should probably not use an array, and just ignore the first data point. It is (probably) easier to use a linked list. Or maybe just use two lists, alternating the inputs between them. And I would definitely not use scanf. If you are new to C, do NOT waste your time learning the foibles of the scanf format string language. The only time scanf is ever useful is in introductory courses where instructors incorrectly believe that you will be able to get input more quickly than if you spend time learning other methods. But in fact you will end up burning more time learning when to use spaces in the format string that you saved by not learning fread. After your introduction to C, you will (almost) never use scanf. Also, it seems like a horrible design to put the discriminant at the end of the input. The values to be summed (the gender) should be given as a command line argument. That said, you could just do:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

FILE *
xfopen(const char *path, const char *mode)
{
        FILE *rv;
        if( (rv = fopen(path, mode)) == NULL ) {
                perror(path);
                exit(EXIT_FAILURE);
        }
        return rv;
}

int
main(int argc, char **argv)
{
        int i;
        int size;  /* Should probably be size_t.  Skipping that for now. */
        FILE *in = argc > 1 ? xfopen(argv[1], "r") : stdin;
        int sum = 0;
        if( fscanf(in, "%d", &size) != 1 || size <= 0 ) {
                fprintf( stderr, "invalid input\n" );
                exit(EXIT_FAILURE);
        }
        int grades[size];
        for( i = 0; i < size; i++ ) {
                if(fscanf(in, "%d", grades + i) != 1) {
                        fprintf( stderr, "invalid input on line %d\n", i );
                        exit(EXIT_FAILURE);
                }
        }
        char gender;
        if(fscanf(in, " %c", &gender) != 1) {
                fprintf( stderr, "invalid input on line %d\n", i );
                exit(EXIT_FAILURE);
        }
        if(strchr("bBgG", gender) == NULL) {
                fprintf( stderr, "invalid gender: %c\n", gender);
                exit(EXIT_FAILURE);
        }
        for( i = tolower(gender) == 'b'; i < size; i += 2 ) {
                sum += grades[i];
        }
        printf("sum: %d\n", sum);
}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Thanks for this new method but I am a beginner in c language .It has been only 20 days since i sarted learning coding using books and youtube.I have not touched the chapter --file management in c which i think you have used. –  Jul 18 '19 at 14:56
  • file management here is extremely minimal. If you want to remove it, just write `FILE *in = stdin`, or just use `stdin` wherever I've use `in`. – William Pursell Jul 18 '19 at 14:58
  • Can you give some tips to learn pointers ,maalloc,calloc dyanamic memory ,structure union which i find tough ??Sometime i get confused and depressed weather should i read book first or watch videoes and then solve problems on hakerank .What was your strategy for quick learning and leveling up. –  Jul 18 '19 at 15:02
  • I don't think there's "quick learning". For me, the process was long and arduous, with many segmentation faults. When something bizarre happens, jump into gdb and track it down. Mostly, though, it's trying things. You would IMO learn more from this problem by ignoring the first input and either putting data into linked lists or reallocating an array as needed when more data arrives. – William Pursell Jul 18 '19 at 15:09
  • Probably because you are writing outside the bounds of the array. – William Pursell Jul 18 '19 at 15:14
  • Thanks William,love from INDIA –  Jul 18 '19 at 15:14
0

Hmm… i changed your code a Little bit and hope this runs as described.

int main() {

       int n, index, sum=0;
       int* stu;
       scanf("%d", &n); // input number of studens

       if(n>0)
          stu = malloc(n*sizeof(int)); // allocate memory
       else
          return 0;

       for(index=0;index<n;index++)
          scanf("%d", &stu[index]);

       char gen;
       scanf("%c", &gen);

       for(index=0; index<n; index++){
          if(gen=='g' && index%2!=0) {
             sum += stu[index];
             printf("%d", sum);
          } else if(gen=='b' && index%2==0) {
             sum += stu[index];
             printf("%d", sum);
          }
       }

       return 0;
    }
dubka
  • 22
  • 5