Not able to understand how values in loop work - c

I tried writing code for cs50 pset1's problem: credit.c(more comfortable) after week2. My code is given below. The problem is that 'sumx' and 'sumy' are just 0 and hence 'sum' is always equal to 0. So whenever I give a correct credit card number, it is just going to new line and program ends. How can I solve this problem and why are 'sumx' and 'sumy' not adding up to their respective sums as they should according to the algorithm?
My code is:
#include <cs50.h>
#include <stdio.h>
int main(void){
long long i;
do{
printf("Your credit card number:\n");
i = get_long_long();
}
while(i < 4e12 || i > 5.5e15);
int count = 0;
int n;
long long c = i;
while(i != 0){
n = i%10;
i = i/10;
count++;
}
int x[count];
for(int j = 0; j < count; j++){
x[j] = c%10;
i = c/10;
}
int sumx = 0;
for(int j = 0; j < count - 1; j += 2){
x[j] = x[j] * 2;
sumx = sumx + x[j];
printf("%i", sumx);
}
int sumy = 0;
for(int j = 0; j < count; j += 2){
sumy = sumy + x[j];
}
int sum;
sum = sumx + sumy;
if(sum%10 == 0){
if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
printf("AmEx\n");
}
else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
printf("MASTERCARD\n");
}
else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
printf("VISA\n");
}
}
else{
printf("Invalid Number\n");
}
return 0;
}

//#include <cs50.h>
#include <stdio.h>
int main(void){
long long i=4111111111111111;
//Master: 5105105105105100;//16
//visa: 4111111111111111
printf("%lld\n",i);
//~ do{
//~ printf("Your credit card number:\n");
//~ i = get_long_long();
//~ }
//~ while(i < 4e12 || i > 5.5e15);
int count = 0;
long long c = i;
int k=0;
int x[100];//
while(c != 0){
x[k] = c%10;
c = c/10;
printf("%lld\n",c);
count++;
k++;
}
//k==count
printf("count:%d\n",count);
printf("k:%d\n",k);
// x[i] contains all the digits of credit card
printf("print x[i]\n");
for (int i=0;i<count;i++){
printf("%d ",x[i]);
}
printf("\n");
int addsum=0,x2prod=0;
for (int j=0; j<k; j+=2 ){
addsum += x[j];
}
printf("addsum:%d\n",addsum);
for (int j=1; j<k; j+=2 ){
if ( (2 * x[j]) > 9 ){ //have 2 digit
x2prod += (2 * x[j]) / 10;
x2prod += (2 * x[j]) % 10;
}
else // have one digit
x2prod += 2 * x[j];
}
printf("x2prod:%d\n",x2prod);
int sum;
sum = addsum + x2prod;
printf("\nsum: %d\n",sum);
if(sum%10 == 0){
if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
printf("AmEx\n");
}
else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
printf("MASTERCARD\n");
}
else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
printf("VISA\n");
}
}
else{
printf("Invalid Number\n");
}
return 0;
}
I apply some correction on your code, store all credit card digits on x[]array in first while().
I checked code output with only three samples and by the way this is not a reliable version, try to catch any error.
As you read on my comment i don't any idea about that, but by perform simple search this link
show me what to do and decode it to your way.

Related

how to fix this unexpected output?

