Different answer in code blocks ide vs Repl.it - c

So im answering an assignment question in c and for some reason when I run it in codeblocks or even C lion I get a different and wrong answer than when I run it on Repl.it online. I copied and pasted the code so there are no errors or differences. The question itself requires u to enter a 12 digit ISBN number then calculate the product by takin (1st number) X 1 + (second number) X 3 and so on then taking the mod of the sum and subtracting from 10 and calculate the last digit.
Ex the number 978030640615
should give the product as 93 and last digit as 7
Below is my code for code blocks:
#include <stdio.h>
int main(void) {
long num1 = 0;
int num2 =0;
int sum =0;
int n = 0;
printf("Enter number :\n");
scanf("%ld",&num1);
for (int i= 0 ; i<12 ; i++){
num2 = 0;
num2 = num1%10;
num1 = num1/10;
n +=1;
if (n%2 == 0){
num2 = num2*1;
//printf("%d" , num3);
}
else {
num2 = num2*3;
//printf("%d", num2);
}
sum = num2+sum;
}
printf("\n" "%d", sum);
num2 = sum%10;
num2= 10 - num2;
printf("\n" "%d", num2);
}
and the output is
-63 and 13
My code for Repl.it is the same as the one from codeblocks I copied and pasted it but i get 93 and 7 as the answer

Related

Write a C program that accepts two numbers and finds all Armstrong numbers in that range

