I want to know the cause of the Segmentation Fault error - c

#include <stdio.h>
#pragma warning(disable:4996)
int math(int a, int b) {
if (a > b) {
printf("%d %d %d", a + b, a - b, a * b);
}
else if (b > a) {
printf("%d %d %d", b + a, b - a, b * a);
}
}
int main(void) {
int n1, n2;
scanf("%d %d", &n1, &n2);
printf(math(n1, n2));
return 0;
}
A program that takes two integers and produces and outputs a function that converts the results of addition, subtraction, and multiplication of two integers. However, a Segmentation Fault error occurs when the compilation is executed. I want to know the cause of the code.
An error appears even if you create and output addition, subtraction, and multiplication functions respectively.

As mentioned in the comments, the printf function is expecting a format string prior to the call to the "math" function. With that in mind here is a snippet of code with some tweaks to avoid the segmentation fault the original code runs into.
#include <stdio.h>
int math(int a, int b) {
int result = 0;
if (a > b) {
printf("%d %d %d\n", a + b, a - b, a * b);
result = (a + b) + (a - b) + (a * b);
}
else if (b > a) {
printf("%d %d %d\n", b + a, b - a, b * a);
result = (a + b) + (b - a) + (a * b);
}
return result; /* Since this function is defined to return an integer */}
int main(void) {
int n1, n2;
printf("Enter in two integers: "); /* Aids the user to know what they are supposed to enter */
scanf("%d %d", &n1, &n2);
printf("The result of calling the math function is %d\n", math(n1, n2)); /* Revised the usage of the printf function */
return 0;
}
A couple of things to point out.
Since the "math" function is defined to return an integer, an integer variable was added to the function to accept a calculated value and then be returned to the statement that called the "math" function.
The printf statement is corrected so that it contains a formatting string to define what and how data is to be printed out.
Following is a sample of a test run from the terminal.
#Dev:~/C_Programs/Console/Formulas/bin/Release$ ./Formulas
Enter in two integers: 33 45
78 12 1485
The result of calling the math function is 1575
Give those tweaks a try to see if it meets the spirit of your project.

Related

How NOT to read float type in scanf when reading type int

