Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

"String index our of range"

0 votes
asked May 23, 2020 by 平秀明 (120 points)
Trying to run this code ends with "string index out of range" error. What is wrong with it?

num_str = input()
n = len(num_str)
i = 0
sum = 0
while i<n:
    i=i+1
    a=int(num_str[i])
mean = sum / n

3 Answers

0 votes
answered May 24, 2020 by Raed Zahr (140 points)
num_str = input()
n = len(num_str)
i = 0
sum = 0
while i<n-1:
    i=i+1
    a=int(num_str[i])
mean = sum / n
+1 vote
answered May 24, 2020 by prashastha kovuri (160 points)

change line 2 as

n = len(num_str)-1

since array indexing starts from 0..Therefore the last element will be present at index (n-1) and if you try to access element n it gives you an error

0 votes
answered May 24, 2020 by rgajjar (180 points)
I am not exactly sure what you are trying to compute, but I have tried to write a relatively clear C code of what you might have been trying to do above.

I have included certain "printf" statements for you to check few validations.

/******************************************************************************

                            Online C Compiler.
                Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <stdio.h>
#include <string.h>
int main()
{
    printf("Hello World\n");
    
    //num_str = input();
    char num_str[30];
    printf("Enter a string: ");
    scanf("%s",num_str);
    
    int n =0 ;
    n = strlen(num_str);
    printf("strlen: %d\n",n);
    int i = 0;
    int sum = 0;
    int a;
    while (i<n)
    {
        i=i+1;
        a=(int)(num_str[i]);
    }    
    int mean = sum / n;
    
    printf("Mean value: %d",mean);

    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...