#include <stdio.h>
void ScanArray (int* , int*);
int Pair (int* , int);
int main () {
int a [15] , n;
ScanArray (a , &n);
// printf("\nHello World !!!\n");
if(Pair(a , n) == 0)
printf("The array fulfills the requirements");
else
printf("The array does not fulfills the requirements");
return 0;
}
void ScanArray (int *a , int *n) {
int i , f = 0;
do {
printf("Enter the number of integers : ");
scanf("%d",n);
if (*n > 15)
printf("Enter number bellow 15 \n");
else
f=1;
} while(f == 0);
printf("Enter the %d integers : ",*n);
for (i = 0 ; i < *n ; i++)
scanf("%d",a+i);
}
int Pair (int *a , int n) {
if (n <= 1)
return 0;
else
if (*a-*(a+1) != 1 && *a-*(a+1) != -1)
return 1;
else
return Pair(a++ , n--);
}
don't know why it's not working.
Segmentation fault (core dump).
else
return Pair(a++ , n--);
Using postfix increment and decrement operators will result in the recursive call processing the same values. You should either use prefix operators, or even better, just add and subtract 1.
else
return Pair(a + 1 , n - 1);
I say that's better because it's misleading to think modifying the values matters; the key to recursion is that the recursive calls will have their own copies of a and n, so modifying them in a parent has no effect on the children.
Related
I've made a program that checks if a given positive integer is a prime or perfect number.The problem I'm facing is I created a function "readNumber" that works as a check loop to ensure that input is a positive integer.But if I enter a negative value and then an acceptable one it shows previous values aswell.I attach a screenshot of the command prompt text to make myself more clear.
Below is my code
#include<stdio.h>
int checkperfectnumber(int);
int checkprimenumber(int);
int readNumber(int);
int main(){
int num, x, y, result;
printf("\nGive a positive integer number: \n");
scanf("%d",&num);
y = readNumber(num);
x = checkperfectnumber(num);
result = checkprimenumber(num);
if (num == 1)
printf("1 is nor a prime neither a perfect number");
else if (x == num)
printf("%d is a perfect number\n",num);
else if ( result == 1 )
printf("%d is a prime number.\n", num);
else
printf("%d is nor prime neither a perfect number.\n", num);
return 0;
}
//perfect number function
int checkperfectnumber(int numbr){
int a=1, sum=0;
while(a < numbr){
if(numbr % a == 0)
sum=sum+a;
a++;
}
return(sum);
}
//prime number function
int checkprimenumber(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}
//input check function
int readNumber(int b){
while (b < 0)
{
printf("Wrong input.\nPlease insert a positive integer.");
main();
break;
}
}
Quick fix is have the program exit after executing main() from readNumber().
To do this, Add #include <stdlib.h> and replace break; in the function readNumber() to exit(0);.
Better solution is having the function readNumber(), not main(), read numbers and stop calling main() recursively.
It will be like this:
#include<stdio.h>
int checkperfectnumber(int);
int checkprimenumber(int);
int readNumber(void);
int main(){
int num, x, y, result;
printf("\nGive a positive integer number: \n");
num = readNumber();
x = checkperfectnumber(num);
result = checkprimenumber(num);
if (num == 1)
printf("1 is nor a prime neither a perfect number");
else if (x == num)
printf("%d is a perfect number\n",num);
else if ( result == 1 )
printf("%d is a prime number.\n", num);
else
printf("%d is nor prime neither a perfect number.\n", num);
return 0;
}
//perfect number function
int checkperfectnumber(int numbr){
int a=1, sum=0;
while(a < numbr){
if(numbr % a == 0)
sum=sum+a;
a++;
}
return(sum);
}
//prime number function
int checkprimenumber(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}
//input check function
int readNumber(void){
for (;;)
{
int b;
scanf("%d",&b);
if (b >= 0) return b; /* 0 is not positive, but this condition is !(b < 0) */
printf("Wrong input.\nPlease insert a positive integer.");
}
}
Is this is program to print prime numbers between two numbers
a and b (null safe or not)?
if not , How to add null safe function to make it (NULL SAFE)
I have tried checking if argv[1] or argv[2] are equall to 0
but it is not how it should work
any Ideas for this?
//check if a or b or both are negative numbers
int check_negative(int *x, int *y){
if(*x<0 || *y<0)
{
printf("Error : One or Both arguments are Negative\n");
return 1;
}
}
//check if n is a prime number
int isprime(int n)
{
int i, status = 1;
for(i=2; i <= n/2; ++i)
{
if (n%i == 0)
{
status = 0;
break;
}
}
return status;
}
int main(int argc, char* argv[] )
{
if(argc==1)
{
printf("Error : No arguments were passed\n");
return 0 ;
}
int a=atoi(argv[1]),b=atoi(argv[2]),n,status;
if(check_negative(&a,&b)==1)
{
return 0;
}
printf("Prime numbers between %d and %d are: \n", a, b);
for(n=a+1; n<b; ++n)
{
status = isprime(n);
if(status == 1)
printf("%d ",n);
}
return 0;
}
Is this c program null safe?
No.
The below fails when argc < 3 (e.g. 2,1,0) as it calls atoi() with NULL or unknown. #Ian Abbott
int a=atoi(argv[1]),b=atoi(argv[2]),n,status;
Instead change prior test from only testing against 1 to the below. Note that argc == 0 is possible on select platforms and with certain function calls.
// if(argc==1)
if(argc < 3)
As a stand-alone function, check_negative() does not check if a null pointer argument is passed before de-referencing. Add checks
int check_negative(int *x, int *y){
if (x == NULL || y == NULL) return 0; /// or handle in some way
Aside:
isprime(Any_int_less_than_2) errantly returns 1.
for(i=2; i <= n/2; ++i) is very slow for large n. Suggest speedier for(i=2; i <= n/i; ++i). Sample
I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.
int main()
{
int i,n;
printf("Enter the number");
scanf("%d",&n);
i=pali(n);
if(n==i)
printf("Number is pall");
else
printf("Not Pall");
}
int pali(int n)
{
int r;
static sum=0;
if(n!=0)
{
r=n%10;
sum=sum*10+r;
pali(n/10);
}
return sum;
}
I used a static variable to add up the sum. Is there any way where no static variable will be used?
Yes, the typical ("functional") approach is to carry the state in the form of a function argument. This often makes it necessary/nice to have a second function that does the actual recursion, which you can start by calling with the proper initial values for the state:
int do_pali(int sum, int n)
{
if(n != 0)
{
const int r = n % 10;
return do_pali(10 * sum + r, n / 10);
}
return sum;
}
the public function then just becomes:
int pali(int n)
{
return do_pali(0, n);
}
In languages with inner functions this can be more neatly expressed (GCC supports this as an extension).
Sure, you can do it this way :
#include <stdio.h>
int pali(int n)
{
int sum = 0;
int keeper = 0;
for (int i = n; i > 0; i /= 10) {
if (keeper != 0) {
sum *= 10;
sum += (keeper - i * 10);
}
keeper = i;
}
sum *= 10;
sum += keeper;
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Using recursion is even easier :
#include <stdio.h>
int pali(int n, int sum)
{
sum += n - ((n / 10) * 10);
n /= 10;
if (n > 0)
pali(n, sum * 10);
else
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n, 0);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
And a recursive version with only one parameter :
#include <stdio.h>
int pali(int n)
{
int fUnit, lUnit;
fUnit = n;
int mul = 1;
while (fUnit > 10) {
fUnit /= 10;
mul *= 10;
}
lUnit = n - ((n / 10) * 10);
n -= (fUnit * mul);
n /= 10;
if (mul == 1) return 1;
else if (fUnit == lUnit) return pali(n);
else return 0;
}
int main(int argc, char** argv)
{
int n;
printf("Enter the number : ");
scanf("%d",&n);
if(pali(n) == 1)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Since your function returns sum you could replace this line:
pali(n/10);
with
sum=pali(n/10);
You'd also have to move it up a line too.
Here is an optimized version that
Doesn't use local static.
Only includes stdio.h
Uses recursion.
#include <stdio.h>
static void perform_useless_recursion (int n)
{
if(n--)
{
perform_useless_recursion(n);
}
}
_Bool is_pali (int n)
{
perform_useless_recursion(1);
int sum = 0;
for(int i=n; i!=0; i/=10)
{
sum = sum*10 + i%10;
}
return n == sum;
}
int main (void)
{
int n=5005;
if(is_pali(n))
printf("Number is pall");
else
printf("Not Pall");
return 0;
}
The code could be improved even further by removing the perform_useless_recursion() function.
The advantage of this code is that the actual calculation is performed by a fast loop, instead of slow, dangerous recursion. In the real world outside artificial school assignments, there is no reason to write inefficient and dangerous code when you could write efficient and safe code. As a bonus, removing recursion also gives far more readable code.
If you benchmark this code you'll notice that it will be faster than all other versions posted and consumes less memory.
You can make a function that check only the first and the last digits of the number and pass the rest of the number onward.
To explain better, think about the following cases:
pali(1220) would check for the first (1) and last (0) digits. Since 1 != 0 pali would return false.
pali(17891) would check first (1) and last (1). Since they're equal then the function would recursively return pali(789) (which itself would return false since 7 != 9).
pali(878) would check that 8=8 and recursively return pali(7)
pali(3) would check that first (3) and last (3) numbers are equal and return 0.
The challenge here is to develop an algorithm that:
Check if first and last numbers are the same (even if it's only one digit!)
Strip the number from first and last digits and call itself on the remainder
Then all you need to do is apply recursion. Here's a sample implementation:
int pali(int number)
{
int smallDigit, bigDigit;
/* When recursion ends suceffuly*/
if (number == 0)
return 1;
/* Check for first and last digit of a number */
smallDigit = number % 10;
bigDigit = number;
while(bigDigit/10!=0)
{
bigDigit = bigDigit/10;
smallDigit = smallDigit*10;
}
/* Check to see if both digits are equal (Note: you can't use smallDigit here because it's been multiplied by 10 a few times) */
if (bigDigit != number%10)
return 0;
else
{
number = (number - smallDigit)/10; /* This is why smallDigit was multiplied by 10 a few times */
return pali(number); /* Recursion time */
}
}
I want to do a void factorial function in C that uses pointers. This is my code but it won't run.
#include <stdio.h>
void factorial(int, int*);
int main()
{
int n;
int r = 0;
printf("Enter n : ");
scanf("%d", &n);
if (n < 0)
{
printf("No factorial for negative");
}
else
{
factorial(n , &r);
printf("factorial of %d is %d", n, r);
}
}
void factorial(int n , int *r)
{
if (n == 0 || n == 1)
{
*r= 1;
}
else
{
*r= n* factorial((n-1), r);
}
}
The error I get is in the last line of the code saying : invalid operands of type "int" and "void" to binary operator * , what does that mean and how to fix it?
Well, if factorial() returns void (which is basically , returning nothing) , this line does not make any sense
*result = num * factorial ((num-1), result);
It's because factorial() returns void.
Try:
factorial((num-1), result);
*result= num *(*result);
Instead of that line.
You cannot use return value of a function if it is declared to return void.
If you want to declare function this way then your factorial function can be:
void factorial(int num , int *result)
{
if (num == 0 || num == 1)
{
//*result = 1;
return;
}
else
{
*result *= num;
factorial ((num-1), result);
}
But also in main function you should change int res = 0 into int res = 1.
void Factorial(int *a,int *result){
if (*a == 0 || *a == 1){
return;
}
else{
*result *= *a;
*a -= 1;
Factorial(a,result);
}}