for loop resulting in undefined behaviour c - c

#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int mult;
int n;
int ans;
ans = mult * i;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 0; i<n; i++) {
printf("%d x %d = %d \n", &mult, &i , &ans);
}
return 0;
}
Hi guys, this is a simple code which is supposed to help the user to list the times table for n times. However, i am receiving undefined behaviour and I am quite stumped as to what is wrong with my implementation of my "for" loop.
I am receiving this as my output.
6356744 x 6356748 = 6356736
for n times in my consoles.
I want to ask
Is anything wrong with the logic of my code? (i assume i do have a problem with my code so please do enlighten me)
Would it be better(or even possible) to use pointers to point to the memory addresses of the mentioned variables when i have to change the value of the variables constantly? If yes, how do i go around doing it?
Thanks!

In printf you must provide integers. You are now giving the addresses of integers. So change
printf("%d x %d = %d \n", &mult, &i , &ans);
to
printf("%d x %d = %d \n", mult, i, ans);
and to make the table, replace ans with just mult*i, so:
printf("%d x %d = %d \n", mult, i, mult*i);
You should also check the return value of scanf to check if it has succeeded reading your input:
do {
printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);

The things you see are the values of the variables memory location.
Change your lines inside for loop as below
ans = mult * i;
printf("%d x %d = %d \n", mult, i, ans);

There are some mistakes in your code .
you are using the & operator in print statement which is used to print the address of the variable.
Initiate the loop with the value '1' instead of '0' & execute the loop till 'i' less than equal to 'n'.
instead of using the ans variable outside the loop , use it inside the loop as it evaluate the multiplication result in each iteration of the loop.
#include <stdio.h>
int main()
{
int i;
int mult;
int n;
int ans;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 1; i<=n; i++) {
ans = mult*i ;
printf("%d x %d = %d \n", mult, i , ans);
}
return 0;
}

Related

How To show original value of a variable after variable has been changed

So I'm having a problem about showing what my original variable value is after changing it in the code.
#include <stdio.h>
int main(){
int n, count =0;
printf("enter an integer = ");
scanf("%d", &n);
while (n!=0){
n/=10;
count++;
}
printf("your number %d has %d digits", n, count);
return 0;
}
Example input:123
Output of this code "your number 0 has 3 digits"
I want to know how to be able to refer the variable "n" in the printf to the original value of '123' so the output will be "your number 123 has 3 digits"
I would recommend that you use a separate variable to save your value or count with a different variable.
This code would look something like this:
#include <stdio.h>
int main()
{
int n, count =0;
printf("enter an integer = ");
scanf("%d", &n);
int buffer = n
while (buffer!=0)
{
buffer/=10;
count++;
}
printf("your number %d has %d digits", n, count);
return 0;
}
This way you save your variable in your code and you only used a buffer and not the actual value n.
You can keep a copy of the original variable and use that copy of the variable while printing.
You can do this:
int main(){
int n, count =0;
printf("enter an integer = ");
scanf("%d", &n);
printf("your number %d has ", n);
while (n!=0){
n/=10;
count++;
}
printf("%d digits", count);
return 0;
}
Of course, you may have to do some error checks..

C Program forLeast Square Regression Line and Errors