In the above mentioned I wanted to ask that what I have done wrong in my code I have tried debugging it many times but was not able to understand the logical error in my code.
Any help would be appreciated.
#include <stdio.h>
#include <math.h>
int digit(int n);
int digit(int n) {
int a;
double i = 0;
do {
a = n % (int)(pow(10, i));
i++;
} while (a != n);
return i;
}
void is_armstrong(int n);
void is_armstrong(int n) {
int a, b;
double sum;
for (int i = 0; i < digit(n); i++) {
a = n / (int)pow(10, (double)i);
b = a % 10;
sum += pow((double)b, 3);
}
if ((int)sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
is_armstrong(153);
return 0;
}
This code is not even showing 153 an Armstrong number.
Noting the comments about using the power function and what your ultimate outcome is in identifying Armstrong numbers over a given range, I did a bit of refactoring to simplify the process in identifying such numbers. Following is the code snippet that provides the functionality.
#include <stdio.h>
void is_armstrong(int n) {
int a, b, c, d;
int sum = 0;
a = n;
c = 0;
while (a != 0) /* Determine the number of digits to raise to a power */
{
a = a / 10;
c = c + 1;
}
a = n; /* Reset the work number */
while (a != 0) /* Noted from the comments to simplify the test */
{
b = a % 10;
d = b;
for (int i = 1; i < c; i++)
{
d = d * b;
}
sum = sum + d; /* Just mulitply each digit by itself the required number of times */
a = a / 10; /* Divide by 10 along with using the modulo function to evaluate each digit */
}
if (sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
return 0;
}
Following are some key points.
Since the power function is not needed, the math.h include file is not needed and linking the math library is also not needed.
Acquiring each digit is simplified by just utilizing the modulo operation in combination with integer division by "10".
Acquiring the value of each digit raised to the nth power is simplified by just performing a repeated multiplication.
Following is test output at the terminal.
#Dev:~/C_Programs/Console/Armstrong/bin/Release$ ./Armstrong
Please input the left hand limit of range :
1
Please input the right hand limit of range :
10000
1 is an armstrong number.
2 is an armstrong number.
3 is an armstrong number.
4 is an armstrong number.
5 is an armstrong number.
6 is an armstrong number.
7 is an armstrong number.
8 is an armstrong number.
9 is an armstrong number.
153 is an armstrong number.
370 is an armstrong number.
371 is an armstrong number.
407 is an armstrong number.
1634 is an armstrong number.
8208 is an armstrong number.
9474 is an armstrong number.
And as a confirmation, it can be seen that the value "153" was recognized as an Armstrong number.
Give the code snippet a try and see if it meets the spirit of your project.
There is no need to count the number of digits in n, you can just sum the cubes of each digit, one at a time dividing the number by 10 at each iteration.
Here is a simplified version:
#include <stdio.h>
void is_armstrong(int n) {
int sum = n;
while (n != 0) {
int b = n % 10;
n /= 10;
sum -= b * b * b;
}
return sum == 0;
}
int main() {
int a, b;
printf("Please input the left hand limit of range:\n");
if (scanf("%d", &a) != 1)
return 1;
printf("Please input the right hand limit of range:\n");
if (scanf("%d", &b) != 1)
return 1;
for (int i = a; i <= b; i++) {
if (is_armstrong(i)) {
printf("%d is an Armstrong number.\n", i);
}
}
return 0;
}

The full output is not being printed

im not getting an output for this program, please help
THE QUESTION:
Twin primes are consecutive odd numbers both of which are prime numbers. Write a program which inputs two positive integers A and B and outputs all twin primes in range A to B.
The code is:
#include <stdio.h>
int main(){
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if(num1>num2){
temp=num1;
for(i=num2;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j!=0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k!=0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num2){
printf("\n%d and %d",i,i+2);
}
}
}
else{
temp=num2;
for(i=num1;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j==0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k==0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num1){
printf("\n%d and %d",i,i+2);
}
}
}
return 0;
}
OUTPUT:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\shaun\OneDrive\Desktop> cd "c:\Users\shaun\OneDrive\Desktop\c programming\programs\" ; if ($?) { gcc twin_primes.c -o twin_primes } ; if ($?) { .\twin_primes }
Enter 2 numbers: 8 19
Twin prime numbers are:
PS C:\Users\shaun\OneDrive\Desktop\c programming\programs>
if(p1==1 && p2==1 && (i+2)<=num2)
if(p1==1 && p2==1 && (i+2)<=num1)
You've mixed up with num2 & num1 in above 2 conditions.
If you use num1 instead of num2 and num2 instead of num1, you'll get the output.
Apart from this, there're several logical errors in code.
Logic to find prime number
Initializing variable p1 and p2 in proper place
To solve above 2 problems, I would recommend to learn more about finding prime numbers. I'll add some resources at below, please check those.
Another thing, you're basically writing same code twice. You could make it more simple by just swapping 2 given values when first one is larger than the second one.
Lastly, I'm giving a sample code here. It's one of the way you could follow to write simple but easily understandable solution for your problem.
Sample code:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num)
{
for(int i = 2; i * i <= num; i++)
{
if (num % i == 0) return false;
}
return true;
}
int main()
{
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if (num1 > num2)
{
// swap the numbers. always keeping the first as the smaller one
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 == 1) num1++; // ignoring 1
for(int i = num1; i <= num2 - 2; i++) // running the loop till num2 - 2, so we won't have to check whether i + 2 <= num2
{
if (isPrime(i) && isPrime(i+2))
{
printf("\n%d and %d",i,i+2);
}
}
return 0;
}
Please check below URLs to learn more about prime number and swapping values
C Program to Swap Two Numbers
C Program to Swap two Numbers GFG
Prime Numbers GFG
C Program to Check Whether a Number is Prime or Not
Which is the most efficient way to calculate prime numbers in C?
Quora

how can I get the desired output?

