Program stops when inputing a variable - c

This is literally my first lines of code in C, so it's really basic.
The code is this:
#include<stdio.h>
int main()
{
int l, b, ar, pr;
printf("Enter the length of the rectangle");
scanf("%d", l);
printf("Enter the breadth of the rectangle");
scanf("%d", b);
ar = l * b;
pr = 2 * (l + b);
printf("\n Area of Rectangle is: %d", ar);
printf("\n Perimeter of Rectangle is: %d", pr);
}
It starts running properly, outputs "Enter the length of the rectangle", but when I input a number, it just stops and I don't get to input the second value.
What am I missing?

You have to pass pointers to the variables to get the values instead of the values in the variables.
You should use unary & operators to get pointers like this:
scanf("%d", &l);
Note that you don't need & to read strings because arrays are automatically converted to pointers to the first element (except for some cases, including when used as an operand of unary & operator).
char str[10];
scanf("%9s", str);

Corrected code
#include<stdio.h>
int main()
{
int l, b, ar, pr;
printf("Enter the length of the rectangle");
scanf("%d", &l);
printf("Enter the breadth of the rectangle");
scanf("%d", &b);
ar = l * b;
pr = 2 * (l + b);
printf("\n Area of Rectangle is: %d", ar);
printf("\n Perimeter of Rectangle is: %d", pr);
}

Related

C program is not adding correctly when looping over an array

I was trying to find the sum of 5 numbers (in C Language) using tutorials from "thenewboston" on Youtube. My code is:
int main(int argc, char *argv[]) {
int a, b, c, d, e;
int array[5]={a, b, c, d, e};
int sum=0;
int i;
int j;
printf("Enter your 5 numbers: ");
scanf("%d, %d, %d, %d, %d", &a, &b, &c, &d, &e);
for (i = 0; i < 5; i++){
sum+=array[i];
}
printf("The sum of 5 numbers is:%d",sum);
return 0;
}
But the weird thing was, no matter what 5 numbers I entered, I always got the sum as 48.
Either discard variables a, b, c, d, e and the array remains or vice versa
Remove variables on your first printf:
print("Enter 5 numbers: ");
Don't put variables when you did't use them.
When you put scanf as scanf("%d, %d", &var1, &var2);, you must also input the same format as
Enter 5 numbers: 10, 20
Working example(more efficient with array):
int main() {
int input[5];
int sum;
printf("Enter 5 numbers: ");
scanf("%d, %d, %d, %d, %d", &input[0], &input[1], &input[2], &input[3], &input[4]);
int i;
for (i = 0; i < 5; i++) {
sum += input[i];
}
printf("The sum is %d", sum);
return 0;
}
You aren't storing a, b, c, d, or e into the array array. You need to store them in the array after you read them in.
Your declaration of array doesn't create an array of pointers to your variables - it creates a single pointer to a contiguous block of five integer fields. You can't update those array fields by just using the addresses of a, etc., since your array doesn't point to them.
The most obvious, clear, and simple way to store them in the array (which I recommend) is:
array[0]=a;
array[1]=b;
array[2]=c;
array[3]=d;
array[4]=e;
Do this just before the beginning of your for loop.

Integration by Simpson's Rule

