Addition of number of polynomials without using structure - c

#include <stdio.h>
#include <stdlib.h>
int main() {
int i, j, n, m, c[20], s = 0;
int *p[100];
I ask the user to enter the number of polynomial equations to add:
printf("Enter the number of equations to add:\n");
scanf("%d", &m);
and ask the user to enter number of coefficients he is planning to use
printf("Enter the maximum coefficient size of largest equation:\n");
scanf("%d", &n);
for (j = 1; j <= m; j++) {
printf("Enter the coefficients of equation number %d:\n", j);
p[j] = (int*)malloc(n * sizeof(int));
for (i = n; i > 0; i--)
scanf("%d", p[j] + i);
printf("The equation %d becomes as follows:\n", j);
i = n;
printf("%dx^%d", *(p[j] + i), i - 1);
for (i = n - 1; i > 0; i--)
printf("+%dx^%d", *(p[j] + i), i - 1);
printf("\n");
}
the code works ok up to here but I am having problem to add polynomials
printf("On adding all equations we get:\n");
for (i = n; i > 0; i--) {
for (j = 1; j <= m; j++) {
s = s + (*(p[j] + i));
c[i] = s;
}
}
i = n;
printf("%dx^%d", c[i], i - 1);
for (i = n - 1; i > 0; i--)
printf("+%dx^%d", c[i], i - 1);
printf("\n");
return 0;
}
also I dont want to use any kind of other methods if possible... and can we multiply polynomials similarly?

