Ok so my main goal is to multiply two matrices.Before jumping there i proposed myself to write 2 functions to read and display a matrix. Basic stuff i thought.
After i run the program and i enter the number of lines and columns,i can only enter 1 value before it crashes.
I use Dev c++.
What could the issue be here? Thank you in advance.
#include <stdio.h>
#define MAXSIZE 20
void readM(int M[MAXSIZE][MAXSIZE],int,int);
void printM(int M[MAXSIZE][MAXSIZE],int,int);
int main ()
{
int NL,NC,i,j;
int M[20][20];
readM(M[20][20],NL,NC);
printM(M[20][20],NL,NC);
return 0;
}
void readM(int M[20][20],int NL,int NC)
{
int i,j;
printf("Type in number lines ");
scanf("%d",&NL);
printf("Type in number of columns ");
scanf("%d",&NC);
printf("Type in values \n");
for(i=0;i<NL;i++)
{
for(j=0;j<NC;j++)
{
scanf("%d",&M[i][j]);
}
}
}
void printM(int M[20][20],int NL,int NC)
{
int i,j;
printf("Matrix is \n");
for(i=0;i<NL;i++)
{
for(j=0;j<NC;j++)
{
printf("\t%d\t",M[i][j]);
}
printf("\n");
}
}
First, when you call readM and printM, you should call them using M, not M[20][20].
Then, there's the lines and columns problem. When you pass the arguments NL and NC to readM, you're passing a copy of their values inside main. When you read the values in readM you'll store what you read locally, and main will never know about it.
To change that, you could use pointers or you could read the lines and columns in main, leaving readM with the sole purpose of reading matrix itens.
The program may be skipping your input because there's trash in the input buffer. The best way of getting user input is creating a custom function that reads whatever there is in stdin, and then treat it accordingly. Because you never know what users will input...
Here's the code with my suggestions:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
void readM(int M[MAXSIZE][MAXSIZE], int, int);
void printM(int M[MAXSIZE][MAXSIZE], int, int);
/* very simple function to treat user input */
int read_num(void)
{
char buf[50];
fgets(buf, 50, stdin);
return atoi(buf);
}
/* if main() won't take any arguments, use void */
int main(void)
{
int NL, NC, i, j;
int M[20][20];
/* extracted from readM */
printf("Type in number lines ");
NL = read_num();
printf("Type in number of columns ");
NC = read_num();
readM(M, NL, NC);
printM(M, NL, NC);
return 0;
}
void readM(int M[MAXSIZE][MAXSIZE], int NL, int NC)
{
int i, j;
printf("Type in values \n");
for (i = 0; i < NL; i++) {
for (j = 0; j < NC; j++) {
M[i][j] = read_num();
}
}
}
void printM(int M[MAXSIZE][MAXSIZE], int NL, int NC)
{
int i, j;
printf("Matrix is \n");
for (i = 0; i < NL; i++) {
for (j = 0; j < NC; j++) {
printf("\t%d\t", M[i][j]);
}
printf("\n");
}
}
Related
I have just started learning how to program and I came across an assignment whereby I have to create an array wherein the weight of the elephant seals is read & printed. Can someone please tell me what's wrong with my code, because I can read in the data but my data is being printed wrong when I call the printArray function.
Below is my code:
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
void arrayReadingData(const int sizeP) //array to read in the weight of the elephantseals
{
int weightP[sizeP];
for(int i = 1; i <= sizeP; i++)
{
printf("Elephant seal %d weight is: ", i);
scanf("%d", &weightP[i]);
}
}
void printArray(const int sizeP)
{
int weightP[sizeP];
for(int i = 1; i <= sizeP; i++)
{
printf("%d\t", weightP[i]);
}
}
int main(void)
{
int size;
printf("How many seals do you want to calculate the average weight for: ");
scanf("%d", &size);
arrayReadingData(size);
printArray(size);
};
You are doing the for loop wrong, your loop should start at i = 0 to i < sizeP, when i = sizeP weights[sizeP] will be assigned an arbitrary value.
Update:
I just noticed you are declaring the array as a local variable to each function and declaring it the wrong way, you should declare that array in the main function and pass it to your functions instead
Here is a solution you can use
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
#define SIZE 3
void arrayReadingData(int weightP[]) //array to read in the weight of the elephantseals
{
for(int i = 0; i < SIZE; i++)
{
printf("Elephant seal %d weight is: ", i);
scanf("%d", &weightP[i]);
}
}
void printArray(int weightP[])
{
for(int i = 0; i < SIZE; i++)
{
printf("%d\t", weightP[i]);
}
}
int main(void)
{
int weights[SIZE];
arrayReadingData(weights);
printArray(weights);
};
Note: if you want the size to be given by the user you can use pointers and allocate memory dynamically
Here is how you can achieve that:
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
#include <stdlib.h>
void arrayReadingData(int weightP[], int size) //array to read in the weight of the elephantseals
{
for(int i = 0; i < size; i++)
{
printf("Elephant seal %d weight is: \n", i);
scanf("%d", &weightP[i]);
}
}
void printArray(int weightP[], int size)
{
for(int i = 0; i < size; i++)
{
printf("%d\t", weightP[i]);
}
}
int main(void)
{
int* weightsArray;
int size;
printf("Enter the size of the array:\n");
scanf("%d", &size);
weightsArray = (int*)malloc(size*sizeof(int));
if(weightsArray == NULL){
printf("couldn't allocate memory");
exit(1);
}
arrayReadingData(weightsArray, size);
printArray(weightsArray, size);
free(weightsArray);
};
I redid the code, after learning from the comments and I came up with this solution, the problem is that now I can only read in 10 numbers and print 10 numbers if I read in 11 numbers and try to print it I get an error stating zsh: segmentation fault
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
void arrayReadingData(const int sizeP, int weightP[]) //array to read in the weight of the elephant seals
{
for(int i = 0; i < sizeP; i++)
{
printf("Elephant seal %d weight is: ", i);
scanf("%d", &weightP[i]);
}
}
void printArray(const int sizeP, int weightP[])
{
for(int i = 0; i < sizeP; i++)
{
printf("%d\n", weightP[i]);
}
}
int main(void)
{
int size;
int weight[size];
printf("How many seals do you want to calculate theaverage weightfor:");
scanf("%d", &size);
arrayReadingData(size, weight);
printArray(size, weight);
}
In the below code, I am saving and printing two vectors. This means I have created each function —scanf() and printf()— twice even though they are the same apart from the vector name they operate. How could I have only one scanf() and printf() functions, and still save and print as many vectors as I want? N.b. In this case, I am only working with static vectors.
#include <stdio.h>
int scanning_first_vector(int *vector1);
int printing_first_vector(int *vector1);
int scanning_first_vector(int *vector2);
int printing_first_vector(int *vector2);
int main()
{
int vector1[5], vector2[5];
printf("Please enter the first vector.\n");
scanning_first_vector(vector1);
printing_first_vector(vector1);
printf("\nPlease enter the second vector.\n");
scanning_first_vector(vector2);
printing_first_vector(vector2);
return 0;
}
int scanning_first_vector(int *vector1)
{
int i;
for (i = 0; i < 5; ++i)
{
scanf("%d", &vector1[i]);
}
return 0;
}
int printing_first_vector(int *vector1)
{
int i;
for (i = 0; i < 5; ++i)
{
printf(" %d ", vector1[i]);
}
return 0;
}
int scanning_second_vector(int *vector2)
{
int i;
for (i = 0; i < 5; ++i)
{
scanf("%d", &vector2[i]);
}
return 0;
}
int printing_second_vector(int *vector2)
{
int i;
for (i = 0; i < 5; ++i)
{
printf(" %d \n", vector2[i]);
}
return 0;
}
I think I just did below the leaner version of the code after reading the comments — thank you, guys! :-) I understand now that I can use the same function & I only need to make sure I give distinctive names to the vectors in the main() function. It works well, but it would also be awesome to get confirmation that the way the code is done here is as lean & good as it can get :-) Thank you!
#include <stdio.h>
int scanning_vector(int *vector);
int printing_vector(int *vector);
int main()
{
int vector1[5], vector2[5];
printf("Please enter the first vector:\n");
scanning_vector(vector1);
printing_vector(vector1);
printf("\nPlease enter the second vector:\n");
scanning_vector(vector2);
printing_vector(vector2);
return 0;
}
int scanning_vector(int *vector)
{
int i;
for (i = 0; i < 5; ++i)
{
scanf("%d", &vector[i]);
}
return 0;
}
int printing_vector(int *vector)
{
int i;
for (i = 0; i < 5; ++i)
{
printf(" %d ", vector[i]);
}
return 0;
}
I am writing a program to generate all possible permutations of a given series of numbers and then generate all possible binary trees from that permutations so, what I thought is having a program which generates permutations and stores the result to a file and then write further code to read line by line (which has all permutations ) and generate binary trees out of them, so right now I have written half program which generates permutation and it stores the result in file.
#include <stdio.h>
//function to print the array
void printarray(int arr[], int size)
{
FILE *fp;
int i,j;
fp=fopen("result.txt","w");
for(i=0; i<size; i++)
{
// printf("%d\t",arr[i]);
fprintf(fp,"%d\t",arr[i]);
}
printf("\n");
fclose(fp);
}
//function to swap the variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//permutation function
void permutation(int *arr, int start, int end)
{
if(start==end)
{
printarray(arr, end+1);
return;
}
int i;
for(i=start;i<=end;i++)
{
//swapping numbers
swap((arr+i), (arr+start));
//fixing one first digit
//and calling permutation on
//the rest of the digits
permutation(arr, start+1, end);
swap((arr+i), (arr+start));
}
}
int main()
{
//taking input to the array
int size;
printf("Enter the size of array\n");
scanf("%d",&size);
int i;
int arr[size];
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
//calling permutation function
permutation(arr, 0, size-1);
return 0;
}
but the problem here in this program is that this program only stores one permutation and does not stores other permutations in result.txt file, how do I go on storing result this way. Also program does not ends a blank cursor blinking which gives a false impression of infinite while loop.
I had to press Ctrl+c to end the program how to get rid of this?
your fopen("result.txt","w"); truncates file each time opened.
use fopen("result.txt","a"); instead
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define N 10
void print(int *num, int n)
{
FILE *fp;
fp=fopen("result.txt","a");
int i;
for ( i = 0 ; i < n ; i++)
// printf("%d ", num[i]);
fprintf(fp,"%d ",num[i]);
fprintf(fp,"\n");
fclose(fp);
}
int main()
{
int num[N];
int *ptr;
int temp;
int i, n, j;
printf("\nHow many number you want to enter: ");
scanf("%d", &n);
printf("\nEnter a list of numbers to see all combinations:\n");
for (i = 0 ; i < n; i++)
scanf("%d", &num[i]);
for (j = 1; j <= n; j++) {
for (i = 0; i < n-1; i++) {
temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
print(num, n);
}
}
return 0;
}
I ask the user to input two integers, n and x. After that, I need to ask them for a value for the a variable n times. I need to create a new a variable for each value. How do I do it? I have absolutely no idea.
Also, I need to do it in one line, so the input will be, for example, 50 30 21, not
50
30
21
Thanks.
#include <stdio.h>
int main (void) {
int a, n, x;
int i = 0;
scanf ("%d%d", &n, &x);
scanf ("%d", &a); /* what should I do here? */
}
Try this:
int arr[100]; // static allocation but you can also allocate the dynamically memory
printf("Enter the number for how many time repeat scanf()\n");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
Try the below code:
#include <stdio.h>
int main (void) {
int a[100];
int n, x;
int i = 0;
scanf ("%d%d", &n, &x);//n cannot be greater than 100 in this case.
for(i = 0; i < n; i++)
{
scanf ("%d", &a[i]);
}
return 0;
}
Using dynamic memory:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int *a = NULL;
int n, x, i;
scanf("%d%d", &n, &x);
if (n <= 0) {
fprintf(stderr, "n must be > 0\n");
return 1;
}
a = malloc(n * sizeof(int));
if (a == NULL) {
fprintf(stderr, "failed to allocate memory for "
"%d integers\n", n);
return 1;
}
/* reading the user input */
for (i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
/* usage */
for (i = 0; i < n; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
printf("x = %d\n", x);
free(a);
return 0;
}
After that, I need to ask them for a value for the a variable n times.
High Level Programming Languages and even Assembly Language (Conditional/Unconditional Jump) provide Loop constructs to a programmer. In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. In C/C++, we have for, while, do while loop constructs.
So, i order to ask a user for a value for n times, you can use for loop in your program. I have given an example below:
#include <stdio.h>
#define MAX_ARR_LEN 100
int main (void)
{
int a[MAX_ARR_LEN];
int n, x;
int i = 0;
scanf ("%d%d", &n, &x);
if (n > MAX_ARR_LEN) {
printf("You can't enter more than - %d\n", MAX_ARR_LEN);
return -1;
}
for(i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
return 0;
}
When you do scanf, it takes the input until the space character, which is a delimiter. You do not need to specify anything extra for that.
If you do not need to use the value of n again, you could use this code.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int n, x, i;
scanf ("%d%d", &n, &x);
int *a = (int *) malloc (n * sizeof(int)); //This will allocate 'n' integer sized memory for 'a'
for(i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
}
I am tryin to take input from the user and store it into an array and print it out: i have 2 functions:
/* Read a vector with n elements: allocate space, read elements,
return pointer */
double *read_vector(int n){
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
vec[i] = n;
return vec;
}
and the print function is:
void print_vector(int n, double *vec){
int i;
for (i = 0; i < n; i++) {
printf("%d\n", vec[i]);
}
}
the main function is:
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n);
void print_vector(int n, double *vec);
void free_vector(double *vec);
int main(){
int n;
double *vector;
/* Vector */
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%d", &n);
printf("Enter %d reals: ", n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n,vector);
free_vector(vector);
}
when i run this, it does not let me enter any numbers, it just skips it and prints out 0's. How do i fix this?
Try the code below. You're almost certainly either not compiling with warnings, or ignoring the warnings. All warnings mean something, and to a beginner they all matter. With gcc use the -Wall option, or even -pedantic.
As halfelf pointed out, you need a scanf in your read loop but it needs to be a pointer (&vec[i]). Always return something at the end of main. Also check the return value of malloc, it could fail and return a null pointer.
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) {
printf("Enter number %i of %i: ", i + 1, n);
scanf("%lf", &vec[i]);
}
return vec;
}
void print_vector(int n, double *vec)
{
int i;
for (i = 0; i < n; i++) {
printf("%f\n", vec[i]);
}
}
void free_vector(double *vec)
{
free(vec);
}
int main()
{
int n;
double *vector;
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%i", &n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n, vector);
free_vector(vector);
return 0;
}
In the read_vector(int n) function's for loop:
for (i=0; i<n; i++)
vec[i] = n; // this should be scanf("%lf",vec+i) to read input from stdin
and notice your { and } there. If there's only one line in the loop, { and } is not necessary, OR you have to use a pair of them. The return clause must be out of the loop.
Btw, add return 0 at the end of your main function.
simple..you forgot to write scanf..!
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
scanf("%d",&vec[i]);
return vec;
}