I wanted to create a program to calculate the regression line of some given data, along with the errors, so I can use in my university assignments. This is the following program:
#include <stdio.h>
#include <math.h>
int main(void)
{
int i,n,N;
double x[n],y[n],a=0.0,b=0.0,c=0.0,d=0.0,D,P=0.0,p,Sx,A,B,dA,dB;
printf("Give the number of data you want to input for x : ");
scanf("\n%d", &N);
printf("\nGive the values of x : ");
for (i=1; i<=N; i++);
{
printf("\n Enter x[%d] = ", i);
scanf("%lf", &x[i]);
a+=x[i];
b+=pow(x[i],2);
}
printf("\nGive the values of y : ");
for (i=1; i<=N; i++);
{
printf("\n Enter y[%d] = ", i);
scanf("%lf", &y[i]);
c+=y[i];
}
D=N*b-pow(a,2);
A=(b*c-a*d)/D;
B=(N*d-a*c)/D;
for (i=1; i<=N; i++);
{
d+=x[i]*y[i];
p=y[i]-A-B*x[i];
P+=pow(p,2);
}
Sx=sqrt(P/N-2);
dA=Sx*sqrt(b/D);
dB=Sx*sqrt(N/D);
printf("\n x \t \t \t y");
for (i=1; i<=N; i++);
printf("\nx[%d] = %lf\t%lf = y[%d]", x[i],y[i]);
printf("\nA = %lf\t B = %lf", A,B);
printf("\nThe errors of A & B are dA = %lf and dB = %lf", dA,dB);
printf("\nThe equation of the regression line is y=%lfx+(%lf)", B,A);
return 0;
}
I have two problems.
Despite giving a value to N, the program runs so that I can only give one value for x and one value for y. Why and where is the mistake?
When printing the "Enter x[%d]", it displays x[11] and at the end when printing "x[%d] = %lf\t%lf = y[%d]", it displays x[0]. Again why and where is the mistake?
Thank you for your help!
You are trying to create a dynamic array in C.
To do that, you need to use dynamic memory allocation with malloc and free. So, your code should look something like this:
int N;
double *x;
printf("Give the number of data you want to input for x :\n");
scanf("%d", &N);
x = malloc(sizeof(double) * N);
Then, at the end of your program you need to free the memory:
free(x);
If you don't want to deal with manual memory management (or can't for some reason), you can use a static maximum array size like this:
#define MAX_N_X 100
int main(void) {
int N;
double x[MAX_N_X];
printf("Give the number of data you want to input for x :\n");
scanf("%d", &N);
if (N > MAX_N_X) {
printf("Can't handle that many inputs! Maximum %d\n", MAX_N_X);
return 0;
}
}
You simply missed two parameters to printf.
Yo wrote:
printf("\nx[%d] = %lf\t%lf = y[%d]", x[i],y[i]);
But it should be:
printf("\nx[%d] = %lf\t%lf = y[%d]", i, x[i], y[i], i);
I found the main problem with this program a few days after posting this and the fix would be removing the ; from the for commands, along with some other minor changes. I thought I might add this comment to let you know and now it is working like a charm. The simplest of mistakes fools even the trained eyes. After I found this, I was shocked that no one picked up on this mistake.

C Programming sum of all integer numbers between two integers

I'm a newbie!
I'm supposed to get 2 integers from the user, and print the result(sum of all numbers between those two integers).
I also need to make sure that the user typed the right number.
The second number should be bigger than the first one.
And if the condition isn't fulfilled, I have to print "The second number should be bigger than the first one." and get the numbers from the user again until the user types right numbers that meet the condition.
So if I programmed it right, an example of the program would be like this.
Type the first number(integer) : 10
Type the second number(integer) : 1
The second number should be bigger than the first one.
Type the first number(integer) : 1
Type the second number(integer) : 10
Result : 55
End
I think that I have to make two loops, but I can't seem to figure out how.
My English is limited, to help your understanding of this quiz, I'll add my flowchart below.
I tried many different ways I can think of, but nothing seems to work.
This is the code that I ended up with now.
But this doesn't work either.
#include <stdio.h>
void main(void)
{
int a = 0;
int b = 0;
int total_sum = 0;
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
while (a > b) {
printf("The second number should be bigger than the first one.\n");
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
}
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : \n", total_sum);
}
Instead of using loop to sum the numbers, we can use mathematical formula.
Sum of first N integers= N*(N+1)/2
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int sum;
//Run infinite loop untill a>b
while(1)
{
printf("Type the first number : ");
scanf("%d", &a);
printf("Type the second number : ");
scanf("%d", &b);
if(a>b)
{
printf("The second number should be bigger than the first one.\n");
}
else
{
break;
}
}
//Reduce comlexity of looping
sum=((b*(b+1))-(a*(a-1)))/2;
printf("Result : %d " , sum);
return 0;
}
After corrections your code should run. The community has pointed out many mistakes in your code. Here's an amalgamated solution:
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int correctInput=0;
int total_sum = 0;
do
{
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
if(a<b)
correctInput=1;
else
printf("The second number should be bigger than the first one.\n");
}
while (correctInput ==0) ;
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : %d \n" , total_sum);
return 0;
}
Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced "n factorial") is equal to the product of the positive integers from 1 to n: n! = 1 x 2 x 3 x x n Write a program that takes as input an integer n and computes n!.