I have been doing on decomposing Integers to prime numbers, but i got stucked , it s working for one prime number, but when the iteration continues then it s not working properly and I can t come up with any solution.
For example for number 12 i expect output 2^2 x 3
but instead program stops at 2^2 x and new input is expected.
int main(int argc, char *argv[])
{
int number;
int stop = 1;
int prime = 0;
int sqr = 0;
while (stop == 1) {
/**------ERROR------ **/
if(scanf("%d",&number) != 1 || number < 0 ){
fprintf(stderr,"%s","Error: Chybny vstup!\n");
return 100;}
if(number == 0){
stop = 0;
break;}
/**------DECOMPOSITION------ **/
for (int index = 1;index <=number;){
if(number == 1){
//Ak sa input cislo rovna 1 tak vypise nasledovne riadky
printf("Prvociselny rozklad cisla 1 je:\n");
printf("1\n");
break;}
if(number % (index + 1) == 0){
// ak je cislo % index +1 (pociatocna hodnota je 2) tak sa vydeli cislom index + 1
// do prime sa ulozi dane prvocislo
// ak je delitelne prvocislom pripocitame sqr +1
// cyklus pokracuje s rovnakym indexom
number = number / (index + 1);
prime = index + 1;
sqr = sqr + 1;
continue;}
else{
if(sqr == 1){
// vypise len prvocislo
printf("%d",prime);}
if(sqr != 1){
//vypise prvocislo aj mocninu
printf("%d^%d", prime,sqr);}
if(number != 1){
printf(" x ");}
else{
printf("\n");
break;}
}
index = index + 1;
sqr = 0;
}
}
return 0;
}
I see two problems in the code:
The special case for number == 1 is being handled inside the loop. That special case is much easier to handle before the loop.
Counting the exponent is mixed into the loop that updates the factor. It's much easier to use a second loop to count the exponent.
#include <stdio.h>
int main(void)
{
while (1){
/**------GET USER INPUT------ **/
int number;
if(scanf("%d",&number) != 1 || number < 0 ){
fprintf(stderr,"%s","Error: Chybny vstup!\n");
return 100;
}
/**------HANDLE SPECIAL CASES------ **/
if(number == 0){
break;
}
if(number == 1){
printf("Prvociselny rozklad cisla 1 je:1\n");
continue;
}
/**------DECOMPOSITION------ **/
for (int factor = 2; factor <= number; factor++){
int exponent = 0;
while(number % factor == 0){
number /= factor;
exponent++;
}
if (exponent == 1){
printf("%d", factor);}
else if (exponent > 1){
printf("%d^%d", factor, exponent);}
if(exponent != 0 && number != 1){
printf(" x ");}
}
printf("\n");
}
}

Why is this code printing different numbers even when the input is same?

I'm trying to solve this:
http://codeforces.com/problemset/problem/888/A
I wrote the following code:
#include <stdio.h>
int main(void)
{
int a, i, q, count;
scanf("%d ", &q);
int ar[q];
for (i = 0; i < q; i++)
{
scanf("%d ", &ar[i]);
}
for (i = 0; i < q; i++)
{
if (i != q - 1 && i != 0)
{
if (((ar[i] < ar[i + 1]) && (ar[i] < ar[i - 1])))
{
count++;
}
else if (((ar[i] > ar[i + 1]) && (ar[i] > ar[i - 1])))
{
count++;
}
}
}
printf("%d", count);
return 0;
}
And when I run the program with the first test case, it prints random numbers.
When I run it again, it prints DIFFERENT random numbers.
I looked up the solution:
https://github.com/Waqar-107/Codeforces/blob/master/A-set/888A.Local%20Extrema.py
Isn't that code exactly what I wrote ? Why is my code printing strange things ?
Thanks in advance.
You should initialize the variable count to zero:
#include <stdio.h>
int main(void)
{
int a, i, q, count=0;
scanf("%d ", &q);
int ar[q];
for (i = 0; i < q; i++)
{
scanf("%d ", &ar[i]);
}
for (i = 0; i < q; i++)
{
if (i != q - 1 && i != 0)
{
if (((ar[i] < ar[i + 1]) && (ar[i] < ar[i - 1])))
{
count++;
}
else if (((ar[i] > ar[i + 1]) && (ar[i] > ar[i - 1])))
{
count++;
}
}
}
printf("%d", count);
return 0;
}

writing a prime factorization program C

