I have tried to write a program in C to check Luhn algorithm for credit cards, but it doesn't work. I think I do not have quite clear how getchar() works, but this program looked sensible to me. Can you tell me what is wrong with it? Thank you in advance for any help with this.
#include <stdio.h>
int main(void) {
char x;
int n, sum, i, c;
sum = 0;
printf("Insert the number of digits: ");
scanf("%d",&n);
printf("Insert the digits: ");
for(i = n; i > 1; i = i - 1){
x = getchar();
if(i%2==0)
if(2*x < 10) sum = sum + 2*x;
else sum = sum + 2*x - 9;
else sum = sum + x;
i = i - 1;
}
c = (9*sum)%10;
x = getchar();
getchar();
if(x == c) printf("Last digit: %d,\nCheck digit: %d,\nMatching",x,c);
else printf("Last digit: %d,\nCheck digit: %d,\nNot Matching",x,c);
}
getchar() reads one character. Therefore, the x = getchar(); in the loop is not good because
It firstly read a newline character if you enter that after the first "number of digits".
It will read a character, not an integer. Character codes typically differ from the integer the character represents, and it may affect the check digit calculation.
Instead of x = getchar();, you should do this in the loop:
scanf(" %c", &x); /* ignore whitespace characters (including newline character) and read one character */
x -= '0'; /* convert the character to corresponding integer */
#include <stdio.h>
#define N 16
void luhn_algorithm();
int main(){
int a[N];
int i;
printf("type the card number:\n");
for(i=1;i<=N;i++){
scanf("%d",&a[i]);
}
luhn_algorithm(a);
}
void luhn_algorithm(int *a){
int i,multiply=1,m,sum=0,total=0;
for(i=1;i<=N;i++){
if(i%2!=0){
multiply=a[i]*2;
if(multiply>9){
while(multiply>0){
m=multiply%10;
sum+=multiply;
multiply/=10;
}
multiply=sum;
}
}
else if(i%2==0){
multiply=a[i]*1;
if(multiply>9){
while(multiply>0){
m=multiply%10;
sum+=multiply;
multiply/=10;
}
multiply=sum;
}
}
total+=multiply;
}
if(total%10==0){
printf("\nthis credit card is valid ");
}
else{
printf("\nthis credit card is not valid");
}
}
this is the program i made to check if credit card number is valid or not try this out.
I took the numbers in an array and then multiplied it according to their position and added them all if the last digit of the added total comes out to be 0 that means the card is valid otherwise its not.
check it out if theres something wrong please tell me.
Related
I'm writing a program that takes in your student number(8 digits long), prints each digit on its own new line, and then gets the sum of all the digits in the number
(E.g. Student Number - 20305324, Sum - 19)
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[8];
int i = 0;
int sum = 0;
printf("Enter your student number: ");
scanf("%s", student_number);
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
scanf("%s", student_number);
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print - DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + student_number[i];
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
OUTPUT
The problem I'm encountering is when my for loop attempts to add each digit in the student number. The output I expect here is 19, but for some reason the sum evaluates to some bizarre number like 403
}
Would someone mind pointing out where exactly the fault in my for loop is or if it is elsewhere? Thanks :)
Firstly, your array char student_number[8]; cannot hold 8-character string because there are no room for terminating null character. You must allocate one more element.
Then, you should convert the characters to corresponding numbers. Character codes for digits are defined to be continuous, so this can be done by subtracting '0' from the character code.
Also you should set a limit of length of string to read via scanf() to avoid buffer overrun. One more good practice is checking the return values of scanf() to see if something is successfully read.
Fixed code:
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[10]; // *** allocate enough elements (one more than needed to catch too long input)
int i = 0;
int sum = 0;
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print -DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + (student_number[i] - '0'); // *** convert characters to numbers before adding
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
When you read characters as a string, the values of the char objects are codes for the characters. Your C implementation is likely using ASCII codes, in which 48 is the code for “0”, 49 is the code for “1”, 65 is the code for “A”, and so on.
To convert a code x for a digit to the value of the digit, use x - '0'.
I think that the task was to read the number not the string.
void printDigitsAndSum(unsigned number)
{
unsigned mask = 1;
unsigned sum = 0;
while(number / (mask * 10)) mask *= 10;
while(mask)
{
printf("%u\n", number / mask);
sum += number / mask;
number %= mask;
mask /= 10;
}
printf("Sum: %u\n", sum);
}
int main(void)
{
unsigned number;
if(scanf("%u", &number) == 1)
printDigitsAndSum(number);
else printf("Wrong number\n");
}
https://godbolt.org/z/1edceh
I have this problem where the number isn't being identified as an Armstrong number. I tried entering 153 which is an Armstrong number which isn't being identified as one. I am learning C. Any help would be nice.
#include <stdio.h>
int main()
{
int x[3],a,b,c,temp;
int temp2 = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d",&x);
for(int i =0;i<3;i++)
{
temp = x[i]*x[i]*x[i];
temp2 = temp2 + temp;
}
if(temp2 == x)
{
printf("This is an Armstrong number!");
}
else
{
printf("This is not an Armstrong number!");
}
}
TL;DR - To store a 3-digit integer value, you don't need an array with 3 ints.
In your code, x is an array type, and the way you use it, only x[0] get a valid value, x[1] and x[2] are left uninitialized. So, your code produces undefined behavior.
I believe, you don't need to have an array, instead make use of the modulo operator to extract each digit one by one and carry on with the calculation.
with respect to your code x is an integer type array.so,integer type array doesn't work like a char type array.
char type array takes base address and it is still open util '\0'(null) char is found.it is defined for scanf().but for int type array you need to manually define the particular position of the array in the memory to store the inputs.
so,u have to use like this =>
#include <stdio.h>
int main(){
int x[3],n,r,c,temp,i;
int temp2 = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d",&n);
c=n;
for(i =0;i<3;i++){
x[i]=n%10;
n=n/10;
temp = x[i] * x[i] * x[i];
temp2 = temp2 + temp;
}
if(temp2 == c){
printf("This is an Armstrong number!");
}
else{
printf("This is not an Armstrong number!");
}
return 0;
}
Firstly take input into a single variable of type int and then store it in array after breaking them by % operator then you will be able to find Armstrong number.
E.g
int x=153;
int y[3];
for(int i=2;i>=;i--)
{
y[i]=x%10;
x=x/10;
}
After this step your loop will work properly
You were no need to use an array for getting all digits from given integer input.
#include <stdio.h>
int main() {
int input, temp, rmdr, sum = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d", &input);
temp = input; // store value of given input (backUp)
for ( ; input>0; ) { // loop till input has data
rmdr = input % 10; // get last digit from input
sum += (rmdr * rmdr * rmdr); // collect cube of remainders
input /= 10; // remove last digit from input
}
// collected sum will compare with temp (backUp)
// because given input will be 0 after loop
if (temp == sum)
printf("This is an Armstrong number!");
else
printf("This is not an Armstrong number!");
}
Thanks all, really helped. I needed to do this for a mini-project.I decided to do this because it seemed the easiest way.
#include <stdio.h>
int main()
{
int x,y,z,temp;
int temp2 = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d",&x);
z = x;
for(int i =0;i<3;i++)
{
y = x%10;
temp = y*y*y;
temp2 = temp2 + temp;
x = x/10;
}
if(temp2 == z)
{
printf("This is an Armstrong number!");
}
else
{
printf("This is not an Armstrong number!");
}
}
For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.
i am only able to count number of digits in an integer.
#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0)
{
n/=10;
count++;
}
printf("Digits in your number: %d",count);
return 0;
}
maybe arrays are the solution. Any help would be appreciated. thank you!
You don't need array. Try something like this:
int countDigits(int number, int digitToCount)
{
// Store how many times given number occured
int counter = 0;
while(number != 0)
{
int tempDigit = number % 10;
if(tempDigit == digitToCount)
counter++;
number = number/10;
}
return counter;
}
So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10.
If we wanted to acquire the least significant digit, we could use number % 10. For 1234, that would have the value of 4.
Understanding this, we can then modify your code to take this into account:
int main() {
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0) {
if (n % 10 == 1)
count++;
n /= 10;
}
printf("Number of 1s in your number: %d", count);
return 0;
}
You may want to use convert your int to a string like this :
char str[100];
sprintf(str, "%d", n);
Then, you can just iterate on str in order to find the occurrences of your digit.
I'm self-studying C and I'm trying to make 2 programs for exercise:
the first one takes a number and check if it is even or odd;
This is what I came up with for the first one:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
the second one should take n numbers as input and count the number of even numbers, odd numbers, and zeros among the numbers that were entered. The output should be the number of even numbers, odd numbers, and zeros.
I would like to ask how to implement the loop in this case: how can I set an EOF value if every integer is acceptable (and so I cannot, say, put 0 to end)? Can you show me how to efficiently build this short code?
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
Check the return value of scanf()
1, 1 field was filled (n).
0, 0 fields filled, likely somehtlig like "abc" was entered for a number.
EOF, End-of-file encountered (or rarely IO error).
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
Or read the count of numbers to subsequently read:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
hey look at this
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
You can do something like this:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
This program ask for a number, evaluate the number and then ask to continue for another number or exit.
I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}