One of my assignments was to create a c program that uses the Simpson's 1/3 rule to find the sum. I am running into issues that I am having trouble fixing. Can some one with more experience point me in the right direction?
In theory my code integrates y=ax^2+bx+c where the user selects values for a,b,c and then the user selects the upper and lower bounds [d,e]. Then the user selects the n value which splits up the area into more rectangles (the value that we will use in my class is 100, so the area is split into 100 rectangles). After which it runs through the Simpson's rule and prints out the sum.
//n is required number of iterations.
#include<stdio.h>
#include<conio.h>
#include<math.h>
double integral (int a,int b,int c,int d,int e,int n)
int main()
{
double a, b, c, d, e, n;
printf("Please select values for y=ax^2+bx+c");
printf("Please select value for a");
scanf("%d", &a);
printf("Please select value for b");
scanf("%d", &b);
printf("Please select value for c");
scanf("%d", &c);
printf("Please select value for the upper limit");
scanf("%d", &d);
printf("Please select value for the lower limit");
scanf("%d", &e);
printf("Please select the number of rectangles for the Simpson's Rule (Input 100)");
scanf("%n", &n);
int i;
double sum=0,length=(double)(d-e)/(n),ad,bd,cd,dd;
ad=(double)a;
bd=(double)b;
cd=(double)c;
dd=(double)d;
for (i=0;i<n;i++)
{
sum+=(ad*(dd*dd+2*dd*length*i+length*length*i*i)+bd*(dd+length*i)+cd)*length;
printf("the value is = %d",sum);
}
return sum;
}
Why do you think this
scanf("%e", &e);
should be that way?
The scanf() function takes a format specifier to match the scanned input with, in your case you want to store the values in a double variable, for which you need the "%lf" specifier, so all your scanf()'s should change to
scanf("%lf", &whateverDoubleVariableYouWantToStoreTheResultIn);
You don't need to cast from a variable of a given type to the same type, like here
dd=(double)d;
And also, you must know, that scanf() returns a value, you should not ignore it because your program will misbehave in case of bad input, you should check scanf() in a library manual or the C standard to understand better how to use it.
In addition to #iharob fine advice:
Change n type
// double a, b, c, d, e, n;
double a, b, c, d, e;
int n;
Adjust input code
// and previous lines
if (1 != scanf("%lf", &e)) // %d --> %lf
Handle_InputError();
printf("Please select the number of rectangles for the Simpson's ...
if (1 != scanf("%d", &n) // %n --> %d
Handle_InputError();
Adjust output
// printf("the value is = %d",sum);
printf("the value is = %e",sum); // or %f
Minor bits
// int main()
int main(void) // or int main(int argc, char *argv[])
// return sum; returning a double here is odd
return 0;

Calculate the length of a side of triangle in C

I am trying to write a program that calculates the length of one side of a triangle with the help of the Pythagoras equation (c²=a²+b²). The user must have the option to choose what side he want to calculate, this is what I have tried:
#include <conio.h>
#include <stdio.h>
#include <math.h>
// Pitagora:
// c=sqrt(pow(a,2)+pow(b,2));
// a=sqrt(pow(c,2)-pow(b,2));
// b=sqrt(pow(c,2)-pow(a,2));
int cateta(int x, int y){
int cat;
printf("Dati marimea lui:");
scanf("%d", &x);
printf("Dati marimea lui:");
scanf("%d", &y);
cat=sqrt(pow(x,2)-pow(y,2));
return cat;
}
int main(){
int a,b,c;
char l;
printf("Ce latura doriti sa aflati?");
printf("\n c : ipotenuza\n a : cateta alaturata\n b : cateta opusa\n");
printf("Introduceti litera laturei respective : ");
scanf("%s", &l);
if (l == a){
a=cateta(c,b);
printf("Marimea catetei alaturate este: %d", a);
}
else if (l == b){
b=cateta(c,a);
printf("Marimea catetei opuse este: %d", b);
}
else {
c=sqrt(pow(a,2)+pow(b,2));
printf("Marimea ipotenuzei este: %d", c);
printf("\n");
}
getch ();
return 0;
}
But, for some reason when I give a value of a to the variable &l the program displays the content of this piece of code: printf("Marimea ipotenuzei este: %d", c); instead of scaning the value of x and y, and terminates. Here is a picture with the result: https://www.dropbox.com/s/wzk3osw1t8729et/Untitled.png?dl=0
you are using %s in scanf() for a character type variable, instead use this
scanf(" %c", &l);
First, u need to change the scanf statement to scanf( "%c",&l);
Now the variable l contains the character entered by user.
Next, during comparison change the if condition to if(l=='a') , if( l=='b') as a and b are character literals.
With this changes, the program should work!
Happy coding!!

Error code: %d expected type int, but argument has type int *

I have an error code I do not understand:
format %d expects type int, but argument 2 has type int *
I do not know the difference between int and int *. I did not know there were different types of int, and cannot find any note of it on webpages about printf and scanf key letters.
The code is as follows:
#include <stdio.h>
#include <math.h>
int main(void)
{
int X = 0, Y = 0, A = 0, D = 0;
printf("This program computes the area of a rectangle ");
printf("and its diagonal length.");
printf("Enter Side 1 dimentions: ");
scanf("%d", &X);
printf("Enter Side 2 dimentions: ");
scanf("%d", &Y);
/* Calc */
A = X * Y;
D = pow(X,2) + pow(Y,2);
D = pow(D, 1 / 2);
/* Output */
printf("Rectangle Area is %d sq. units.", &A);
printf(" Diagonal length is %d.", &D);
return 0;
}
The error references the last two printf's:
printf("Rectangle Area is %d sq. units.", &A);
printf(" Diagonal length is %d.", &D);
Additionally, this program was originally written using floats (declaring X,Y,A, and D as float and using %f). But that gave an even stranger error code:
format %f expects type double, but argument 2 has type float *
I knew that %f is used for doubles and floats, so I could not understand why I had this error. After I got the error code about floats/doubles I tried changing everything to int (as shown in the above code), just to check. But that delivered the error code at the top of this post, which I do not understand either.
I've been using the gcc compiler.
Would someone explain what's being done wrong?
The problem is that you're trying to pass pointers to the printf function. Here's what your code looks like:
printf("Rectangle Area is %d sq. units.", &A);
printf(" Diagonal length is %d.", &D);
A is the int variable, but &A is a pointer to the int variable. What you want is this:
printf("Rectangle Area is %d sq. units.", A);
printf(" Diagonal length is %d.", D);
int* means a pointer to an int object. this is what you get because you use & before the variable name (i.e &A in your code)
You can read this to understand more about pointers and references, but basically if you omit the & before the variable names, it will work fine.
Why passing pointers to printf("...%d...", &D)?
Take a look to pointers explanation:
http://www.codeproject.com/Articles/627/A-Beginner-s-Guide-to-Pointers
And to simplified printf() manual:
http://www.cplusplus.com/reference/cstdio/printf/
int d = 1;
printf("I'm an integer: %d", 42); // OK, prints "...42"
printf("I'm an integer too: %d", d); // OK, prints "...1"
printf("I'm a pointer, I have no idea why you printing me: %p", (void*)&d); // OK, prints "...<address of d>", probably not what you want
printf("I'm compile-time error: %d", &d); // Fail, prints comiper error: 'int' reqired, but &d is 'int*'

c program to swap values printing wrong result [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Hi I have written a c program that reads in 2 values then swaps them and prints the new values except the second value keeps showing 0. For example it you enter 10 for 'a' and 8 tor 'b', then a will be 8 but b will be 0. Does anyone know the solution to fix this? Here is the code:
#include <stdio.h>
int getData()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
int a, b = getData();
swapValues(a, b);
return(0);
}
return (a, b);
doesn't do what you think it does, it's a misapplication of the comma operator.
The expression op1, op2 evaluates both op1 and op2 but gives you the value of op2. So it's not passing back a couple of values (although some languages like Python can do this sort of thing).
Similarly,
int a, b = getData();
won't grab the mythical two values returned from getData(). Rather it will set a to an indeterminate value and set b based on the single value returned from the function.
I would be looking at something like this:
#include <stdio.h>
int getData (char *which) {
int val;
printf ("Enter value for %s: ", which);
scanf("%d", &val);
return val;
}
void swapValues (int a, int b) {
printf("The swapped value of a is: %d\n", b);
printf("The swapped value of b is: %d\n", a);
}
int main (void) {
int a = getData ("a");
int b = getData ("b");
swapValues(a, b);
return 0;
}
You should also keep in mind that, if you actually want to swap the variables a and b and have that reflected back to main(rather than just print them as if they've been swapped), you'll need to pass pointers to them and manipulate them via the pointers.
C is a pass-by-value language meaning that changes to function parameters aren't normally reflected back to the caller. That would go something like this:
void swapValues (int *pa, int *pb) {
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
:
swapValues (&a, &b);
// a and b are now swapped.
You have unnecessarily complicated the whole thing.For one, something like return(a,b) is absurd in C.Further, if you intend to swap, why are you passing b as argument for the printf() meant to print 'a' and passing a to the printf() of 'b'?Anyways,here's a modified code that keeps it simple and gets the job done.
#include <stdio.h>
void swapValues()
{
int a, b,tem;
printf("Enter first number: ");
scanf("%d", &a);
printf("\nEnter second number: ");
scanf("%d", &b);
tem=a;
a=b;
b=tem;
printf("\nThe value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swapValues();
return(0);
}
First of all you can't return more than one value in C. The way around that is to return a struct or pass the values address.
void getData(int *a,int* b)
{
//int a, b;
printf("Enter first number: ");
scanf("%d", a); // look here you passed the address of a to scanf
// by doing that scanf can write to a
printf("Enter second number: ");
scanf("%d", b);
//return(a, b);
}
The old main:
int main()
{
int a, b = getData(); // b gets the return value from getData()
// but a is still uninitialized
//to call the new function you have to do the following
int a,b;
getData(&a,&b);
swapValues(a, b);
return(0);
}
You cannot return multiple values from a C function. I'm not even sure why the statement return(a, b) compiles.
If you want to return more than value from a function you should either put them into an array or a structure. I'm going to use a structure to demonstrate one way to do this correctly. There are many ways to do this, but this one modifies you code the least.
struct TwoNums{
int a;
int b;
};
TwoNums getData()
{
/* This creates a new struct of type struct TwoNums */
struct TwoNums nums;
printf("Enter first number: ");
scanf("%d", &(nums.a));
printf("Enter second number: ");
scanf("%d", &(nums.b));
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
/* Get the whole structure in one call */
struct TwoNums nums = getData();
/* Call the swap function using fields of the structure */
swapValues(nums.a, nums.b);
return 0;
}
The first:
getData() function is written incorrectly.
You can not return more than one parameter from the function in C. So you can to separate data reading, or use pointers as below:
void getData(int* a, int* b) {
printf("Enter first number: ");
scanf("%d", a);
printf("Enter second number: ");
scanf("%d", b);
}
In main()
int a, b;
getData(&a, &b);
The second:
swapValues(int a, int b) does not swap the data.
More correct:
void swapValues(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
without using temporary variable.
So try this code
#include <stdio.h>
int swape()
{
int a,b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
a=a+b;
b=a-b;
a=a-b;
printf("The value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swape();
return(0);
}

Resources