CodeChef - Runtime error(SIGSEGV) - c

I am getting a runtime error after I submit the solution on Codechef. I can compile and execute the solution in Code blocks on my machine. Please check the code and let me know what is wrong.
Problem definition -
All submissions for this problem are available.
In a company an emplopyee is paid as under:
If his basic salary is less than Rs. 1500, then HRA = 10% of base salary and DA = 90% of basic salary.
If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the Employee's salary is input, write a program to find his gross salary.
NOTE: Gross Salary = Basic Salary+HRA+DA
Input
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer salary.
Output
Output the gross salary of the employee.
Constraints
1 ≤ T ≤ 1000
1 ≤ salary ≤ 100000
Example
Input
3
1203
10042
1312
Output
2406
20383.2
2624
My solution -
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr1[10];
double arr2[10];
int t,t1;
int i,j;
float HRA,DA,GS;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d",&arr1[i]);
}
i=0;
t1=t;
while(t>0)
{
if(arr1[i]<1500)
{
HRA=(0.1*arr1[i]);
DA=(0.9*arr1[i]);
GS=(arr1[i]+HRA+DA);
arr2[i]=GS;
}
if(arr1[i]>=1500)
{
HRA=500;
DA=(0.98*arr1[i]);
GS=(arr1[i]+HRA+DA);
arr2[i]=GS;
}
i++;
t--;
if(i==t1)
break;
}
for(j=0;j<i;j++)
{
printf("\n%g",arr2[j]);
}
return 0;
}

The i variable in the first loop is indexing an array of 10 elements and it is going from 0 to t-1, while the t variable is read from user/test script and is not guaranteed to be less than 10. So once it is more than that, you get an index out of bounds and memory violation.

The solution is now accepted. The question had a constraint
1 ≤ T ≤ 1000
I modified the code to int arr1[1000] and double arr2[1000] and it got accepted.
Thanks for the help!

Related

Where am I going wrong with this? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I'm new to C programming. I came across this problem in codechef.
https://www.codechef.com/problems/TLG?tab=statement
I have no idea why it is failing. Please help.
The game of billiards involves two players knocking 3 balls around on a green baize table. Well, there is more to it, but for our purposes this is sufficient.
The game consists of several rounds and in each round both players obtain a score, based on how well they played. Once all the rounds have been played, the total score of each player is determined by adding up the scores in all the rounds and the player with the higher total score is declared the winner.
The Siruseri Sports Club organises an annual billiards game where the top two players of Siruseri play against each other. The Manager of Siruseri Sports Club decided to add his own twist to the game by changing the rules for determining the winner. In his version, at the end of each round, the cumulative score for each player is calculated, and the leader and her current lead are found. Once all the rounds are over the player who had the maximum lead at the end of any round in the game is declared the winner.
Consider the following score sheet for a game with 5 rounds:
Round
Player 1
Player 2
1
140
82
2
89
134
3
90
110
4
112
106
5
88
90
The total scores of both players, the leader and the lead after each round for this game is given below:
Round
Player 1
Player 2
Leader
Lead
1
140
82
Player 1
58
2
229
216
Player 1
13
3
319
326
Player 2
7
4
431
432
Player 2
1
5
519
522
Player 2
3
Note that the above table contains the cumulative scores.
The winner of this game is Player 1 as he had the maximum lead (58 at the end of round 1) during the game.
Your task is to help the Manager find the winner and the winning lead. You may assume that the scores will be such that there will always be a single winner. That is, there are no ties.
Input
The first line of the input will contain a single integer N (N ≤ 10000) indicating the number of rounds in the game. Lines 2,3,...,N+1 describe the scores of the two players in the N rounds. Line i+1 contains two integer Si and Ti, the scores of the Player 1 and 2 respectively, in round i. You may assume that 1 ≤ Si ≤ 1000 and 1 ≤ Ti ≤ 1000.
Output
Your output must consist of a single line containing two integers W and L, where W is 1 or 2 and indicates the winner and L is the maximum lead attained by the winner.
Sample 1:
Input:
5
140 82
89 134
90 110
112 106
88 90
Output:
1 58
My code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int N, a, b, cum1 = 0, cum2 = 0, lead = 0, leader = 0;
scanf("%d", &N);
while (N--) {
scanf("%d%d", &a, &b);
cum1 += a;
cum2 += b;
if (abs(cum1 - cum2) > lead) {
lead = abs(cum1 - cum2);
leader = cum1 > cum2 ? 1 : 2;
}
}
printf("%d%d\n", leader, lead);
return 0;
}
I tried solving it without the use of array, but it is showing as wrong answer. Unfortunately I don't know the failed test cases either. What can be the reasons for such failure?
There is at least this problem: you print both numbers without a space in between. The printf statement should be changed to:
printf("%d %d\n", leader, lead);
You should have been able to diagnose this problem by running your program with sample test data on your system or with an online compiler with a shell window. Testing and debugging are a must for programming, you must learn these skills early.
Aside from this trivial problem, your code is elegant and simple, the use of arrays is definitely not warranted.
Yet there is a non obvious limitation that might be a problem on some systems: both N and all Si and Ti values are specified with a range that will fit in type int, but the cumulative scores might exceed 32767, which is the largest value the int type may handle in some older 16-bit systems. For maximum portability, you should use type long, function labs() and the %ld conversion specifier.
Here is a modified version with extra sanity checks:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int N, a, b, leader = 0;
long cum1 = 0, cum2 = 0, lead = 0;
if (scanf("%d", &N) != 1)
return 1;
while (N-- > 0 && scanf("%d%d", &a, &b) == 2) {
cum1 += a;
cum2 += b;
if (labs(cum1 - cum2) > lead) {
lead = labs(cum1 - cum2);
leader = cum1 > cum2 ? 1 : 2;
}
}
printf("%d %ld\n", leader, lead);
return 0;
}