I need to write two integers (and nothing else) to variables. It does the validation makes sure that none of args is a string and that they are not empty and excepts division by zero, or when i put float as a first arg but when i put float as a second argument it does not makes an exception. How can i solve it using only stdio.h?
#include <stdio.h>
void sum(int a, int b);
void dif(int a, int b);
void prod(int a, int b);
void qut(int a, int b);
int main() {
int x, z;
int digits = scanf("%d %d", &x, &z);
if (digits != 2) {
printf("n/a\n");
return 2;
}
else {
sum(x, z);
dif(x, z);
prod(x, z);
qut(x, z);
}
return 0;
}
void sum(int a, int b) {
printf("%d ", a + b);
}
void dif(int a, int b) {
printf("%d ", a - b);
}
void prod(int a, int b) {
printf("%d ", a * b);
}
void qut(int a, int b) {
if (a == 0 || b == 0) {
printf("n/a\n");
}
else {
printf("%d\n", a / b);
}
}
Sorry, i understand that the code is quiet simple and my question is quiet dumb :)
Thx!
As mentioned in the comments, scanf is the WRONG TOOL for this job. scanf is notoriously bad at error handling.
Theoretically it's possible — barely possible — to solve this problem using scanf. By the same token, it's possible to drive a screw into a piece of wood using a hammer. But it's a terrible idea. A woodshop teacher who taught his students to drive screws using a hammer would be fired for incompetence. But for some reason we tolerate this kind of incompetence in teachers of beginning programming.
Normally I don't do homework problems here; normally that's a bad idea, too; normally it makes much more sense to have you, the student, do the work and acquire the learning. In the case of boneheaded assignments like this one, though, I have no qualms about giving you a fully-worked-out solution, so you can get your incompetent instructor off your back and go on to learn something more useful. Here is the basic idea:
Read a line of text (a full line), using fgets.
Parse that line using sscanf, ensuring that it contains a number and a number, and nothing else.
Specifically, we'll use %d to read the first integer, and %d to read the second integer, and then we'll use a third %c to pick up whatever character comes next. If that character is anything other than the \n that marks the end of the line, it indicates that the user has typed something wrong, like a string, or the . that's part of a floating-point number.
This is basically the same as user3121023's solution.
int main()
{
char line[100];
int x, z;
char dummy;
if(fgets(line, sizeof(line), stdin) == NULL) return 1;
int digits = sscanf(line, "%d%d%c", &x, &z, &dummy);
if(digits < 2 || digits > 2 && dummy != '\n') {
printf("n/a\n");
return 2;
}
...
See also What can I use for input conversion instead of scanf?
Footnote: The code here has one unfortunate little glitch: If the user types a space after the second number, but before the newline, the code will reject it with n/a. There are ways to fix that, but in my opinion, for this exercise, they're just not worth it; they fall under the "law of diminishing returns". If your users complain, just act like incorrigible software vendors everywhere: remind them that they were supposed to type two numbers and nothing else, and the space they typed after the second number is "something else", so it's THEIR FAULT, and not your bug. :-)
After scanning for the integers, use a loop to scan for one whitespace character. Break out of the loop on a newline.
For any other character, the scan will return 0.
#include <stdio.h>
void sum(int a, int b);
void dif(int a, int b);
void prod(int a, int b);
void qut(int a, int b);
int main() {
char ws[2] = ""; // whitespace
int scanned = 0;
int x, z;
int digits = scanf("%d %d", &x, &z);
if (digits != 2) {
printf("n/a\n");
return 2;
}
while ( ( scanned = scanf( "%1[ \t\n]", ws))) { // scan for 1 whitespace
if ( scanned == EOF) {
fprintf ( stderr, "EOF\n");
return 1;
}
if ( ws[0] == '\n') {
break;
}
}
if ( scanned != 1 || ws[0] != '\n') {
printf("n/a\n");
return 3;
}
else {
sum(x, z);
dif(x, z);
prod(x, z);
qut(x, z);
}
return 0;
}
void sum(int a, int b) {
printf("%d ", a + b);
}
void dif(int a, int b) {
printf("%d ", a - b);
}
void prod(int a, int b) {
printf("%d ", a * b);
}
void qut(int a, int b) {
if (a == 0 || b == 0) {
printf("n/a\n");
}
else {
printf("%d\n", a / b);
}
}

Using a recursive function ,find a program that computes the multiplication of two numbers using addition operator

Using a recurrence function ,find a program that computes the multiplication of two numbers using addition operator.
What I found is as follows:
/*C program to multiply two numbers using plus operator.*/
#include <stdio.h>
int main()
{
int a,b;
int mul,loop;
printf("Enter first number: ");
scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);
mul=0;
for(loop=1;loop<=b;loop++){
mul += a;
}
printf("Multiplication of %d and %d is: %d\n",a,b,mul);
return 0;
}
However I'm not sure if the it uses a recurrence function,can someone check that and if it does use a recursive function then show me how to do that?
This simple logic should work for you:
int multiply(int a, int b)
{
if(a < b)
return multiply(b, a); // swap
else if(b != 0)
return (a + multiply(a, b - 1)); // recursion
else
return 0;
}

Error while executing code MSB6006 "CL.exeexecuted with code 2

I am getting the following error while executing code on Visual Studio 2019
MSB6006"CL.exe" exited with code 2
#include<stdio.h>
#include<conio.h>
int main()
{
int a, b, c,x;
x = a / (b - c);
printf("\n Enter values of a,b and c");
scanf_s("%d%d%d", &a, &b, &c);
printf("\n The value of x is %d", x);
return 0;
}
Your order of statements is off.
First assign values to a, b, and c.
Only after use those values in calculations.
#include <stdio.h>
int main(void) {
int a, b, c, x;
// x = a / (b - c); // NOPE! a, b, and c have no valid values
printf("Enter values of a, b and c\n");
scanf("%d%d%d", &a, &b, &c);
x = a / (b - c); // calculation moved here; a, b, and c (hopefully) have valid values now
printf("The value of x is %d\n", x);
return 0;
}
Note: the return value of scanf() should be checked to be sure all of a, b, and c have valid values.
if (scanf("%d%d%d", &a, &b, &c) != 3) /* error */;
Note 2: I changed your code a little bit: removed non-standard <conio.h>, changed the placing of most '\n' to be more line-oriented, replaced the optional scanf_s (this function may not exist in all C11/C18 implementations).

