program doesn't read a file properly - c

For homework I have to write a program where I am typing the string of n integer and then the program that prints the string,calculates the arithmetic mean and makes a new file only with even numbers and at the end prints the new file on screen.
And here are 2 programs
#include<stdio.h>
main()
{
int x,n,i;
FILE *p;
p=fopen("podaci.dat","wb");
printf("n=");
scanf("%d",&n);
fwrite(&n,sizeof(int),1,p);
for(i=0;i<n;i++)
{
printf("x=");
scanf("%d",&x);
fwrite(&x,sizeof(int),1,p);
}
fclose(p);
}
#include<stdio.h>
void stampa(int n,int a[])
{
int i;
for(i=0;i<n;i++)
printf("%5d",a[i]);
printf("\n");
}
float ars(int n,int a[])
{
int i,s=0;
float ars=0;
for(i=0;i<n;i++)
s+=a[i];
return 1.0*s/n;
}
main()
{
int i,n;
FILE *p,*u;
u=fopen("niz.dat","wb");
p=fopen("podaci.dat","rb");
fread(&n,sizeof(int),1,p);
printf("n=%d\n",n);
int a[n],m=0;
for(i=0;i<n;i++)
{
fread(&a[i],sizeof(int),1,p);
if(a[i]%2==0)
{
m+=1;
}
fwrite(&m,sizeof(int),1,u);
for(i=0;i<n;i++)
if(a[i]%2==0)
{
fwrite(&a[i],sizeof(int),1,u);
}
stampa(n,a);
printf("ars=%.2f",ars(n,a));
fclose(p);
fclose(u);
}
}
When I type more than 2 numbers the program instead of those numbers reads them as 0 and sometimes it adds numbers.