I tried using the for loop for the test cases as I thought that would bring the desired output but it didn't
int main()
{
int num, temp, digit, sum = 0;
int test,i;
scanf("%d",&test);
for(i=1;i<=test;i++)
{
printf("\n");
scanf("%d", &num);
temp = num;
while (num != 0)
{
digit = num % 10;
sum = sum + digit;
num /= 10;
}
printf("%d",sum);
}
return 0;
}
Expected results- 2 123 456
Output- 6 15
Obtained Results- 2 123 456
Output- 6 21
The first output is correct but at the second print it is summing up the first result with the second line which I don't want.
You never clear sum after processing 123. You are calculating the correct sum (15) but it is being added to the sum from the previous step (6). To fix the problem clear sum inside the for loop.
for(i=1;i<=test;i++)
{
sum = 0;
printf("\n");

Creating table for Fibonacci Sequence

Thank you in advance. I appreciate any and all feedback. I am new to programming and i am working on an assignment that prints the Fibonacci Sequence based on how many numbers the user asks for. I have most of the code complete, but there is one remaining piece I am having difficulty with. I would like my output in a table format, but something is off with my code and I am not getting all of the data I would like in my output. In grey is my code, my output, and my desired output.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int sequence = 1;
int a = 0, b = 1, c = 0;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
printf("\n n\t\t Fibonacci Numbers\n");
printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b);
for (i=0; i <= (n - 3); i++)
{
c = a + b;
a = b;
b = c;
sequence++;
printf("\t\t\t%d\n ", c);
}
return 0;
}
Here is my output:
How many Fibonacci numbers would you like to print?: 8
n Fibonacci Numbers
1 0
1
1
2
3
5
8
13
Here is my desired output:
How many Fibonacci numbers would you like to print?: 8
n Fibonacci Numbers
1 0
2 1
3 1
4 2
5 3
6 5
7 8
8 13
I am not getting all of the data
That's because you are not printing the sequence in printf() of the for loop.
printf("\t\t\t%d\n ", c);
and even before 2nd number before for loop
printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b);
try making the below changes to your code :
printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b);
sequence++; //as you've printed 2 values already in above printf
for (i=0; i <= (n - 3); i++)
{
c = a + b;
a = b;
b = c;
printf("%d\t\t\t%d\n ",++sequence, c);
//or do sequence++ before printf as you did and just use sequence in printf
}
sample input : 5
sample output :
How many Fibonacci numbers would you like to print?: 5
n Fibonacci Numbers
1 0
2 1
3 1
4 2
5 3
Edit : you can do it using functions this way... it's nearly the same thing :)
#include <stdio.h>
void fib(int n)
{
int i,sequence=0,a=0,b=1,c=0;
printf("\n n\t\t Fibonacci Numbers\n");
printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b);
sequence++;
for (i=0; i <= (n - 2); i++)
{
c = a + b;
a = b;
b = c;
printf("%d\t\t\t%d\n ",++sequence, c);
}
}
int main()
{
int n;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
fib(n);
return 0;
}
You forgot to print sequence in the for loop. Print sequence along with c in the for loop after giving proper number of \t!
This would work, also it is better to properly indentate your code:
int main() {
int i, n;
int sequence = 1;
int a = 0, b = 1, c = 0;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
printf("\n n\t\tFibonacci Numbers\n");
printf(" %d\t\t\t%d\n", sequence, a);
printf(" %d\t\t\t%d\n", ++sequence, b); // <- and you can use pre increment operator like this for your purpose
for (i=0; i <= (n - 3); i++) {
c = a + b;
a = b;
b = c;
sequence++;
printf(" %d\t\t\t%d\n",sequence, c);
}
return 0;
}
Output:
How many Fibonacci numbers would you like to print?: 4
n Fibonacci Numbers
1 0
2 1
3 1
4 2

Problem determining if a number is an Armstrong Number