Returns a value as an output parameter

I have a question in C where I need to insert coefficients of a quadratic equation into a function and return the number of solutions and result.
Write a program that accepts a series of 3 real numbers, which are the
coefficients of a quadratic equation, and the program will print out
some solutions to the equation and the solutions themselves.
Guidelines:
Functions must be worked with one of the functions that
returns the number of solutions as a returned value, and returns the
solutions themselves through output parameters.
3 numbers must be
received each time. The input will be from a file (will end in EOF)
In the meantime I built the function without reading from a file just to see that it works for me, I built the function that returns the number of solutions but I got entangled in how to return the result as output parameter
here is my code for now:
int main ()
{
double a, b, c, root1,root2,rootnum;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
rootnum=(rootnumber(a,b,c);
printf("the number of roots for this equation is %d ",rootnum);
}
int rootnumber (double a,double b, double c)
{
formula=b*b - 4*a*c;
if (formula<0)
return 0;
if (formula==0)
return 1;
else
return 2;
}
In C, providing an "output parameter" usually amounts to providing an argument that is a pointer. The function dereferences that pointer and writes the result. For example;
int some_func(double x, double *y)
{
*y = 2*x;
return 1;
}
The caller must generally provide an address (e.g. of a variable) that will receive the result. For example;
int main()
{
double result;
if (some_func(2.0, &result) == 1)
printf("%lf\n", result);
else
printf("Uh oh!\n");
return 0;
}
I've deliberately provided an example that illustrates what an "output parameter" is, but has not relationship to the code you actually need to write. For your problem, you will need to provide two (i.e. a total of five arguments, three that you are providing already, and another two pointers that are used to return values to the caller).
Since this is a homework exercise, I won't explain WHAT values your function needs to return via output parameters. After all, that is part of the exercise, and the purpose is for you to learn by working that out.
Apart from a wayward parenthesis in the call and some other syntax errors, what you have so far looks fine. To print out the number of roots, you need to put a format specifier and an argument in your printf statement:
printf("the number of roots for this equation is %d\n", rootNum);
The %d is the format specifier for an int.
Here is your working code:
#include <stdio.h>
int rootnumber (double a,double b, double c)
{
double formula = (b*b) - (4*(a)*(c));
if (formula > 0) {
return 2;
}
else if (formula < 0) {
return 0;
}
else {
return 1;
}
}
int main (void)
{
double a, b, c;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
printf("The number of roots for this equation is %d ", rootnumber(a,b,c));
return 0;
}
It just need some sanity checking, its working now:
#include<stdio.h>
int rootnumber(double a, double b, double c);
int main ()
{
double a, b, c, root1,root2;
int rootnum;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
rootnum=rootnumber(a,b,c);
printf("the number of roots for this equation is %d", rootnum);
return 0;
}
int rootnumber(double a, double b, double c)
{
int formula= (b*b) - (4*a*c);
if (formula<0)
return 0;
if (formula==0)
return 1;
else
return 2;
}

Scan multiple variables depending on test cases?

I want to calculate sum of arithmetic progression in which we have to take 3 variables from user. a=first number, b= step size/increment, c=length of sequence.
If there are more than 1 test case , say three, then I have to scan a,b,c three time. How to do this?
E.g scanf (" %d %d %d", a,b,c); 3 times without affect initial values in first test case.
If you know no of test cases read it first and store it in a variable.
int calculate_ap(int a, int b, int c)
{
//Implement function to calculate Arithmetic progression and return the result
}
int main()
{
int test_cases = 0;
int a, b, c;
scanf("%d", &test_cases); //Reads no of test cases
while(test_cases--)
{
scanf("%d, %d, %d", &a, &b, &c); //read A, B, C
printf("%d\n", calculate_ap(a, b, c));
}
}
Hope this helps.

Resources