You cannot declare an array a[n] where n is a variable (number that you don't know at compile time but only once you read the file).
You can ether declare a[N] where N is a number big enough defined in with #DEFINE
#include <stdio.h>
#include ...
#DEFINE N 10000
//...
int a[N];
or you have to allocate a[] dynamically
int * a;
a = (int*)malloc(sizeof(int)*n);
You can read more about this here and here

Related

C programming parameters

#include <stdio.h>
void getScores(int a, char n[10][15], int s[10]) {
int score;
printf("Enter the number of students: ");
scanf("%d",&a);
for (int i=0; i < a;i++)
{
scanf("%s",n[i]);
scanf("%d",&score);
s[i]=score;
}
}
void printScores(int a, char n[10][15], int s[10] ) {
for (int i=0; i < a;i++)
{
printf("%s", n[a]);
printf(" ");
printf("%d\n",s[a]);
}
}
int main() {
char names[10][15];
int scores[10];
int num;
getScores(num,names,scores);
printScores(num,names,scores);
}
What I am trying to accomplish is have the parameter value of int a from the getScores function to be used in the printScores function as an array length as it is being used in getScores.
The arrays are saving its value when used in the print function but the a value is resetting to an unassigned number 896 when I need it to be what the user enters in the get function. Any tips?
Print scores will not print anything.
void getScores(int *a,
And the call
getScores(&num
You need also change accordingly the functions code

Identify an Armstrong number

I Wrote this code which can identify whether a number is a Armstrong number or not
#include <stdio.h>
#include <stdlib.h>
int n;
const int input()
{
printf("insert n:");
scanf("%d",&n);
return n;
}
int Num_amount()
{
int amount=0;
while(n>=10)
{
amount++;
n=n/10;
if(n<10)
amount++;
}
return amount;
}
int Armstrong()
{
n=input();
int v;
int z=0;
int y=10
int x=Num_amount();
int m[100]={};
int i;
for(i=0;n>=10;i++)
{
v=n%10;
m[i]=pow(v,x);
z=z+m[i];
y=y*10;
}
return z;
}
int main()
{
int z=Armstrong();
printf("%d",z);
}
When run with n=153 i always get 0.After several debugging,I found out the problem is somewhere in the Armstrong function(most likely)
int Armstrong()
{
n=input();
int v;
int z=0;
int y=10
int x=Num_amount();
int m[100]={};
int i;
for(i=0;n>=10;i++)
{
v=n%10;
m[i]=pow(v,x);
z=z+m[i];
y=y*10;
}
return z;
}
The debug watches indicate that instead of execute the for loop,it went straight to the return z line,I have tried everything but still can't figure it out.Can you tell me what the problem is?
You are getting the wrong result because of some logical error. When you are choosing a variable to be global, you need to consider that the variable value can be modified by any function and in this case, you have already modified its value in num_amount function. You have also made some logical error in Num_amount and Armstrong function.
You haven't included math.h header file for pow.
Here is your modified code,
#include <stdio.h>
#include <stdlib.h>
#include<math.h> //<-------------Should have included
int n;
const int input()
{
printf("insert n:");
scanf("%d",&n);
return n;
}
int Num_amount() //<------------modified
{
int z = n; //<--------take a copy of global n
int amount=0;
while(z>0)
{
amount++;
z=z/10;
}
return amount;
}
int Armstrong() //<------------modified
{
n=input();
int v;
int z=0;
int x=Num_amount();
int i;
while(n>0)
{
v=n%10;
z+=pow(v,x);
n/=10; //<-------modification of global n
}
return z;
}
int main()
{
int z=Armstrong();
printf("%d",z);
}
Found a lot problems with the code. Here is a modified version.
1. Do not use a global variable.
2. Make calculation for power easier.
3. Return the status of result, not the result. You want to check whether number is Armstrong or not.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int no_digits(int n){
int digits = 0;
while(n){
digits++;
n = n/10;
}
return digits;
}
int armstrong(){
int n;
printf("insert n:");
scanf("%d",&n);
int digits = no_digits(n);
int curnum = 0,original = n;
while(n){
curnum += pow(n%10,digits);
n /= 10;
}
if(original == curnum)
return 1;
return 0;
}
int main(){
if(armstrong())
printf("Is Armstrong\n");
else printf("Not Armstrong\n");
}
Let's take a look at your loop:
for(i=0;n>=10;i++)
{
v=n%10;
m[i]=pow(v,x);
z=z+m[i];
y=y*10;
}
What's the value of n at this point? You've set it in the previous call to Num_amount like so:
while(n>=10)
{
amount++;
n=n/10;
if(n<10)
amount++;
}
So, after Num_amount has finished executing, n must be less than 10, meaning the loop in Armstrong won't execute.
This is a big reason why you shouldn't use globals, even in a toy program like this. If you use it for different purposes in different places, you just create headaches like this.
At the very least, you should change your code such that n is passed as a parameter to Num_amount and Armstrong.
Your function Num_amount() return "n" value is already less than 10 and for loop never run.

How to read a bidimensional array inside a function?

i have this code how to read the bidimensional array using a function?
i write this function it works read all the numbers but when i output to console the array there are not the values that i entered
ex
Input:
2 1 2 3 4
Output:
16 256
1 4525376
#include <stdio.h>
#include <stdlib.h>
void citMat(int a, int n) {
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf("a[%d][%d]",i,j);
scanf("%d", &a);
}
}
int main()
{ int i,j;
int a[10][10],n;
printf("Introdu n:");
scanf("%d", &n);
citMat(a[10][10],n);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
You need to change the prototype to (Here array dimension is important)
void citMat(int a[10][10], int n)
Other changes are explained by others (The whole code is below)
#include <stdio.h>
#include <stdlib.h>
void citMat(int a[10][10], int n) {
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("a[%d][%d]:",i,j);
fflush(stdout);
scanf("%d", &a[i][j]);
}
}
int main()
{ int i,j;
int a[10][10],n;
printf("Introdu n:");
scanf("%d", &n);
if (n > 10)
{
fprintf(stderr, "Invalid input %d\n", n);
return 1;
}
citMat(a,n);
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
1. If you want to pass a 2-d array to function .Change your function definition to -
void citMat(int a[10][10], int n) { // first parameter to take a 2-d int array
2. And then inside function citMat to take input-
scanf("%d", &a[i][j]); // you need to write like this
Note -
1. Array indexing starts from 0 , so if you have array a[n] then it have valid index from 0 to n-1 .
So start reading from 0 and till n in all for loops . If you include n then you would access index out of bound and writing to it will cause undefined behaviour.
So, look out for that .
2. int main() -> int main(void) or int main(int argc,char **argv)
You need to change few things in your program to make it work
1) Call the function with the base address of the array, lik
citMat(a,n);
2) Change your function definition to,
void citMat(int a[10][10], int n)
to make it accept 2D array as parameter.
3) Change the scanf() to read for each element,
scanf("%d", &a[i][j]);
4) Since the array index starts from 0, change all the for loops termination condition to
for(i=1;i<n;i++)