I'm trying to check whether or not the number provided by the user is an armstrong number. Something is wrong though and I can't figure it out.
Any help is appreciated.
Code attached below.
#include<stdio.h>
int fun(int);
int main()
{
int x,a,b,y=0;
printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
scanf("%d",&a);
for(int i=1 ; i<=3 ; i++)
{
b = a % 10;
x = fun(b);
y = x+y;
a = a/10;
}
if(y==a)
printf("\narmstrong number");
else
printf("\nnot an armstrong number");
return 0;
}
int fun(int x)
{
int a;
a=x*x*x;
return (a);
}
The primary problem is that you don't keep a record of the number you start out with. You divide a by 10 repeatedly (it ends as 0), and then compare 0 with 153. These are not equal.
Your other problem is that you can't look for 4-digit or longer Armstrong numbers, nor for 1-digit ones other than 1. Your function fun() would be better named cube(); in my code below, it is renamed power() because it is generalized to handle N-digit numbers.
I decided that for the range of powers under consideration, there was no need to go with a more complex algorithm for power() - one that divides by two etc. There would be a saving on 6-10 digit numbers, but you couldn't measure it in this context. If compiled with -DDEBUG, it includes diagnostic printing - which was used to reassure me my code was working right. Also note that the answer echoes the input; this is a basic technique for ensuring that you are getting the right behaviour. And I've wrapped the code up into a function to test whether a number is an Armstrong number, which is called iteratively from the main program. This makes it easier to test. I've added checks to the scanf() to head off problems, another important basic programming technique.
I've checked for most of the Armstrong numbers up to 146511208 and it seems correct. The pair 370 and 371 are intriguing.
#include <stdio.h>
#include <stdbool.h>
#ifndef DEBUG
#define DEBUG 0
#endif
static int power(int x, int n)
{
int r = 1;
int c = n;
while (c-- > 0)
r *= x;
if (DEBUG) printf(" %d**%d = %d\n", x, n, r);
return r;
}
static bool isArmstrongNumber(int n)
{
int y = 0;
int a = n;
int p;
for (p = 0; a != 0; a /= 10, p++)
;
if (DEBUG) printf(" n = %d, p = %d\n", n, p);
a = n;
for (int i = 0; i < p; i++)
{
y += power(a % 10, p);
a /= 10;
}
return(y == n);
}
int main(void)
{
while (1)
{
int a;
printf("Enter the number you want to identify as an Armstrong number or not: ");
if (scanf("%d", &a) != 1 || a <= 0)
break;
else if (isArmstrongNumber(a))
printf("%d is an Armstrong number\n", a);
else
printf("%d is not an Armstrong number\n", a);
}
return 0;
}
One problem might be that you're changing a (so it will no longer have the original value). Also it would only match 1, 153, 370, 371, 407. That's a hint to replace the for and test until a is zero and to change the function to raise to the number of digits.
#include<stdio.h>
#include <math.h>
int power(int, int);
int numberofdigits(int);
//Routine to test if input is an armstrong number.
//See: http://en.wikipedia.org/wiki/Narcissistic_number if you don't know
//what that is.
int main()
{
int input;
int digit;
int sumofdigits = 0;
printf("enter the number you want to identify as an Armstrong or not:");
scanf("%d",&input);
int candidate = input;
int digitcount = numberofdigits(input);
for(int i=1 ; i <= digitcount ; i++)
{
digit = candidate % 10;
sumofdigits = sumofdigits + power(digit, digitcount);
candidate = candidate / 10;
}
if(sumofdigits == input)
printf("\n %d is an Armstrong number", input);
else
printf("\n %d is NOT an Armstrong number", input);
return 0;
}
int numberofdigits(int n);
{
return log10(n) + 1;
}
int power(int n, int pow)
{
int result = n;
int i=1;
while (i < pow)
{
result = result * n;
i++;
}
}
What was wrong with the code:
No use of meaningful variable names, making the meaning of the code hard to understand; remember code is written for humans, not compilers.
Don't use confusing code this code: int x,a,b,y=0; is confusing, do all vars get set to 0 or just y. Always put vars that get initialized on a separate line. It makes reading easier. Go the extra mile to be unambiguous, it will pay off big time in the long run.
Use comments: If you don't know what an armstrong number is, than it will be very hard to tell from your code. Put a few meaningful comments in so people know what your code it supposed to do. This will make it easier for you and others because they know what you meant to do and can see what you actually did and solve the difference if need be.
use meaningful routine names WTF does fun(x) do?. Never name anything fun() it's like fact free science, what's the point?
Don't hardcode things, your routine only accepted armstrong3 numbers, but if you can hardcode then why not do return (input == 153) || (input == 370) || ....
Okay so, the thing is that there are also Armstrong numbers that are not just 3 digits for example 1634, 8208 are 4 digit Armstrong numbers, 54748, 92727, 93084 are 5 digit Armstrong numbers and so on. so to check the number is Armstrong or not, here's what I did.
#include <stdio.h>
int main()
{
int a,b,c,i=0,sum=0;
printf("Enter the number to check is an Armstrong number or not :");
scanf("%d",&a);
//checking the digits of the number.
b=a;
while(b!=0)
{
b=b/10;
i++;
}
// i indicates the digits
b=a;
while(a!=0)
{
int pwr = 1;
c= a%10;
//taking mod to get unit place and getting its nth power of their digits
for(int j=0; j<i; j++)
{
pwr = pwr*c;
}
//Adding the nth power of the unit place
sum += pwr;
a = a/10;
//Dividing the number to give the end condition
}
if(sum==b)
{
printf("The number %d is an Armstrong number",b);
}
else
{
printf("The number %d is not an Armstrong number",b);
}
}
/*
Name: Rakesh Kusuma
Email Id: rockykusuma#gmail.com
Title: Program to Display List of Armstrong Numbers in 'C' Language
*/
#include<stdio.h>
#include<math.h>
int main()
{
int temp,rem, val,max,temp1,count;
int num;
val=0;
num=1;
printf("What is the maximum limit of Armstrong Number Required: ");
scanf("%d",&max);
printf("\nSo the list of Armstrong Numbers Before the number %d are: \n",max);
while(num <=max)
{
count = 0;
temp1 = num;
while(temp1!=0)
{
temp1=temp1/10;
count++;
}
if(count<3)
count = 3;
temp = num;
val = 0;
while(temp>0)
{
rem = temp%10;
val = val+pow(rem,count);
temp = temp/10;
}
if(val==num)
{
printf("\n%d", num);
}
num++;
}
return 0;
}
Check No. is Armstrong or Not using C Language
#include<stdio.h>
#include<conio.h>
void main()
{
A:
int n,n1,rem,ans;
clrscr();
printf("\nEnter No. :: ");
scanf("%d",&n);
n1=n;
ans=0;
while(n>0)
{
rem=n%10;
ans=ans+(rem*rem*rem);
n=n/10;
}
if(n1==ans)
{
printf("\n Your Entered No. is Armstrong...");
}
else
{
printf("\n Your Entered No. is not Armstrong...");
}
printf("\n\nPress 0 to Continue...");
if(getch()=='0')
{
goto A;
}
printf("\n\n\tThank You...");
getch();
}
If you are trying to find a armstrong number the solution you posted is missing a case where your digits are great than 3 ...armstrong numbers can be greater than 3 digits (for example 9474). Here is the code in Python, the logic is simple and it can be converted to any other language.
def check_armstrong(number):
num = str(number)
total=0
for n in range(len(num)):
total+=sum(int(num[n]),len(num))
if (number == total):
print("we have armstrong #",total)
def sum(input,power):
input = input**power
return input
check_armstrong(9474)
Here's a way to check whether a number is armstrong or not
t=int(input("nos of test cases"))
while t>0:
num=int(input("enter any number = "))
n=num
sum=0
while n>0:
digit=n%10
sum += digit ** 3
n=n//10
if num==sum:
print("armstronng num")
else:
print("not armstrong")
t-=1
This is the most simplest code i have made and seen ever for Armstrong number detection:
def is_Armstrong(y):
if y == 0:
print('this is 0')
else:
x = str(y)
i = 0
num = 0
while i<len(x):
num += int(x[i])**(len(x))
i += 1
if num == y:
print('{} is an Armstrong number.'.format(num))
break
else:
print('{} is not an Armstrong number.'. format(y))
is_Armstrong(1634)

Resources