I'm having a small issue with this problem and I could really use another set of eyes with this. I am basically trying to read a matrix that I input and then display the said matrix.
The program always returns a null matrix (0 on all positions). The size of the matrix (columns/rows) is good. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#define MAXN 10
void display_matrix(int n, int m, double a[MAXN][MAXN], char ch)
{
int i, j;
printf("\n MATRIX %c\n", ch);
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++) printf("%8.2lf ",a[i][j]);
printf("\n");
}
}
void read_matrix(int *n, int *m, double a[MAXN][MAXN])
{
int i,j;
printf("\nInput of size and elements of a matrix\n");
printf("\n\tNumber of rows, n=");
scanf("%d", n);
printf("\n\tNumber of columns, m=");
scanf("%d", m);
printf("\n\tThe elements of the matrix\n");
for (i = 0; i < *n; i++)
{
for(j = 0; j < *m; j++)
{
printf("a[%d,%d]=", i, j);
scanf("%lf",&a[i][j]);
}
}
printf("\n");
}
void main()
{
int n, m;
double a[MAXN][MAXN];
read_matrix(&n, &m, a);
display_matrix(n, m, a, 'X');
return 0;
}
Your code seems mostly fine (main() should have a return type of int, and you should always check the return value of scanf()), except possibly for the following line:
printf("%8.2lf ",a[i][j]);
Prior to the C99 standard, the l modifier was not defined in conjunction with the f conversion specifier. Using the two in combination resulted in undefined behaviour. I don't know what the odds are, but it is not inconceivable that you have a pre-C99 C library that either misbehaves or implements %lf to match something entirely different, perhaps long double.
To print a double, you should use the %f conversion specifier:
printf("%8.2f ",a[i][j]);
This is just clutching at straws though. It might not change anything at all for you.
Background
The scanf() function has different conversion specifiers for float (%f) and double (%lf), because it need to know the exact type that the corresponding pointer argument is pointing to.
But when you pass a float to a variadic function, such as printf(), the default argument promotions convert the float to a double. Hence, the printf() function does not need a conversion specifier for float, because there is no way to pass a float to it. The C99 standard added the l modifier just for symmetry with the scanf() function.
References
The C90 Standard: ISO/IEC 9899:1990 (Withdrawn)
The C99 Standard: ISO/IEC 9899:1999 (Withdrawn)
The C11 Standard: ISO/IEC 9899:2011 (Withdrawn)
The C18 Standard: ISO/IEC 9899:2018 (Current)
Related
Here is my factorial program—this is executing and giving a correct result:
#include <stdio.h>
int main()
{
int n;
printf("enter the no=");
scanf("%d", &n);
fun(n);
printf("%d\n", fun(n));
return 0;
}
int fun(int n)
{
if(n == 0)
return 1;
else
return fun(n - 1) * n;
}
This is my program to compute the power of a number—this is giving 0 instead of the correct result and yet is almost identical:
#include <stdio.h>
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
pow(m, n);
printf("%d\n", pow(m, n));
return 0;
}
int pow(int m, int n)
{
if(n == 0)
return 1;
else
return pow(m, n - 1) * m;
}
Both are running on same compiler.
Why is my factorial program working but my almost identical power program is not working?
A few issues are present here. First and foremost, you didn't declare a prototype for your function before calling it the first time. To do so, you need to place int pow(int, int); above main. This lets the compiler know exactly what your function expects and what it returns.
Ordinarily, this wouldn't cause the behavior you're seeing (though it is bad practice), but there's also already a function named pow in the C library. Since you never gave it a definition of your own, it's being implicitly included in your code. Now, it's expecting you to put two doubles in and get a double out.
Add the prototype at the top and rename your function, and you'll fix both of these issues at once.
Demo
(Also, for what it's worth, you've got an unnecessary call.)
#include <stdio.h>
int powr(int, int); // helps avoid compiler warnings
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
powr(m, n); // unnecessary
printf("%d\n", powr(m, n));
return 0;
}
int powr(int m, int n)
{
if(n == 0)
return 1;
else
return powr(m, n - 1) * m;
}
For a little backstory behind this: The GNU C compiler (presumably what you're using) has implicit declarations for most of the Standard C Library functions that can be optimized in target-specific ways. pow is one of them.
To fix this, you should rename your pow function to something not reserved by the Standard C library and provide a prototype for it, like so:
#include <stdio.h>
int power(int m, int n);
If you compile in strict C89/C90 compliance mode, you don't even need to provide a prototype due to implicit function declaration rules. However, if you compile with any other standard (which is the default and highly recommended), you'll need to provide a prototype for that function, as shown above.
I'd also like to note that you have an unnecessary call to your power-computing program (also present in the factorial-computing program):
scanf("%d%d", &m, &n);
power(m, n); // here
printf("%d\n", power(m, n));
So I was pondering about this problem in C using only stdio.h -
I have to write a program that reads an integer p and then reads p integers. Now I have to use these p integers and perform another operation on them to get a final answer, which my main program will return.
The problem is I don't know how to perform an operation on a variable number of integers. I tried using pointers but they don't seem to work.
Can anyone help please?
#include <stdio.h>
int main(){
int i, p, n;
scanf ("%d", &p);
for (n=0; n<p; n++){
int a;
scanf ("%d", &a);
int *k=&a;
}
for (n=0; n<p; n++){
int a=*k;
if (a==0)
i=0;
else i=1;
}
return i;
}
What I want to do here is to read a certain integer p, then read p integers a, and if at least one of these as is 0, my answer is 0. Otherwise it's 1.
But the compiler says *k is not defined for the second for loop. What should I do?
I think you can do this with a fixed number of variables. Like
int p, a, ans=1;
scanf("%d", &p); //read number
for(int r=0; r<p; ++r)
{
scanf("%d", &a);
if(a==0)
{
ans=0;
break;
}
}
printf("\nAnswer is: %d", ans);
ans variable holds the answer. First you read the number of ints into p and then read p number of ints using a loop.
During each iteration of the loop, you read into the same variable a. You just need to know if at least a single input is zero.
ans is initially set to 1 and is changed to 0 only if a zero is input. If zero is input, the control exits the loop immediately because of the break statement.
You may want to check the return value of scanf() and other error checking.
Various ways to use an unknown number of variables is mentioned in the comments.
If you can use C99, variable length array are allowed. Like
int p;
scanf("%d", &p);
int arr[p];
If dynamic memory allocation is used, you could use malloc() or calloc() which are in stdlib.h.
See this.
And the pointer k in
for (n=0; n<p; n++){
int a;
scanf ("%d", &a);
int *k=&a;
}
for (n=0; n<p; n++){
int a=*k;
if (a==0)
i=0;
else i=1;
}
is a local variable of the first loop and is hence visible only to that loop and is invisible to the second loop. k's scope is limited to the first loop. See this.
If you want a variable to be visible in both the loops, declare it outside both.
First things first, I'll help you understand the compiler error you talked about:
k is not defined for the second for loop
// some code
for (n=0; n<p; n++){
int a;
scanf ("%d", &a);
int *k=&a; // Definition of k is here, and is restricted to this block,
}
for (n=0; n<p; n++){
int a=*k; // Its undefined here
if (a==0)
i=0;
else i=1;
}
// some code
Explanation: Read the comment in the code. What I meant by block is the code between the upper '{' and lower '}'. Beyond these, anywhere in code, k is undefined. Hence in second loop, the k is undefined.
You should change your main() function to:
int main()
{
int i, p, n, k = 0;
scanf ("%d", &p);
for (n=0; n<p; n++) {
int a;
scanf ("%d", &a);
int *k=&a;
}
for (n=0; n<p; n++) {
int a=*k;
if (a==0)
i=0;
else
i=1;
}
return i;
}
Now to address your next issue, I guess you might want to study variadic functions in C. I may be wrong in understanding your problem statement, but my take on it is that you are willing to pass multiple arguments to a function. For example,
At some time, you want to call function as:
function(Count_args, 1, 2, 3, 4, 5);
and sometimes as:
function(Count_args, 10);
If I am right, you might want to take a look at this example on the same reference I cited above. For making your life easier, I am adding the same code here:
#include <stdarg.h>
#include <stdio.h>
int
add_em_up (int count,...)
{
va_list ap;
int i, sum;
va_start (ap, count); /* Initialize the argument list. */
sum = 0;
for (i = 0; i < count; i++)
sum += va_arg (ap, int); /* Get the next argument value. */
va_end (ap); /* Clean up. */
return sum;
}
int
main (void)
{
/* This call prints 16. */
printf ("%d\n", add_em_up (3, 5, 5, 6));
/* This call prints 55. */
printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
return 0;
}
If you are willing to know that latest standard says about having variable arguments to a function, refer C11, section 7.16 Variable arguments , it does help!
#include <stdio.h>
int main(void) {
int t;
long long int a[100000], n, i;
scanf("%d\n", &t);
while(t){
t--;
scanf("%d", &n);
printf("%ld\n", n);
n = n * (n-1);
printf("%ld\n", n);
n = n/2;
printf("%ld\n", n);
}
return 0;
}
Can't figure out the problem in division. It's returning garbage value in the third printf statement. Can you please help me identify where the problem is?
The format specifier for long long int is lld, not ld.
That's especially important in the scanf as using the wrong specifier may end up putting the data in the wrong bytes within the variable.
My program is supposed to order a list of numbers inputed by the user, but it crashes even before reaching the first printf. My compiler makes 2 warnings, but I don't see the issue. I haven't studied pointers yet, so I didn't want to use them. Here are the messages:
In function `selection_sort':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
In function `main':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
.
#include<stdio.h>
int selection_sort(int n, int v[n])
{
int high = v[0];
int i;
for(i = 0; i < n; i++)
high = high < v[i]? v[i] : high;
if(n - 1 == 0)
return;
v[n - 1] = high;
n -= 1;
selection_sort(n, v[n]);
}
int main(void)
{
int n, i;
int v[n];
printf("Enter how many numbers are to be sorted: ");
scanf("%d", &n);
printf("Enter numbers to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &v[i]);
selection_sort(n, v[n]);
printf("In crescent order: ");
for(i = 0; i < n; i++)
printf("%d ", v[i]);
getch();
return 0;
}
Your program is using a variable length array, a feature that was added in C99.
However, you declare its size based on an uninitialized variable. What did you believe would happen there?
In C, variables declared inside functions are NOT set to 0. They are not set to anything. They pick up whatever value was left on the stack or in the register that they are assigned.
I believe that your program is crashing because n in int v[n] is a ridiculously big number and v is trying to use too much memory.
You can probably fix this by moving your array declaration below the scanf that reads in n.
You need to pass v, not v[n] to the function selection_sort. v is the array, v[n] is actually an out of bounds element of v.
the line should be selection_sort(n, v);
I've been working on a project euler problem, which by their very nature coerce you to use data types with big storage.
#include <stdio.h>
#include <conio.h>
#define num 600851475143
int main()
{
long long i, j, count=0, number=num, k;
for(i=2;number!=1;i++)
{
count=0;
for(j=1;j<=i;j++)
{
if((i%j)==0)
{
count++;
}
}
for(k=0;k<100000000;k++)
{}
if(count==2)
{
printf(" %d\n", i);
if(number%i==0)
{
number/=i;
printf(" %d\n", number);
printf("%d\n", i);
i=2;
}
}
}
getch();
return 0;
}
When I compile and run the program, there is nothing printed for number. I have tried various printf conversions %ll, %l, I have changed data types. I am using GNU GCC compiler. What should I do?
You should (re)read the documentation, I guess.
%ll didn't work since ll is not a complete specifier, it's just a modifier for the actual conversion specifier, which should follow.
Try %lld.
The correct format for printf is %lld. Moreover you should use a prefix for your constant num, because this integer constant is too large to be hold in long type.
#define num 600851475143LL
Perhaps should you avoid lower-case macro's identifiers?