Can't find error in my c code

can't find an error please help, this is a C code to find minimum number of possible quadrangles on co-ordinate plane
#include <stdio.h>
int quadrangle(int *,int);
int min(int,int);
int main(){
int t,i,j,n,p[n][n];
printf("\nEnter the number of test cases");
scanf("%d",&t);
for(i=0;i<t;i++){
scanf("%d",&n);
for(j=0;j<n;j++){
scanf("%d %d",&p[j][0],&p[j][1]);
}
printf("%d",quadrangle(&p[0][0],n));
}
return 0;
}
int quadrangle(int *p,int len){
int f=0,s=0,t=0,fo=0,i;
for(i=0;i<len;i++){
if(*(p+i*len)>0&&*(p+i*len+1)>0)
f++;
if(*(p+i*len)>0&&*(p+i*len+1)<0)
s++;
if(*(p+i*len)<0&&*(p+i*len+1)<0)
t++;
if(*(p+i*len)<0&&*(p+i*len+1)>0)
fo++;
}
return min(min(f,s),min(t,fo));
}
int min(int a,int b){
if(a>b) return b;
else return a;}
I tested it on codeblocks software it is compiling okay but ends abruptly when I execute it . The control doesn't even enter main() .
n is uninitialized and you create an array of size n (guess what's the value of n) here:
int t,i,j,n,p[n][n];
Declare the array after n gets initialized, i.e, change
int t,i,j,n,p[n][n];
to
int t,i,j,n;
and add
int p[n][n];
after
scanf("%d",&n);

C program keeps crashing

My program keeps crashing. The codes seems legit and correct. Wonder what's the problem.
#include <stdio.h>
void queue(int length,int turns){
int permutations,totalTurns;
turns++;
if (length>0){
queue(length-1,turns);
if (length>1){
queue(length-2,turns);
}
}
else{
permutations++;
totalTurns+=turns;
}
}
int main()
{
while(true){
int length;
float average;
int permutations=0;
int totalTurns=0;
printf("Queue length: ");
scanf("%d", &length);
queue(length,-1);
average=totalTurns/permutations;
printf("The average turns are %f", average);
}
}
int permutations=0;
average=totalTurns/permutations;
You're dividing by zero.
Note that the permutations variable you've declared in main() is different from the one in queue().
You should probably return the permutations value from queue(), like this:
int queue(int length,int turns){
int permutations = 0;
...
return permutations;
}
int main(void) {
...
int permutations = queue(length,-1);
}
You should declare permutations as a global variable, i.e. outside main function as well as totalTurns because as others mentioned it's always 0 because even thought you declare it in function queue it's being forgotten outside it.
#include <stdio.h>
static int permutations=0;
static int totalTurns=0;
void queue(int length,int turns){
turns++;
if (length>0){
queue(length-1,turns);
if (length>1){
queue(length-2,turns);
}
}
else{
permutations++;
totalTurns+=turns;
}
}
int main()
{
while(true){
int length;
float average;
int totalTurns=0;
printf("Queue length: ");
scanf("%d", &length);
queue(length,-1);
average=totalTurns/permutations;
printf("The average turns are %f", average);
}
}

Resources