If you change
for(j=1;j<=m;j++){
to
for(s=0,j=1;j<=m;j++){
your code gives correct output if dynamic memory allocated in differenet locations and garbage values are zeros.
You are allocating n*sizeof(int) memory for p[j]th pointer
p[j]=(int*)malloc(n*sizeof(int));
for(i=n;i>0;i--)
scanf("%d",p[j]+i);
That means you can access from p[j]+0 to p[j]+n-1. If read some element to p[j]+n that means you are accessing memory which doesn't belong to you.
I modified code a bit which is working fine
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,n,m,c[20] = {0},s=0;
int *p[100];
printf("Enter the number of equations to add:\n");
scanf("%d",&m);
printf("Enter the maximum coefficient size of largest equation:\n");
scanf("%d",&n);
for(j=1;j<=m;j++){
printf("Enter the coefficients of equation number %d:\n",j);
p[j]=(int*)malloc(n*sizeof(int));
for(i=n-1;i>=0;i--)
scanf("%d",p[j]+i);
printf("The equation %d becomes as follows:\n",j);
i=n-1;
printf("%dx^%d",*(p[j]+i),i);
for(i=n-2;i>=0;i--)
printf("+%dx^%d",*(p[j]+i),i);
printf("\n");
}
printf("On adding all equations we get:\n");
for(i=n-1;i>=0;i--){
for(s=0,j=1;j<=m;j++){
s=s+(*(p[j]+i));
c[i]=s;
}
}
i=n-1;
printf("%dx^%d",c[i],i);
for(i=n-2;i>=0;i--)
printf("+%dx^%d",c[i],i);
printf("\n");
return 0;
}
Note: Don't forgot to add check for scanf and malloc.

Related

Couldn't get the reason for the fault in the code

This is a program to print the smallest value and its position in an array (defined by user).
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[n];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<=n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
But upon running it, it shows following error:
Segmentation fault (core dumped)
What can be the possible reason(s) for it?
First error, as stated in one of the comments, is declaring an array of size n before even knowing how much n is.
Second mistake is for loop in your main function that goes from 0 to n, i.e. index of an array is out of bounds.
Try this:
int main() {
int n = 0, j = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for (j = 0; j < n; j++) {
printf("a[%d] = ", j + 1);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
If this solved your problem, please mark it.
First of all:
int n, j;
both uninitialized. Initialize them otherwise you will get garbage values.
int n = 0, j = 0;
What happens if n by chance (very likely) is 0 in following line?
int a[n];
You allocate 0 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will get segmentation fault in for() loop below because your loop is trying to put 10 elements where you allocated no memory at all.
What happens if uninitialized n by chance (very likely) is 2^32 * 4 bytes (ints max)?
int a[n];
You allocate 2^32 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will not get segmentation fault but you will allocate 2^32 * 4 bytes of memory for your program and you will use only 10
Second if that is not enough:
for (j = 0; j <= n; ++j)
scanf("%d", arr[n];
will access 11th element of array which is undefined behavior, and you might even get segmentation fault there. As you know arrays in C arrays are indexed from 0 to n - 1 (if n is size of array).
Third your loop inside function:
for(i=0; i<=n-1; i=i+1)
is the same as:
for(i=0; i < n; ++i)
And finally, you have a bug in your code, I believe:
if(a[i]<a[0])
should be:
if (a[i] < smallest)
because it is most likely that you would like compare other number to already smallest element not to a[0]. Here is my code
#include <stdio.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i = 0, k=0;
for(i=0; i<n; ++i) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for(j=0; j<n; ++j) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
The version above is legit for C99 and up standards. If you are using C89 and earlier compilers you are stack with fixed size as mentioned in #Saurabh's answer or preferably use malloc().
Here is malloc() version:
#include <stdio.h>
#include <stdlib.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i=0,k=0;
for(i=0; i<=n-1; i=i+1) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int *a = malloc(sizeof(int) * n);
for(j=0; j<n; j=j+1) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
Use this one:
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[100];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
Specify the size of the array anything but run the loop according to user's input.
And there is some problems in your function position_smallest. So if you want correct it then take a look at #Gox's answer.

Beginner in C - Programming arithmetic algorithm?

Here is what I'm supposed to do:
Write a program that reads a positive integer and displays the maximum positive integer n for which the sum 1^2 + 2^2 + 3^2 + ... + n^2 is less than the given number.
So far I am only able to just add the sum of all natural numbers until n:
#include <stdio.h>
int main ()
{
unsigned int n;
int sum = 0;
int i;
sum = 0;
printf("Print your number");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
sum += i;
}
printf("sum = %d", sum);
return 0;
}
Appreciate the help!
you can try this
#include <stdio.h>
int max_positive_integer(int given_number)
{
int sum = 0;
int n = 1;
while (sum < given_number) {
sum += n * n;
n++;
}
printf("sum= %d\n", sum);
return n;
}
int main ()
{
printf("Print your number:");
int n;
scanf("%d", &n);
int max_integer = max_positive_integer(n);
printf("max_integer = %d\n", max_integer);
return 0;
}
How to sum a series of squares in a loop is the easy part
sum = 0;
for (n=0; TBD; n++) {
sum += n*n;
}
printf(..., n);
The trick is when to stop given "sum ... is less than the given number."
Code could use
for (n=0; sum + n*n < given_number; n++) {
sum += n*n;
}
n--;
That works up to a point, yet seems redundant. It has a problem in that sum + i*i may overflow. Perhaps subtract i*i each time as we do not need to report the sum, just n.
for (n=0; n*n < given_number; n++) {
given_number -= n*n;
}
n--;
What it nice about this is that the compare on the right side gets smaller as n*n increases, yet n*n does not overflow. Note: n will be about the cubic root of given_number
If you want to avoid the loop, research Sum of First n Squares
As #user4581301 commented, use "%u" with unsigned.

How can I write a program that has an input of n and then calculates the sum of n numbers that the user enters?

I've written this so far:
#include<stdio.h>
int main()
{
int n = 0, i = 0, sum = 0, a = 0;
scanf("%d", &n);
while (i <= n);
{
scanf("\n%d", &a);
sum = sum + a;
i++;
}
printf("%d", sum);
}
but when I enter 8, for example, it won't allow me to add any other numbers.
What's the problem?
while (i <= n); --> while (i <= n). Drop the ;. With the;, the while() loop never ends and { scanf("\n%d", &a); ... is never entered.
Suggest using auto formatting - easy to catch problems like this.
Also, to read n values use < #BLUEPIXY
// while (i <= n)
while (i < n)
#Shabnam You can use this code
#include <stdio.h>
int main()
{
int n, sum = 0, c, value;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (c = 1; c <= n; c++)
{
scanf("%d", &value);
sum = sum + value;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}

Calculating the mean of an array

#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
int j, sum = 0;
for (j = 0; j < i; j++)
{
sum = arr[j] + sum;
}
return (float)sum/i;
}
int main()
{
int arr[100] = { NULL };
int i, n, sum = 0;
printf("How many numbers would you like to enter?");
scanf_s("%d", &n);
while (n > 100 || n < 0)
{
printf("Amount of numbers should be less than 0 and more than 100\n");
scanf_s("%d", &n);
}
for (i = 0; i < n; i++)
{
scanf_s("%d", &arr[i + 1]);
}
printf("%f", mean(i-1, arr[i]));
system("pause");
}
When I run the code it gives me a read access error. The problem is with the mean() function I created but I don't know what's wrong. Help?
When I run the code it gives me a read access error. The problem is with the mean() function
Although the mean() function produces read access error, the actual problem is here:
printf("%f", mean(i-1, arr[i]));
You are not passing an array to your function, but its element (it is one past the end of what was written, too, so even the value that you pass is undefined).
You need to pass i for the length, because your mean() treats it as an exclusive upper limit, and you also need to pass arr for the array:
printf("%f", mean(i, arr));
Indexing problem when reading the data also needs to be fixed - you need to remove + 1:
scanf_s("%d", &arr[i]);
// ^
Try this:
#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
int j, sum = 0;
for (j = 0; j < i; j++)
{
sum = arr[j] + sum;
}
return (float)sum/i;
}
int main()
{
int arr[100] = { 0 };
int i, n, sum = 0;
printf("How many numbers would you like to enter?");
scanf("%d", &n);
getchar();
while (n > 100 || n < 0)
{
printf("Amount of numbers should be more than 0 and less than 100\n");
scanf("%d", &n);
getchar();
}
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
getchar();
}
printf("%lf", mean(n, arr));
getchar();
}
Your call to the mean function was wrong. You have to pass the entire array, not just one element. Change arr[i] to arr.
Other minor modifications are what I did to make it run on my system. If it works for you otherwise, then great.

Converting 2d array C code to malloc

I made a program that adds two matrices and displays their sum with a max dimension of 100.
/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */
#include <stdio.h>
// Construct function
void construct()
{
int m, n, i, j; // Variables
int first[100][100], second[100][100], sum[100][100]; // Matrices variables
printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);
// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second[i][j]);
// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum[i][j] = first[i][j] + second[i][j];
// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum[i][j]);
printf("\n"); // Prints new line
}
return ;
}
// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}
Now I need to change it so there is no max size for each matrix.
So I need to use malloc to create my arrays.
So I cant use int A[rows][cols].
This is what I did to covert arrays to malloc. It compiles but it crashes after I entered all the integers. Need help.
/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */
#include <stdio.h>
#include <stdlib.h>
// Construct function
void construct()
{
int m, n, i, j; // Variables
int *first = NULL;
int *second = NULL;
int *sum = NULL; // Matrices variables
printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);
first = (int*)malloc(m * sizeof(int));
second = (int*)malloc(n * sizeof(int));
sum = (int*)malloc(m * n * sizeof(int));
// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first);
// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second);
// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum = *first + *second;
// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum);
printf("\n");
}
return ;
}
// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}
First of all, you don't need to use malloc. Just move the array definitions to be after you have inputted m and n:
int first[m][n];
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
and similarly for second and sum.
If the matrices might be larger than 100x100 then it might be good to use malloc to avoid the risk of a stack overflow; the way to do that is:
int (*first)[n] = malloc(m * sizeof *first);
printf("Enter Matrix A\n");
// etc.
and at the end, free(first);. No other changes are required.
In your attempt to use malloc, you didn't allocate enough space, and you didn't scanf into the space you allocated either (instead you overwrote the pointer to the allocated space).

Resources