When I execute my code, scanf("%d", &n); don't scan anything, I mean, if I introduce any number it doesn't do anything, regardless of the numbers I introduce.
void testEsPrimo() {
int n;
printf("Comprobando si un número es o no primo\n");
printf("Teclee un número entero: ");
fflush(stdout);
scanf("%d", &n); //<---- The problem ?
if(esPrimo(n) == cierto){
printf("%d es primo\n", n);
}else{
printf("%d NO es primo\n", n);
}
fflush(stdout);
}
Logico esPrimo(int n){
int divisor;
int esPrimox;
for(divisor = 2; sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
if(esPrimox == 1) {
return cierto;
}
return falso;
}
This is my esPrimo code that is about decide if a number is prime or not.
typedef enum {falso, cierto} Logico;
and this is Logico, defined in a .h file
PD: This are my first steps on C so my code might be bad.
PD2: Excuse me for my bad English I'm not native and my English isn't really good.
Your scanf is perfect.
I think that your mistake is the loop for from esPrimo. Actually you have an infinite loop, because sqrt(n) has always the same value and it isn't a boolean expression.
Change your loop:
for(divisor = 2; sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
for this:
for(divisor = 2; divisor < sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
But then you have a problem when you know that your number is not prime: you have to finish the loop.
You can do this:
for(divisor = 2; divisor < sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
break;
}
}
}
But if you can avoid using breakinside a loop for, don't use that.
With complicated algorithms you have a clean code with that, but when you read a loop for, usually your understand that the loop do a exactly number of iterations. If you have another flag to end the loop, use while.
While (divisor < sqrt(n) && esPrimox == 0){
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
There are 2 main problems in esPrimo.
First, the for loop will not terminate:
for(divisor = 2; sqrt(n); divisor++) {
Change the condition to:
for(divisor = 2; divisor <= sqrt(n); divisor++) {
Second is in the logic. If you find that n is not a prime, you need to break the loop or the function will always return true. You could do it either with the break statement or by checking the value of esPrimox in the loop condition.
Here's how to do it using break:
for(divisor = 2; divisor <= sqrt(n); divisor++) { /* fixed loop condition */
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
break; /* break the loop */
} else {
esPrimox =1;
}
}
}
Related
I'm trying to write a function, that would check for a matching parentheses.
For example, if the given string is "(1+1))" it would print false otherwise it's true.
However, in my code it's printing false no matter what the case is.
bool isMatched(char pran[]) {
bool completetd = true;
int count = 0;
for (int i = 0; pran[i] != '\0'; i++) {
if (pran[i] == '('){
count++;
}
else {
// It is a closing parenthesis
count--;
}
if (count < 0) {
// there are more Closing parenthesis
completetd = false;
break;
}
// If count is not zero, there are more opening parenthesis
if (count != 0) {
completetd = false;
}
}
return completetd;
}
int main() {
char arr[] = "((1+a))";
if (isMatched(arr)) {
printf("TRUE \n");
}
else {
printf("FALSE \n");
}
return 0;
}
I would appreciate any help.
You can try this not sure if this is what you are looking for.
bool isMatched(char pran[]) {
int open = 0;
int close = 0;
for (int i = 0; pran[i] != '\0'; i++) {
if (pran[i] == '('){
open++;
}
if (pran[i] == ')'){
close++;
}
}
// Check if both match
if(open == close){
return true;
}
return false;
}
int main() {
char arr[] = "((1+a))";
if (isMatched(arr)) {
printf("TRUE \n");
}
else {
printf("FALSE \n");
}
return 0;
}
By adding a
printf("got 1 (!\n"); next to count++;
and a
printf("got 1 )!\n"); next to count--;,
you get:
Got 1 (!
Got 1 (!
Got 1 )!
Got 1 )!
Got 1 )!
FALSE
This shows that you have a validation problem with your checking logic
As pointed-out in the comments, replace your else with else if (pran[i] == ')') { will fix that part for you.
But the real problem lies with your last validation.
Take it out of the for loop. It sets the value to false as soon as you detect a parenthesis.
Thus, take this:
// If count is not zero, there are more opening parenthesis
if (count != 0) {
printf("Count: %d\n",count);
completetd = false;
}
}
and make it this:
}
// If count is not zero, there are more opening parenthesis
if (count != 0) {
printf("Count: %d\n",count);
completetd = false;
}
I'm trying to check the return value of the function in an if statement so that I will return its value if its 1, but it gets called when I do it in an if statement. Is there a way where I prevent the call in the if statement. I want to check all three function but if I checked one without if statement then it returns 0 and stops.
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else
{
string chars = argv[1];
if (check_length(chars) == 1)
{
return check_length(chars);
}
else if (check_rc(chars) == 1)
{
return check_rc(chars);
}
else if (check_alpha(chars) == 1)
{
return check_alpha(chars);
}
}
string ptext;
ptext = get_string("Input Text: \n");
}
int check_rc(string chars)
{
for (int i = 0, n = strlen(chars); i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!(i == j))
{
if (chars[i] == chars[j])
{
printf("Key must not contain repeated characters. \n");
return 1;
}
}
}
}
return 0;
}
int check_alpha(string chars)
{
for (int i = 0, n = strlen(chars); i < n; i++)
{
if (isdigit(chars[i]))
{
printf("Key must only contain alphabetic characters. \n");
return 1;
}
}
return 0;
}
int check_length(string chars)
{
int charLength = strlen(chars);
if( charLength !=26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
return 0;
}
Your Question is hard to understand but i am assuming that if you want to reduce theamount of unnessecary check you could apply the concept of short-circuit evalution of &&
or u could just not use (else if). and use 3 if statement instead.
all following(else if) is skip if one of the if statement before it is true.
hope this help.
You can save the return value in a local variable and use it all the way:
int check_rc_val = check_length(chars);
if (check_rc_val == X)
{
return check_rc_val;
}
int check_rc_val = check_rc(chars);
if (check_rc_val == Y)
{
return check_rc_val;
}
int check_alpha_val = check_alpha(chars);
if (check_alpha_val == Z)
{
return check_alpha_val;
}
I am taking CS50, and I completed the first week problem of implementing the Luhn Check algorithm. Although my solution works, I feel it's very sloppy and not efficient. Can someone please suggest how I can improve my solution. (It's a first week problem; you are not intended to use arrays or functions.)
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<cs50.h>
int main()
{
long long x,j=0;
int len,i,len_flag,flag=0,flag_val=0,sp_len=0,check_flag=0; //basic integers related to loop etc
int res,sum,fin_sum=0,h=0,d2_sum=0,d1_sum=0,ff_num=0; // variables related to extracting numbers
int sum_len=0,in_sum=0,in_fsum=0,len_sum=0,m=0; // extraing numbers from more than single sum result
int sum_f=0,sum_final=0;
do{
x = get_long("enter a valid card number \n");
j=x;
len_flag = 0;
len = 0;
while(len_flag!=1)
{
x = x / 10;
if(x==0)
{
len_flag = 1; //finding the lenght of the number
}
len++;
}
if(len==15||len==16||len==13)
{
flag = 1;
sp_len =1;
}
else
{
flag=1;
}
}while(flag!=1);
for(i=0;i<len;i++)
{
res = j % 10;
j = j / 10;
if(i%2!=0)
{
sum = res * 2;
//printf("multi_res : %d \n",sum);
len_flag = 0;
sum_len = 0;
len_sum = sum;
while(len_flag!=1)
{
len_sum = len_sum / 10;
if(len_sum==0)
{
len_flag=1; // checking if the sum is more than single digit
}
sum_len++;
//printf("trig\n");
}
if(sum_len>1)
{ x=0;
while(x<sum_len)
{
in_sum = sum % 10;
sum = sum/10;
in_fsum = in_fsum + in_sum;
//printf("double sum : %d \n",in_fsum);
x++;
}
}
fin_sum = fin_sum + sum;
}
if(i==len-1)
{
for(h=0;h < 1;h++)
{
fin_sum = fin_sum + in_fsum;
}
d1_sum = res;
}
else if(i%2==0)
{
sum_f = sum_f + res; // adding up the number that where not x2
}
if(i==len-2)
{
d2_sum = res; //5555555555554444
}
}
sum_final = sum_f + fin_sum;
//printf("sum_final : %d\n",sum_final);
//printf("sum_f_final : %d\n",sum_f);
//printf("sum_in_final : %d\n",fin_sum);
if(sum_final%10==0)
{
flag_val=1; // checking if the number is valid
}
if(ff_num == 0)
{
ff_num = (d1_sum*10) + d2_sum; //flip
}
do
{
if(sp_len==0)
{
printf("INVALID\n");
check_flag=1;
break;
}
if((flag==1&&flag_val==1&&ff_num==34)||ff_num==37)
{
printf("AMEX\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&ff_num>50&&ff_num<56)
{
printf("MASTERCARD\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&d1_sum==4)
{
printf("VISA\n");
check_flag=1;
break;
}
else
{
printf("INVALID\n");
check_flag=1;
break;
}
}while(check_flag!=1);
return 0;
}
I felt like I was fixing a leak while writing the code. I would try to correct one thing, and another thing would go wrong, and this is the final result.
I have to scan this file which partly contains
SNOL
INTO num IS 8
INTO res IS 9
and the output of the code below is
Program starts...
Set value of num to 0
Set value of res to 8
input msg
which is wrong because num should be 8 and res should be 9
why is it num scanning 0 instead of 8?
and why doesn't the code work anymore if I assign number to num and number to res?
num = number;
//Tokenizer functions//
bool isLowerCase(const char *object)
{
int i;
int len = strlen(object);
for(i = 0; i < len; i++) {
if(object[i] >= 'a' && object[i] <= 'z') {
return true;
}
}
return false;
}
//function to check if character is Float.
bool objectFloat(const char* object) {
//check if 1st character is a digit, if not then return false,
otherwise
return true.
if(!isdigit(object[0]))
return false;
// Check if the 2nd character to the last are digits or periods.
// If not, return false otherwisereturn true
int periods = 0; //initialize how many periods in the object to zero
int i;
//if character is a period then increment periods.
for(i = 1; i < strlen(object); i++) {
if(object[i] == '.') {
periods++;
}
//return false if character is not a digit
else if(!isdigit(object[i])) {
return false;
}
}
// return true if there is only one period.
return periods == 1;
}
//function to check if character is a keyobject.
bool isKeyobject(const char* object) {
char keyobjects[11][11] = { "SNOL", "LONS", "INTO", "IS", "MULT", "BEG",
"PRINT", "ADD", "SUB", "DIV", "MOD" };
int i;
for(i = 0; i < 11; i++) {
// Check if object is equal to keyobjects at index i
// If yes, return true
if(isLowerCase(object))
return false;
if(strcmp(object, keyobjects[i]) == 0) {
return true;
}
}
//object is not equal to any of the keyobjects so return false
return false;
}
//Function to check if every character is an integer
// If not, return false otherwise return true
bool objectInt(const char* object) {
int i;
for(i = 0; i < strlen(object); i++) {
if(!isdigit(object[i])) return false;
}
return true;
}
bool objectIsVariable(const char* object) {
// Check if alphanumeric character & lower case
// If not, return false
int i;
for(i = 0; i < strlen(object); i++) {
if(!isalnum(object[i]) && !isLowerCase(object)) return false;
}
return true;
}
int main() {
FILE *s_path = fopen("test.snol", "r");
int number = 0;
int num, res;
if(isKeyobject(object) && strcmp(object, IsitSNOL) == 0) {
printf("Program starts...\n");
}
else if(isKeyobject(object) && strcmp(object, IsitINTO) == 0) {
printf("Set value of ");
}
if(objectInt(object)) {
number = atoi(object);
}
else if(objectFloat(object)) {
number = atof(object);
}
if(objectIsVariable(object) && strcmp(object, IsitNum) == 0) {
//if float
printf("num to %d\n", number);
num == number;
}
else if(objectIsVariable(object) && strcmp(object, IsitRes) == 0) {
//if float
printf("res to %d\n", number);
res == number;
}
else if(isKeyobject(object) && strcmp(object, IsitBEG) == 0) {
printf("input msg\n");
scanf("%s", msg);
fscanf(s_path, " %s", &object);
printf("INPUT(%s): %s\n", object, msg);
}
}
} // END MAIN -----------------------------------//
The problem seem to be that you read the number after the variable name but you do the print before.
So your sequence is:
Keyobject INTO
objectIsVariable num // Now you print the value
objectInt // Now you read the value
You need to postpone the printing until you have actually read the value.
This is not a very elegant solution, but you can try like:
int flag = 0;
if(objectInt(object)) {
number = atoi(object);
if (flag == 1)
{
num = number;
printf("num to %d\n", number);
}
else if (flag == 2)
{
res = number;
printf("res to %d\n", number);
}
else
{
printf("Illegal flag\n");
}
flag = 0;
}
if(objectIsVariable(object) && strcmp(object, IsitNum) == 0) {
flag = 1;
}
else if(objectIsVariable(object) && strcmp(object, IsitRes) == 0) {
flag = 2;
}
Trying to implement a very simple Roman Numeral to Decimal converter but can't seem to figure out a way for the program to return -1 if any non-roman numeral characters are in the string. This is what I have so far.
#include <stdio.h>
#include <ctype.h>
int convertFromRoman(const char *s)
{
int i = 0;
int total = 0;
while (s[i] != '\0') {
if (isalpha(s[i]) == 0) {
return -1;
}
if (toupper(s[i]) == 'I') {
total += 1;
}
if (toupper(s[i]) == 'V') {
total += 5;
}
if (toupper(s[i]) == 'X') {
total += 10;
}
if (toupper(s[i]) == 'L') {
total += 50;
}
if (toupper(s[i]) == 'C') {
total += 100;
}
if (toupper(s[i]) == 'D') {
total += 500;
}
if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
i++;
}
if (total == 0) {
return -1;
}
return total;
}
int main()
{
printf("%d\n", convertFromRoman("XVII"));
printf("%d\n", convertFromRoman("ABC"));
}
The first one should return 17 and the second one should return -1. However they both return -1 but if I remove the else statement, the first one returns 17 and the second one returns 100.
Any help is appreciated.
Change if() if() if() else to if() else if () else if() else
if (toupper(s[i]) == 'I') {
total += 1;
}
else if (toupper(s[i]) == 'V') {
total += 5;
}
else if (toupper(s[i]) == 'X') {
total += 10;
}
....
else if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
Not really an answer, just a bit of fun/alternate way of looking at the problem. It does solve the problem if you're not considering ordering just adding "digit" values.
char *romanNumerals = "IVXLCDM";
int values[] = { 1, 5, 10, 50, 100, 500, 1000 };
int convertFromRoman(const char *s) {
int val = 0;
for (int i = 0; s[i]; i++) {
char *idx;
if (NULL == (idx = strchr(romanNumerals, toupper(s[i])))) {
return -1;
}
val += values[idx - romanNumerals];
}
return val;
}