Can anyone help me with this C program?

I've just started to learn coding
#include <stdio.h>
int main(void)
{
int i=0, x=0;
for (i=1; i<=100; i++) {
x++;
if (x%5==0 || x%3==0)
printf("The numbers are : %d\n", &x);
}
return 0;
}
so I'm trying to print all the integers <=100 that are divisible by either 3 or 5.
In the line:
printf("the numbers are : %d", &x);
printf is expecting an integer because of the %d format specifier, you have given it the address of an integer, thats what the & means, address of x. To fix this give printf what it desires, an int:
printf("the numbers are : %d", x);
The ampersand (&) operator returns the address of a variable, which isn't what you want - you just want the value. Also, note that you don't need two variables (x and i) - you can just use the loop's counter:
printf("The numbers are:\n");
for (i = 1; i <= 100; i++) {
if (i % 5 == 0 || i % 3 == 0) {
printf("%d ", i);
}
}
Removing the & will eliminate the error. You may also want to move the "the numbers are:" statement outisde of the loop so the text does not print each time through the loop.

Getting an Array from user? C programming

My console keeps on crashing after entering a few numbers. I am trying to get an array of 10 numbers from the user thru the console and then taking count of positives, negatives, evens, and odds. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pos, neg, even, odd;
int nums[10];
printf("Give me 10 numbers: ");
pos = neg = even = odd = 0;
for(int i = 0; i < 10; i++){
scanf(" %d", nums[i]);
if(nums[i] > 0){
pos++;
if(nums[i] % 2 == 0){
even++;
}
else{
odd++;
}
}
else{
neg++;
}
}
printf("Positives: %d, Negatives: %d, Evens: %d, Odds: %d\n", pos, neg, even, odd);
return 0;
}
In your code,
scanf(" %d", nums[i]);
should be
scanf(" %d", &(nums[i]));
or,
scanf(" %d", nums+i);
as you need to pass the pointer to variable as the format specifier's argument in scanf() .
To elaborate, %d expects a pointer to int and what you're supplying is an int variable. it invokes undefined behavior.
That said,
Always check the return value of scanf() to ensure proper scanning.
int main() should be int main(void) to conform to the standard.
Modify scanf like scanf(" %d", &nums[i]);
scanf(" %d", nums[i]);
Scanf expects a pointer to a location to write to, and you're not giving it one.
Change your scanf to:
scanf(" %d", &(nums[i]));
to make your program work.
With this change I tested your program with stdin of
20 10 9 1 39 1 2 2 31 1
And recieved output:
Give me 10 numbers: Positives: 10, Negatives: 0, Evens: 4, Odds: 6
ideone of the thing for your testing purposes.
Change scanf(" %d", nums[i]); to scanf(" %d", &nums[i]);, because scanf() needs addresses. The parentheses around nums[i] isn't necessary, and may effect readability.
Also note that 0 is even, but not negative.
When scanf is usedto convert numbers, it expects a pointer to the corresponding type as argument, in your case int *:
scanf(" %d", &nums[i]);
This should get rid of your crash. scanf has a return value, namely the number of conversions made or the special value EOF to indicate the end of input. Please check it, otherwise you can't be sure that you have read a valid number.
When you look at your code, you'll notice that you don't need an array. Afterreading the number, you don't do aything with the array. You just keep a tally of odd, even and so on numbers. That means you just need a single integer to store the current number. That also extends your program nicely to inputs of any length.
Here's a variant that reads numbers until the end of input is reached (by pressing Ctrl-D or Ctrl-Z) or until a non-number is entered, e.g. "stop":
#include <stdlib.h>
#include <stdio.h>
int main()
{
int count = 0;
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
int num;
while (scanf("%d", &num) == 1) {
count++;
if (num > 0) pos++;
if (num < 0) neg++;
if (num % 2 == 0) even++;
if (num % 2 != 0) odd++;
}
printf("%d numbers, of which:\n", count);
printf(" %d positive\n", pos);
printf(" %d negative\n", neg);
printf(" %d even\n", even);
printf(" %d odd\n", odd);
return 0;
}
Change scanf statement after for loop to
scanf(" %d", &nums[i]);

Resources