I am trying to write a program that shows the results of prime factorization as below:
prompt: Input a positive integer
result examples:
100 = 2^2*5^2
It is a composite integer !
13 = 13
It is a prime number !
I tried to write it only with the basic loops, not using sophisticated techniques because it was for beginner's class. The problem is that when I enter 100 as an input, the result is just
100 =
being printed and the program stops there. Other than that, it gives me results I intended. Can anyone help me find what part of this code is the problem?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int inputNumber (int* input);
int primeFactors (int input);
int main (void) {
int input;
while ( 1 ) {
inputNumber (&input);
primeFactors (input);
}
return 0;
}
int inputNumber (int* input){
printf("\nInput a positive integer : ");
scanf("%d", input);
if(*input == 0){
printf("\n End of program");
exit(0);
}
return;
}
int primeFactors (int input){
int cnt = 0, i = 3, cnt_sum;
printf("%d = ", input);
if(input > 0){
while ( input % 2 == 0){
cnt++;}
if(cnt == 1){
printf("%d",2);}
else if( cnt > 0 && cnt != 1){
printf("%d^%d",2,cnt);
}
cnt_sum += cnt;
for ( ; i <= sqrt(input); i = i+2){
cnt = 0;
while(input % i == 0){
cnt++;
input /= i;
}
if(cnt == 1){
printf("%d",i);
}
else if( cnt > 0 && cnt != 1){
printf("%d^%d",i,cnt);
}
cnt_sum += cnt;
}
if(cnt_sum > 1){
printf("\nIt is a composite number !\n");
}
else{
printf("%d\nIt is a prime number !\n",input);
}
}
else{
printf("\nIt is an invalid number !\n");
}
}
There were few bugs.
while ( input % 2 == 0){cnt++;} loops infinitely if input is even( #Marian )
if(input > 1){ instead of if(input > 0){. since 1 is neither prime nor composite.
Corrected function:
int primeFactors (int input){
int cnt = 0, i = 3, cnt_sum;
printf("%d = ", input);
if(input > 1){
while ( input % 2 == 0){
input/=2;
cnt++;
}
if(cnt == 1){
printf("%d",2);}
else if( cnt > 0 && cnt != 1){
printf("%d^%d",2,cnt);
}
cnt_sum += cnt;
for ( ; i <= sqrt(input); i = i+2){
cnt = 0;
while(input % i == 0){
cnt++;
input /= i;
}
if(cnt == 1){
printf("%d",i);
}
else if( cnt > 0 && cnt != 1){
printf("%d^%d",i,cnt);
}
cnt_sum += cnt;
}
if(cnt_sum > 1){
printf("\nIt is a composite number !\n");
}
else{
printf("%d\nIt is a prime number !\n",input);
}
}
else{
printf("\nIt is an invalid number !\n");
}
}
ideone
You seem to be missing some steps in your algorithm, as well as checking redundant conditions in your primeFactors function.
int cnt = 0, i = 3, cnt_sum;
Because these won't ever be negative, you can change the type to unsigned.
while ( input % 2 == 0){
cnt++;
}
This while statement will loop infinitely if input is odd, because nothing is done to change input. You can add input = input / 2; to stop this.
if(cnt == 1){
printf("%d",2);}
else if( cnt > 0 && cnt != 1){
printf("%d^%d",2,cnt);
}
The else if expression can be reduced to an else statement, because unsigned variables are always greater than 0 and we already know cnt != 1, otherwise the first statement would be triggered.
while(input % i == 0){
cnt++;
input /= i;
}
The while statement is all good here, how peculiar. :P
if(cnt == 1){
printf("%d",i);
}
else if( cnt > 0 && cnt != 1){
printf("%d^%d",i,cnt);
}
Same deal here as with the if / else if statements before: change the else if to else.
With these corrections applied (and some style inconsistencies fixed), the function now looks like this:
int primeFactors (int input) {
unsigned cnt = 0, i = 3, cnt_sum;
printf("%d = ", input);
if (input > 0) {
while (input % 2 == 0) {
cnt++;
input /= 2;
}
if (cnt == 1) {
printf("%d", 2);
} else {
printf("%d^%d", 2, cnt);
}
cnt_sum += cnt;
for ( ; i <= sqrt(input); i += 2){
cnt = 0;
while (input % i == 0) {
cnt++;
input /= i;
}
if (cnt == 1) {
printf("%d", i);
} else {
printf("%d^%d", i, cnt);
}
cnt_sum += cnt;
}
if (cnt_sum > 1) {
printf("%d\nIt is a composite number !\n");
} else {
printf("%d\nIt is a prime number !\n",input);
}
}
else{
printf("\nIt is an invalid number !\n");
}
}

Number Board Program doesn't place hyphens correctly in C

We're supposed to create a number board whereby a user is allowed to select a number for instance, number 5 and one of the number 5's in the board will be clearly indicated as selected with a hyphen above and below it.
Problem now is: No matter what I try the hyphens refuse to move to the right spot.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define HEIGHT 9
#define WIDTH 8
void board(char array[HEIGHT][WIDTH])
{
int x,y,i,j,score,steps = 0;
/****BORDER CREATION*/
for (i = 0; i < WIDTH+4; i ++)
printf("# ");
printf("\n");
for(y=0;y<WIDTH+1;y++)
{
printf("\n");
printf("# ");
for(x=0;x<HEIGHT+1;x++)
{
printf("%c ",array[y][x]);
}
printf("# ");
printf("\n\n");
}
for (i = 0; i < WIDTH+4; i ++)
printf("# ");
printf("\n");
/****BORDER CREATION*/
}
void instruc(char *name, int *steps, int *selected)
{
/*User record & score header*/
printf("\n-----Hello %s! Let's see what you can do------\n",name);
printf("----------WELCOME TO NUMBER CONNECT----------\n");
printf("----------PREVIOUS PLAYERS' RECORDS----------\n");
printf("----------Name: %s Score(Steps): %i--\n\n",name,*steps);
printf("\nYour score: %i",*steps);
printf("\nNumber %i is currently selected",*selected);
printf("\n\nAction Keys: ");
printf("\nPush 'U' to move UP");
printf("\nPush 'D' to move DOWN");
printf("\nPush 'L' to move LEFT");
printf("\nPush 'R' to move RIGHT");
printf("\nPush 'X' to REMOVE path\n");
printf("\nTo select a new number, press digits from 1 to 7\n");
printf("\nPush 'q' or 'Q' to QUIT\n\n");
}
void select(int *selected,char array[HEIGHT][WIDTH])
{
int i,j,x;
printf("\nPlease select a number (1-8): ");
fflush(stdin);
scanf("%i",selected);
/*POINTER TYPE CONVERTION FAIL
selected = (char)*selected;*/
/*ASCII CHARACTER ATTEMPT FAIL
if (*selected == 1){
*selected = 1;
}
else if (*selected == 2){
*selected = 2;}
else if (*selected == 3){
*selected = 3;}
else if (*selected == 52){
*selected = 4;}
else if (*selected == 53){
*selected = 5;}
else if (*selected == 54){
*selected = 6;}
else if (*selected == 55){
*selected = 7;}
else if (*selected == 56){
*selected = 8;}
else{
printf("Non-Numeric Input not allowed");}*/
printf("\nNumber Selected: %i",*selected);
/*To indicate selected number with hyphens (denoted by 45)*/
for (i = 0; i < WIDTH+1;i++)
{
for (j =0; j < HEIGHT+1; j++){
if (array[i][j] == *selected){
array[i-1][j] = 45;
array[i+1][j] = 45;
}
}
}
printf("\nPosition of i: %i ",i);
printf("Position of j: %i\n\n",j);
}
void assign(char array[HEIGHT][WIDTH], int *selected)
{
int i,j;
/*int rr,rrr;
int x = 0;
srand((unsigned) time(NULL));
for (i = 0; i < WIDTH+3;i++)
{
for (j = 0; j < HEIGHT; j++){
x = (rand()%8+1)+48;
array[i][j] = x;
}
}
for (i = 0; i < WIDTH+3;i++)
{
for (j = 0; j < HEIGHT+3; j++){
rr = rand()%WIDTH;
rrr = rand()%HEIGHT;
x= 32;
array[rr][rrr] = x;
}
}
printf("\n");*/
/*To blank our everything that is not a symbol*/
array[0][1] = 49;
array[0][7] = 49;
array[5][9] = 50;
array[6][1] = 50;
array[1][4] = 51;
array[5][7] = 51;
array[7][2] = 52;
array[5][5] = 52;
array[3][3] = 53;
array[1][1] = 53;
array[7][3] = 54;
array[6][2] = 54;
array[3][7] = 55;
array[7][6] = 55;
array[2][4] = 56;
array[4][4] = 56;
for (i = 0; i < WIDTH+4;i++)
{
for (j = 0; j < HEIGHT+4; j++){
if ((array[i][j] != 49) && (array[i][j] != 50) && (array[i][j] != 51) &&
(array[i][j] != 52) && (array[i][j] != 53) && (array[i][j] != 54) && (array[i][j] != 55) &&
(array[i][j] != 56)){
array[i][j] = 32;
}
}
}
}
int main(void)
{
int i,j,x,y,score = 0,steps = 0,result = 0,selected=0;
char array[HEIGHT][WIDTH],name[20];
printf("Please Input Name: ");
scanf("%s",&name);
instruc(name,&steps,&selected);
assign(array,&selected);
board(array);
select(&selected,array);
board(array);
return 0;
}

ArrayGame. Why doesn't it update the print?

This is my C Programming assignment. We're required to build a simple game that uses array. Our game is like the popular minesweeper game. At first, we initialise the 20*50 array area. Then we put some bombs randomly in the map. In the game, the player is required to travel from the starting point to the ending point to win the game. When the player moves, the movement will make the arrays hidden so that the user knows where did he start. However, in my case, the system doesn't update and make the array empty after the player moves. Can anyone help me with my 's' code? What is wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define iMAX 20
#define jMAX 50
char array[20][50];
int i; //row
int j; //column
int z; //bomb
int n; //steps counter
int o; //x
int p; //y
o = 0;
p = 0;
int level;
int bomb;
char move;
int steps;
int main() {
printf("Welcome to the BombArray Game!\n");
printf("\nLevel 1 Begineer : 50 bombs\nLevel 2 Intermediate : 100 bombs\nLevel 3 Advance : 200 bombs\n");
printf("\nI want to challenge level ");
scanf_s("%d", &level);
printf("\n");
srand(time(NULL));
for (i = 0; i < 20; i++) {
for (j = 0; j < 50; j++) {
array[i][j] = '*';
}
}
array[0][0] = 'S';
array[19][49] = 'E';
if (level == 1) {
bomb = 50;
}
else if (level == 2) {
bomb = 100;
}
else if (level == 3) {
bomb = 200;
}
for (z = 0; z < bomb; z++) {
i = rand() % 20;
j = rand() % 50;
array[i][j] = '1';
}
do {
system("cls");
for (i = 0; i < iMAX; i++) {
for (j = 0; j < jMAX; j++) {
if (array[i][j] == 'S') {
printf("S");
}
else if (array[i][j] == '*') {
printf("*");
}
else if (array[i][j] == '1') {
printf("*");
}
else if (array[i][j] == 'E') {
printf("E");
}
else if (array[i][j] == '2') {
printf(" ");
}
}
printf("\n");
}
printf("\n\nMoving direction (w:up s:down a:left d:right e:exit): ");
scanf_s(" %c", &move);
printf("Steps? ");
scanf_s("%d", &steps);
if (move == 's') {
for (n = 0; n < steps; n++) {
i = o;
j = p;
i++;
array[i][j] = '2';
o = i;
p = j;
}
}
} while (array[19][49] != 2);
return 0;
}
if (move == 's') {
array[o][p] = '2';
for (n = 0; n < steps; n++) {
i = o;
j = p;
i++;
array[i][j] = '2';
o = i;
p = j;
}
array[o][p] = 'S';
}
You have to delete the S at the Start position and write it at the end position when you move
Some additional things: You don't need that much variables. You can remove i and j (or o and p).
If you enter something others than 1-3 for the level you will have an undefined number of bombs (if you declare the bomb variable as a local variable), therefore you should make a default case.
You never look if you are hitting a bomb, you just overwrite array[i][j] without prove if there's a bomb.
better:
if (move == 's') {
array[i][j] = '2';
for (n = 0; n < steps; n++) {
i++;
if (array[i][j] == '1') {
printf("bomb\n");
return 0;
}
array[i][j] = '2';
}
array[i][j] = 'S';
}

Resources