Google Kickstart 2020 Round A allocation problem in c

I have wrote the code in C language but it seems to pass the sample cases but when it comes to test cases it shows wrong answer.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a single line containing the two integers N and B. The second line contains N integers. The i-th integer is Ai, the cost of the i-th house.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the maximum number of houses you can buy.
Limits
Time limit: 15 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
1 ≤ B ≤ 105.
1 ≤ Ai ≤ 1000, for all i.
Test set 1
1 ≤ N ≤ 100.
Test set 2
1 ≤ N ≤ 105.
Sample
Input
Output
3
4 100
20 90 40 90
4 50
30 30 10 10
3 300
999 999 999
Case #1: 2
Case #2: 3
Case #3: 0
In Sample Case #1, you have a budget of 100 dollars. You can buy the 1st and 3rd houses for 20 + 40 = 60 dollars.
In Sample Case #2, you have a budget of 50 dollars. You can buy the 1st, 3rd and 4th houses for 30 + 10 + 10 = 50 dollars.
In Sample Case #3, you have a budget of 300 dollars. You cannot buy any houses (so the answer is 0).
And My code is
#include <stdio.h>
int main(){
int test;
scanf("%d",&test);
for(int i=1;i<=test;i++){
int N;
long int B;
scanf("%d %ld",&N,&B);
long int Case = 0,r=0;
int array[10000];
char ch;
do {
scanf("%d%c",&array[r],&ch);
r++;
}while(ch!='\n');
for (int k=0;k<N;k++){
for (int m=k;m<N;m++){
int temp;
if(array[k]>array[m]){
temp=array[k];
array[k]=array[m];
array[m]=temp;
}
}
}
r=0;
while(Case<=B){
Case+=array[r];
r++;
}
printf("Case #%d: %d\n",i,r-1);
}
}
The main culprit is the condition controlling the while loop below
while(Case<=B){ /* the logic of condition expression is wrong*/
Case+=array[r];
r++;
}
It must have been (r < N && Case+array[r]<=B) (r<N is necessary; you must also check the array index). The line
printf("Case #%d: %d\n",i,r-1);
is also wrong. It must be corrected as
printf("Case #%d: %ld\n",i,r);
Another mistake is the array size in int array[10000];. The size must have been 100000 since the value of N can be 100000 at maximum.
Your sorting algorithm is slow. A faster algorithm or the standard library function qsort should have been used.

