I am solving problem in a online judge and I faced a problem. I think my code is correct but unfortunately the judge says wrong answer. Where did I made mistake?
Habib has learned so much about programming in the last few days! Today he faces a new challenge, handling input with test cases! For this, he must solve a set of inputs and for each input h must generate an output. And what is better than to practice this other than calculating factorials?! A factorial of an integer N is calculated by multiplying all the integers from 1 to N. For example, 4! (4 factorial) is calculated as- 1x2x3x4=24. In this problem, Habib is required to solve a set of inputs for a defined number of test cases. For example, if testcase = 3, then he must take 3 set of inputs and generate 3 sets of desired outputs, one output for one input. Help him solve the problem.
Input
The input starts with an integer Test (0 < Test < 100) which denoted number of inputs or testcases to be solved. For each testcase, input an integer n (0 <= n <= 10).
Output
For each testcase generate output in a single line in the format: Case x: y, where x is the testcase number and y is the answer for calculating n!.
#include <stdio.h>
int main()
{
int i,Test,n=0,x,j,y,s=1;
scanf("%d",&Test);
for(i=1;i<=Test;i++)
{
scanf("%d",&n);
for(j=1;j<=n;j++)
{
s=s*j;
}
printf("Case %d: %d\n",i,s);
}
return 0;
}
You forgot to reset s for each test cases.
Try adding s=1; after scanf("%d",&n);.
Input The input starts with an integer Test (0 < Test < 100) which denoted number of inputs or testcases to be solved. For each testcase, input an integer n (0 <= n <= 10).
Your code does not reflect this. You should definitely check if the inputs are valid or not, a way could be:
if(Test < 100 && Test > 0){
//do something
}else{
printf("Invalid input!");
}
Furthermore you should consider staying with either capital variable names or only lowercase, example: int test,n or int Test, N. Mixing both makes bigger projects a guessing game when you have to edit it after a few days.
Now to your Task:
Basically your task is to find n! and do this X-times.
As stated by #MikeCat you never reset your s, which is the starting point for your factorial.
#include <stdio.h>
int main(){
int i,test,n=0,x,j,y,s=1;
scanf("%d",&Test);
if(!(test <100 && test > 0)){
printf("Invalid input!");
}
for(i=1;i<=test;i++)
{
scanf("%d",&n);
s = 1;
for(j=1;j<=n;j++)
{
s=s*j;
}
printf("Case %d: %d\n",i,s);
}
return 0;
}
This should do the trick.
Change your code to
#include <stdio.h>
int main()
{
int i,Test,n=0,x,j,y;
scanf("%d",&Test);
for(i=1;i<=Test;i++)
{
int s=1;//observe this
scanf("%d",&n);
for(j=1;j<=n;j++)
{
s=s*j;
}
printf("Case %d: %d\n",i,s);
}
return 0;
}
Related
I am attempting to write a C program that can calculate the factorial of a number inputted by a user. I have the program below, and it seems to work fine without any errors. However, everything I input a number like 5, I get a strange answer like -1899959296.
I cant seem to find where the error is, let alone how the answer is negative. Any help would be appreciated, thank you very much.
int main()
{
int inputnumber;
int n;
printf("\nThis program is a factorial calculator. Input a number below to finds its factorial: ");
scanf("%i", &inputnumber);
//A 'for' loop repeats the same contained statements until a condition is met.
//A general form of a 'for' statements is shown below:
// for( initial values; loop condition; loop expression)
for (n = 1; n <= inputnumber; n++)
{
inputnumber = inputnumber * n;
}
printf("\nThe answer is %i", inputnumber);
return 0;
}
I attempted to make a factorial program, but all inputted numbers give very wrong answers.
The problem is this part of your code:
for (n = 1; n <= inputnumber; n++)
{
inputnumber = inputnumber * n;
}
The code inside the loop increases inputnumber when n > 1. This causes the loop to run much longer than intended because n <= inputnumber (your loop conditional) is always satisfied until there is an integer overflow, i.e., when inputnumber < 0. Hence, the loop only stops when inputnumber becomes negative.
To fix this, you should store your factorial result as a separate variable, e.g.:
int result = 1;
Then update your loop to be result *= n; (and obviously change your print statement accordingly).
If you changed your conditional portion of your for loop to restrict to only < rather than <= it should produce the right answers.
For example i assume the input: '2' gives you '4' as a result:
input = 2 * 1
input = 2 * 2
end
return input
or by using a third variable you can use your current logic:
#include <stdio.h>
int main() {
int number, i, factorial = 1;
printf("Enter an integer: ");
scanf("%d", &number);
for (i = 1; i <= number; i++) {
factorial *= i;
}
printf("Factorial of %d = %d\n", number, factorial);
return 0;
}
I want to directly input a 2-D Array in C, separated just by single spaces and newlines. At the same time I also want to verify whether the user is entering a valid single digit integer (either positive or negative).
I tried the following.
int A[3][3];
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&A[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",A[i][j]);
printf("\n");
}
But I want 2 things in this:-
Input that is first verified whether its a single digit integer or not.
Not works merely for positive integers and 0 but also for negative integers.
eg.
input such as the following should be accepted and stored in 2-d array
1 2 -3 4
-5 1 2 -6
1 1 2 3
I'm sorry if I wasn't clear. An important component is that the input should be confirmed whether its integer or not i.e. the input should be either as char or string and if it is an integer (which can be ascertained by functions such as isdigit() , then it should be converted to an integer value.
This following code chunk works for single positive values
char c = getchar();
if (isdigit(c))
int value = c - '0';
However, I don't know how to enable this functionality for negative integers in a complete 2D array input.
If you want to verify that a number is a single digit, just check if its between -9 and 9.
As for negative numbers, im pretty sure the %d modifier for the scanf captures that.
Please comment down below if the answer is incorrect so i could fix it :)
Edit: i forgot to note that scanf returns the number of read elements. so comparing this against 1 (since you read one element at a time) will allow you to know if the input was partial or not.
something like this:
if (scanf(" %d", &A[i][j]) != 1){
//here goes the code for when the input is partial
}
should do the trick
So first, tell the user to enter values row-wise or column-wise. In this case, ask like this
printf("Enter integers row-wise");
Now the user will enter values.
After scanning those values put an if statement to verify that value is greater than or equal to -9 and less than 9. If value is within the range continue; else put a exit(1); statement and tell the user that entered value is incorrect. Like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int A[3][3];
int i, j;
for( i = 0; i < 3; i++ )
{
for( j = 0; j < 3; j++)
{
scanf("%d", &A[i][j]);
if(A[i][j] >= -9 && A[i][j] <= 9)
continue;
else
{
printf("Enter correct values.\n");
exit(1);
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",A[i][j]);
printf("\n");
}
return 0;
}
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 5 years ago.
Improve this question
I want to check if the numbers in an array are a power of two.
I wrote the following code, but it doesn't work it skips the part that checks if the number is the power of two and prints the last sentence.
Also, if someone can help me in how to check if the input is a number and not any other character.
Thank you!
update the power of two thing is working but i still haven't figure out how to check if the input is a number and not any other characher
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
int i;
int k;
int count=0;
int a;
int sum=0;
printf("Enter size of input:\n");
scanf("%d",&x);
int *numbers=malloc(sizeof(int)*x);
if (x<0){
printf("Invalid size\n");
}
else {
printf("Enter numbers:\n");
for(i=0;i<x;++i){
scanf("%d",&numbers[i]);
}
}
for(k=0;k<x;++k)
{
count=0;
a=numbers[k];
while (((numbers[k] % 2) == 0) && numbers[k] > 1){ /* While x is even and > 1 */
numbers[k]/= 2;
++count;
}
if (numbers[k]==1&&a!=1){
printf("The number %d is a power of 2:%d=2^%d\n",a,a,count);
sum+=count;
}
}
printf("Total exponent num is %d\n",sum);
return 0;
}
Your check for the power of two is wrong: you divide out two all the way down to 1, but the following if incorrectly checks numbers[k]==0.
The check should be numbers[k]==1 instead, because when you divide out all twos from a power of two you end up with 20, which is 1.
Note: You can check if a number is a power of two without a loop by using a bit trick described in this Q&A.
There's much in your example that's incidental to the problem. For example, allocating an array and reading user input is just a distraction from finding the solution. Concentrate first on debugging your algorithm:
#include <stdbool.h>
bool is_power_of_two(int n)
{
while (n % 2 == 0 && n > 1){ /* While x is even and > 1 */
n/= 2;
}
return n == 0;
}
int main()
{
return !is_power_of_two(2);
}
Now, you can refine that function until it gives the correct result. The simple fix is to replace n == 0 with n == 1. Now you can add more tests, running the program as you add each one:
int main()
{
return is_power_of_two(0)
+ !is_power_of_two(1)
+ !is_power_of_two(2)
+ is_power_of_two(3)
+ !is_power_of_two(4)
/* negative numbers can never be an exact power of a positive */
+ is_power_of_two(-1)
+ is_power_of_two(-2)
+ is_power_of_two(-3);
}
Once you have some confidence in your function, you can then use it in your program to process arrays.
When you do introduce a function to read input, you'll want to check that x isn't negative before using in the argument to malloc(). Better would be to ensure it's not negative, by using an unsigned type:
unsigned int x;
printf("Enter size of input:\n");
if (scanf("%u", &x) != 1) {
fprintf(stderr, "That's not a valid size!\n");
return EXIT_FAILURE;
}
int *numbers = malloc(x * sizeof *numbers);
if (!numbers) {
fprintf(stderr, "Couldn't allocate memory for %u numbers!\n", x);
return EXIT_FAILURE;
}
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}
Just try to learn and pick up the logic of C programming. I feel little bit confused for the looping to control the row and column
How can i achieve it in C ?
Enter the number: 3
-a-
---
-a-
Enter the number: 5
-a-a-
-----
-a-a-
-----
-a-a-
Thanks for your help!
Since this is a learning exercise, here are some points to get you on the path to a solution:
The most common way of iterating in two dimensions is two nested loops
In this situation, using two nested for loops would be a good idea
Inside the body of the inner for loop you have access to two variables - one denoting the current row, and one denoting the current column
Your code needs to decide if a letter or a dash is to be printed based on the values of the row and the column
When the row is odd, or when the column is even, print a dash; otherwise, print character 'a'
You can tell if a number is odd or even by examining num % 2 or num & 1. In both cases, if the result is zero, the number is even; otherwise, the number is odd.
It is just about using nested loops, I would say if you want to learn specifics about accessing row and coloumn, practice some programs on Matrix operations such as addition, multiplication etc. You will find a lot of them in google.
put this in your gcc -o cloop cloop.c -std=c99 and ./cloop it.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char**argv){
int i;
do{
i = 0;
printf("Give me an int (0 to quit) ");
if( scanf("%u", &i) != 1) break;
if( i < 0 ) i = 0;
for( int j =0; j<i;j++) {
for( int k =0; k<i;k++)
printf("%s", (
k % 2 == 0
? "-"
: j % 2 == 0 ? "a" : "-" )
);
printf("\n");
}
} while ( i > 0 );
}
#include<stdio.h>
main()
{
int i,j,n;
printf("Enter the number:");
scanf("%d",&n); // Input the number
for(i=0;i<n;i++) // For n rows
{
printf("\n"); // New line after each row
for(j=0;j<n;j++) // For n columns for each row
{
if(i%2==0) // For alternate(even) rows(the one with a's)
{
if(j%2==0) // For alternate(even) columns(the one without a's)
printf("-");
else
printf("a");
}
else
printf("-"); // For alternate(odd) rows(with only -'s)
}
}
}
This is the logic.