I have written two code for max and min. The first is without, the second with an extra function.
The first one works, but for second one minimum is always 1. Why?
What causes the problem?
(1) Code without function:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x,n,min=x,max=1,cnt;
while(1){
cnt=0;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
while (cnt!=n){
scanf("%d",&x);
cnt++;
if(x>max)
max=x;
if(x<min)
min=x;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
system("cls");
}
return 0;
}
(2) Code with function:
#include <stdio.h>
#include <stdlib.h>
int maximum(int);
int main(int argc, char *argv[]) {
int n;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
maximum(n);
return 0;
}
//*****************************************
int maximum(int n){
int i,a,max=1,min=a;
printf("enter your number\n");
for(i=1;i<=n;i++){
scanf("%d",&a);
if(a>max)
max=a;
if(a<min)
min=a;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
}
Your code causes undefined behavior. Undefined behavior means, anything could happen.
You have not initialized the variable a and you are doing min=a;
C99 section 6.7.8 Initialization:
If an object that has automatic storage duration is not initialized explicitly,
its value is indeterminate.
C99 section 3.18 Un-defined behavior:
Behavior, upon use of a non-portable or erroneous program construct, of erroneous
data, or of indeterminately valued objects, for which this International Standard
imposes no requirements.
This means, compiler is free to do anything. It can crash your program, your program might print JLo pic on your monitor...Etc...
Your code invokes undefined behavior because the assignment min=x in first and min=a in second done without initializing x and a. In this case you may get anything, either expected or unexpected result or segmentation fault or program crash.
To fix this issue you can modify your code as
Code 1.
int x,n,min,max=1,cnt;
while(1){
cnt=1;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
scanf("%d",&x);
min = x;
while (cnt!=n){
scanf("%d",&x);
...
...
Code 2.
int maximum(int n){
int i,a,max=1,min;
printf("enter your number\n");
scanf("%d",&a);
min = a;
for(i=1;i<n;i++){
scanf("%d",&a);
...
...
Related
I using a old version of Borland for C lang.
At the beginning of the program you enter the name (full name, FIO), then 4 digits (as grades). The program calculates the average among 5 entered FIO and back a average number.
#include <stdio.h>
#include <conio.h>
int main(){
struct nya{
char a[100];
int x[4];
}A[5];
int i;
for(i=0;i<5;i++){
puts("FIO");
scanf("%s", A[i].a);
puts("4 ocenki");
for(int g=0;g<4;g++){
scanf("%i", A[i].x[g]);
}
clrscr();
}
float bird=0, comme[5];
for(i=0;i<5;i++){
comme[i]=0;
}
for(i=0;i<5;i++){
for(int g=0;g<4;g++){
comme[i]+=A[i].x[g];
}
comme[i]=comme[i]/4;
bird+=comme[i];
}
bird=bird/5;
printf("Sredny = %f", bird);
}
change scanf("%i", A[i].x[g]); to scanf("%i", &A[i].x[g]); (with a &)
thanks to #Blaze
I typed the following code to sort the components of an int array. It does not show any error but does stops working abruptly. The error is generally after entering 7-8 inputs which shows that program.exe has stopped working. Does it has anything related to the code ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,a[n],i,j,temp;
printf("Enter number of inputs.\n");
scanf("%d",&n);
printf("Enter inputs\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Numbers in descending order are:\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
return 0;
}
The problem is here:
int n, a[n], i, j, temp;
Declarations are done sequentially. If you write this in a slighly more readably (but equivalent form) you'd have this:
int n;
int a[n]; // here the variable n has not yet been initialized
// it contains an indeterminate value, and therefore the a array
// will have an indeterminate size and the program will have
// so called "undefined behaviour " (google that)
int i;
...
You should write the beginning of your program like this:
int main()
{
int n,i,j,temp;
printf("Enter number of inputs.\n");
scanf("%d",&n);
int a[n]; // now n has a determinate value
printf("Enter inputs\n");
Disclaimer: no error checking is done for brevity.
Always compile with warnings enabled and listen to them. Many of them are actually errors. Especially the warning variable 'somevar' is uninitialized when used here is always an error.
So i have this type of problem. How to make an array 1*x and then sum up its digits together. I wrote down something like this for now. Any ideas? Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int a,i,w,j,m;
int s[a];
printf("How many digits do you want to sum up\n");
scanf("%d",&a);
for(i=0;i<a;i++)
{
printf("Enter numer %d: ",i);
scanf("%d",&s[i]);
}
for(j=0;j<a;j++)
{
m=s[j]+s[j++];
}
printf("\n %d",m);
return 0;
}
The problems of your code are:
int a;
int s[a];
Here a is uninitialized.So,array size is unknown which is incorrect.And,instead of this
m=s[j]+s[j++];
you should do like this :
m += s[j];
One more thing,you have initialize m = 0 before starting to add.
I've Changed your program to this:
#include <stdio.h>
int main(int argc, char *argv[]) {
int a,i,m = 0;
//First get the array size
printf("How many digits do you want to sum up\n");
scanf("%d",&a);
//Then declare the array with the size (a)
int s[a];
for(i = 0; i < a; i++){
printf("Enter numer %d: ",i);
scanf("%d",&s[i]);
m += s[i];
}
printf("\n %d",m);
return 0;
}
Using uninitialized variable is undefined behaviour.
int s[a];
The above statement defines an array s of size a but the value of a is unpredictable since it is uninitialized and contains garbage. The size of the array must be known when it defined and it remains the same throughout its lifetime. You cannot resize your array by changing the value of a here. You can use dynamic memory allocation using malloc.
Further, the following statement again invokes undefined behaviour -
m=s[j]+s[j++];
That's because it violates the the following rule stated in the C99 standard §6.5 ¶2
Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an expression.
Furthermore, the prior value shall be read only to determine the value
to be stored.
I am not able to understand why it is showing this error.
I have never encountered such an error before.
Here is my code, can you identify the mistake or the cause of it :
#include<stdio.h>
#include<math.h>
void dec2bin(int n,int bin[1000]){
int num = 0, index = 0, i;
while (n != 0){
bin[index] = n%2;
index++;
n = n/2;
}
}
int Sub(int a[100],int b[1000],int ac[100],int siz){
int i=siz-1,k=0;
for(;i>=0;i--){
if(b[i]){
a[k++]=ac[siz-i-1];
}
}
return k;
}
int sum(int a[100],int s){
int i,sum=0;
for(i=0;i<s;i++)
sum+=a[i];
return sum;
}
main(){
int b[1000],sub[100],a[100],n,i,s,count=0;
printf("Enter n: ");
scanf("%d",n);
for(i=0;i<n;i++){
printf("Enter number %d",i+1);
scanf("%d",&a[i]);
}
printf("Enter S: ");
scanf("%d",s);
int no=(int)pow(2.0,(float)n);
for (i=0;i<1000;i++)
b[i]=0;
for(i=0;i<no;i++){
dec2bin(i,b);
int siz=Sub(sub,b,a,n);
if(sum(sub,siz)==s)
count++;
}
printf("Subsets: %d",count);
}
And this code shows memory fault error immediately after entering the value of n.
You're using scanf slightly incorrectly.
The arguments following the format string need to be pointers to your objects, not the objects themselves.
scanf("%d", &n);
Do remember though, that scanf is very dangerous to use. Behavior is undefined for instance if the integer would overflow. Better to read a line safely then use strtol to parse it, since you can detect errors properly.
when taking input for n.
scanf("%d", &n);
You forgot a &
Note: This is a homework question.
Use FOR construction to fill 2D board with values that were given by
user. The program asks for board size n, m and then it asks for each
board value.
My try
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i = scanf("%d",&i);
printf("Enter the number of rows");
int y = scanf("%d",&y);
int r[i][y];
int a;
int b;
for (a=0; a<i; a++){
for(b=0; b<y; b++){
int r[a][b] = scanf("%d",&a,&b); //bug
}
}
}
Bug: c:13 variable-sized object may not be initialized
EDIT:
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i;
scanf("%d", &i);
printf("Enter the number of rows");
int y;
scanf("%d", &y);
int r[i][y];
int a;
int b;
for (a=0; a<i; a++){
for (b=0; b<y; b++){
scanf("%d",&r[a][b]);
}
}
}
scanf takes the address of the variable that is being read and returns the number of items read. It does not return the value read.
Replace
int i = scanf("%d",&i);
int y = scanf("%d",&y);
by
scanf("%d",&i);
scanf("%d",&y);
and
int r[a][b] = scanf("%d",&a,&b);
by
scanf("%d",&r[a][b]);
EDIT:
You are using variable length array (VLA) in your program:
int r[i][y];
as i and y are not constants and are variables. VLA are a C99 standard feature.
you have to allocate the 2D array dynamically cause you don't know it size in compilation.
replace
int r[i][y];
with
int *r = malloc(i*y*sizeof(int));
and when finish, add:
free(r);
*and also the SCANF errors, people already answered here.
First the return value of scanf isn't the value that was read from stdin, instead it is the number of input values scanf read.
Secondly, C does not allow creation of arrays by using variables. You have to first create one array by dynamically allocating it. And for each entry in the first array you have to create yet another array.
Don't forget to free the memory you allocate!
The use of scanf(%d, &var) is incorrect.
scanf reads from console an integer (this type is specified by its first paramenter %d) and stores it in the second parameter.
This second parameter must be a pointer, so an & is needed when your variable is not a pointer yet.
Therefore you should correct your code in this way:
int i;
scanf("%d",&i);
int y;
scanf("%d", &y);
And in your for loop
scanf("%d", &r[a][b]);
It doesn't print the message because of line buffering.
If you add \n to your strings (to start a new line), it might do what you expect:
printf("Enter the number of columns\n");
Alternatively, if you really want the user to type on the same line, you need to flush the buffer manually:
printf("Enter the number of columns");
fflush (stdout);