How to store the salaries & IDs of employees in multi-dimensional arrays using for loop and updating them through another function ( C )

So the question should be rather simple (not to me tho for some reason).
i need to give some employees some IDs and give those IDs their own salary.and allow said employee to be stored IF their salary is above a set point. so far I've been able to (brokenly) implement this (i apologize if it seems like i'm talking a lot it's just that i can't seem to explain my problem that easily)
OLD code
#include <stdio.h>
void Employee_Data(int number_of_employees,
float Data[3][number_of_employees],float salary){
int i ;
for(i = 0 ;i < number_of_employees;i++){
printf("Employee %d\n\n",i+1);
printf("enter the salary of employee %d:",i+1);
scanf("%f",&salary);
printf("\n");
}
}
int main() {
printf("Enter the number of employees: ");
int number_of_employees = 0;
scanf("%d",&number_of_employees);
float Data[3][number_of_employees];
float salary;
Employee_Data(number_of_employees,Data,salary);
return 0;
}
what i need is a way to set an ID that the user inputs in the above function
and another function to print out the employees and their IDs if they have a salary over a number that the user also inputs and lastly (most likely the hardest) a function to give a raise to employees which are picked by their IDs and said raise is to be percentage wise of their current salary
Once again i apologize if it's too long and too confusing i have a bit of problems trying to get my point to be understood hopefully it is though.
NEW CODE
#include <stdio.h>
float employee_ID(int number_of_employees,int ID[number_of_employees]){
for (int i = 0; i<1;i++){
scanf("%d",&ID[i]);
}
return *ID;}
float Salary_of_employees(int number_of_employees,int salary[number_of_employees]){
for(int i = 0; i<1;i++){
scanf("%d",&salary[i]);
}
return *salary;}
void printing(int number_of_employees,int *salary[number_of_employees], int *ID[number_of_employees]){
for(int k = 0; k<number_of_employees;k++){
printf("Employee %d 's ID is %d and their salary is %d\n",k+1,*ID[number_of_employees],*salary[number_of_employees]);
}
}
int main() {
int number_of_employees;
int ID[number_of_employees];
int salary[number_of_employees];
printf("Please input the number of employees you need : ");
number_of_employees = 0;
scanf("%d",&number_of_employees);
int i;
for (int i = 0; i<number_of_employees;i++){
printf("please input the ID for employee %d\n",i+1);
employee_ID(number_of_employees,&ID[number_of_employees]);
printf("please input the salary of employee %d\n",i+1);
Salary_of_employees(number_of_employees,&salary[number_of_employees]);
}
printf("if you want to see the IDs and the salaries of the employees please write 1\n if you want to ");
int choice;
scanf("%d",&choice);
if (choice == 1){
printing(number_of_employees,salary,ID);
}
return 0;
}
Currently my problem with this is that i've got 2 warnings at the calling of the printing function (salary and ID are the warnings for some reason can't get them to be fixed)
And my other problem is that the storing only takes the last inputted number given by the user. for example if i give an ID of 321 and a salary of 543 the output of the printing function would be employee number(thank god the counter works)'s ID is 543 and the salary is 543 (TO EACH EMPLOYEE)
Edit1: So basically when i run the code it asks me to input the number of employees. (so far so good) when i insert the number it starts with employee number 1 and asks me to input the salary. upon inputting the salary it just gives me 2 new lines and stops basically what i need is that each time it'd -instead of saying employee 1- it'd first ask me to set the employee ID first and then say "Employee -insert ID-'s salary: "and then asks me to insert the salary of said employee. and then the same for each employee that i set . + the other functions
Edit2: Updated the code by removing the for loop that seemingly crashed the program and updated the title + (i think) explained the stuff that i need better
Edit 3: after messing around and legit deciding to restart the code i began experiencing some uhhh trouble with the storing for some reason. and decided to add the new code and keep the old one as well
You have an inner and outer loop over the number of employees. Not only will this behave strangely, but Its likely that if you enter more than 3 employees the code will crash. The J loop doesn't look right.

How to solve UVA 11137

I was trying to solve uva 11137:
People in Cubeland use cubic coins. Not only the unit of currency is
called a
cube
but also the coins are shaped like cubes and their values
are cubes. Coins with values of all cubic numbers up to 9261 (= 213), i.e., coins with the denominations of 1, 8, 27, :::, up to 9261 cubes,
are available in Cubeland.
Your task is to count the number of ways to pay a given amount
using cubic coins of Cubeland. For example, there are 3 ways to pay
21
cubes: twenty one 1
cube
coins, or one 8
cube
coin and thirteen 1
cube
coins, or two 8
cube
coin and five 1
cube
coins.
Input
Input consists of lines each containing an integer amount to be paid. You may assume that all the
amounts are positive and less than 10000.
Output
For each of the given amounts to be paid output one line containing a single integer representing the
number of ways to pay the given amount using the coins available in Cubeland
But I am having some problems. My code is:
#include <stdio.h>
#include <string.h>
#define max_coin 21
#define max_ammount 10000
int coin[max_coin], make;
unsigned long long int dp[max_coin][max_ammount];
unsigned long long int ways(int i, int ammount)
{
if(ammount <= 0) return 1;
if(i >= max_coin-1) return 0;
if(dp[i][ammount] != -1) return dp[i][ammount];
unsigned long long int return1 = 0, return2 = 0;
if(ammount - coin[i] >= 0) return1 = ways(i, ammount-coin[i]);
return2 = ways(i+1, ammount);
return dp[i][ammount] = return1 + return2;
}
void make_coins()
{
int i = 0;
coin[i] = 1;
for(i++; i < 21; i++) coin[i] = (i+1)*(i+1)*(i+1);
return ;
}
int main(void)
{
memset(dp,-1,sizeof(dp));
make_coins();
while(scanf("%d",&make) == 1) printf("%llu\n", ways(0, make));
return 0;
}
It gives the right output for almost all inputs. But for large inputs like 9999 (the largest), its output doesn't match with the sample. What mistake have I done?
For 9999
Accepted output : 440022018293
My output : 1935335135
My code may have problem with many other inputs, I don't know; I have tried the udebug example given uva though.

Write a program that sums the sequence of integers, as well as the smallest in the sequence

Write a program that sums the sequence
of integers as well as the smallest in
the sequence. Assume that the first
integer read with scanf specifies the
number of values remaining to be
entered. For example the sequence
entered:
Input: 5 100 350 400 550 678
Output: The sum of the sequence of
integers is: 2078
Input: 5 40 67 9 13 98
Output: The smallest of the integers
entered is: 9
This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help
First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.
Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).
I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.
If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).
And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).
Update:
Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", &currentNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
And here is the output from your sample data:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.
Read:
Assume that the first integer read
with scanf specifies the number of
values remaining to be entered
so it's not part of the sequence...
for the rest, it's your homework (and C...)
No. 5 is the number of integers you have to read into the list.
Jeebus, I'm not doing your homework for you, but...
Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:
Read integer
Loop that many times
** Read more integers
** Add
** Find Smallest
IF you're in C look at INT_MAX - that will help out finding the smallest integer.
Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.
-Adam
First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).
Then do a loop on the array to get the sum of to find the smallest value.
Hope that helps
wasn[']t looking for you guys to do the work
Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").
You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."
#include <stdio.h>
main ()
{
int num1, num2, num3, num4, num5, num6, i;
int smallestnumber=0;
int sum=0;
int numbers[50];
int count;
num1 = 0;
num2 = 0;
num3 = 0;
num4 = 0;
num5 = 0;
num6 = 0;
printf("How many numbers will be entered (max 50)? ");
scanf("%d", &count);
printf("\nEnter %d numbers then press enter after each entry: \n", count);
for (i=0; i < count; i++) {
printf("%2d> ", i+1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
smallestnumber = numbers[0];
for (i=0; i < count; i++) {
if ( numbers[i] < smallestnumber)
{
smallestnumber = numbers[i];
}
}
printf("the sum of the numbers is: %d\n", sum);
printf("The smallest number is: %d", smallestnumber);
}

Resources