Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've got a problem. I've tried to write program. This is command:
The user specifies a whole number n>0.
Program:
Allocates two arrays of numbers of type int size n+1
Using only these arrays and a small number of statically allocated variables, the program calculates recursively the n line of the Pascal triangle (all binomial symbols with an upper parameter equal to n)
Prints out the calculated values
Memory slowing down
Example
input: 5
output: 1 5 10 10 5 1
I wrote iteration, but I have no idea how change this for recursion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,k;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0') printf("%d", 1);
if(n=='1') printf("%d %d", 1, 1);
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = 1;
array_1[1] = 1;
k=1;
while(k!=n)
{
for(i=0; i<=k+1; i++)
{
if(i==0)
{
array_2[0] = 1;
}
else if(i==n)
{
array_2[i] = 1;
}
else
{
array_2[i] = array_1[i] + array_1[i-1];
}
}
for(i=0; i<=n; i++)
{
array_1[i] = array_2[i];
array_2[i] = 0;
}
k++;
}
for(i=0; i<=n; i++)
{
printf("%d ", array_1[i]);
}
free(array_1);
free(array_2);
return 0;
}
The recursive version could look something like the following, with the actual work being left to fill-in under the two /* ... */ comments. The missing code essentially exists in the iterative version as posted, it just needs to be retrofitted here.
void recurse(int k, int n, int *array_1, int *array_2)
{
/*
print previously calculated k-th row in array_1
*/
// nothing left to do
if (k == n + 1) return;
/*
calculate next (k+1)-th row in array_2
*/
// swap arrays and repeat
recurse(k + 1, n, array_2, array_1);
}
int main()
{
int n, *array_1, *array_2;
if(scanf("%d", &n) != 1) return 1; // input error
if (n < 0) return 1; // invalid input
array_1 = (int*)calloc(n + 1, sizeof(int));
array_2 = (int*)calloc(n + 1, sizeof(int));
array_1[0] = 1;
recurse(1, n, array_1, array_2);
free(array_1);
free(array_2);
return 0; // done
}
Thanks everyone for answer :). This is my code:
#include <stdio.h>
#include <stdlib.h>
void recurse (int k, int n, int *array_1, int *array_2)
{
int i;
if(k==n+1) return;
for(i=1; i<=k+1; i++) array_2[i] = array_1[i] + array_1[i-1];
recurse(k+1, n, array_2, array_1);
}
void output(int n, int *array_1, int *array_2)
{
int i;
if(n%2!=0)
for(i=0; i<=n; i++) printf("%d ", array_1[i]);
else
for(i=0; i<=n; i++) printf("%d ", array_2[i]);
}
int main()
{
int n;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0')
{
printf("%d", 1);
return 0;
}
else if(n=='1')
{
printf("%d %d", 1, 1);
return 0;
}
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = array_1[1] = array_2[0] = 1;
recurse(1, n, array_1, array_2);
output(n, array_1, array_2);
free(array_1);
free(array_2);
return 0;
}
Related
So I'm very new to programming and the C language, and I would like to find the simplest, fastest, and most efficient way to count all the distinct elements of a 1D array. This was actually for a school assignment, but I've been stuck on this problem for days, since my program was apparently too slow for the online judge and it got a TLE. I've used regular arrays and dynamically allocated arrays using malloc, but neither worked.
Anyways, here's the latest code of it(using malloc):
#include <stdio.h>
#include <stdlib.h>
int distinct(int *arr, int N){
int j, k, count = 1;
for(j = 1; j < N; j++){
for(k = 0; k < j; k++){
if(arr[j] == arr[k]){
break;
}
}
if(j == k){
count++;
}
}
return count;
}
int main(){
int T, N, i = 0;
scanf("%d", &T);
do{
scanf("%d", &N);
int *arr;
arr = (int*)malloc(N * sizeof(int));
for(int j = 0; j < N; j++){
scanf("%d", &arr[j]);
}
int count = distinct(arr, N);
printf("Case #%d: %d\n", i + 1, count);
i++;
}while(i < T);
return 0;
}
The most efficient way depends on too many unknown factors. One way is to sort the array and then to count distinct elements in there, skipping the duplicates as you go. If you have sorted the array and gotten this:
1 1 1 1 2 2 2 2 3 3
^ ^ ^
+-skip--+-skip--+-- end
... you can easily see that there are 3 distinct values in there.
If you don't have a favourite sorting algorithm handy, you could use the built-in qsort function:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Example:
#include <stdio.h>
#include <stdlib.h>
int compar(const void *l, const void *r) {
const int* lhs = l;
const int* rhs = r;
if(*lhs < *rhs) return -1; // left side is less than right side: -1
if(*lhs > *rhs) return 1; // left side is greater than right side: 1
return 0; // they are equal: 0
}
int distinct(int arr[], int N){
// sort the numbers
qsort(arr, N, sizeof *arr, compar);
int count = 0;
for(int i=0; i < N; ++count) {
int curr = arr[i];
// skip all numbers equal to curr as shown in the graph above:
for(++i; i < N; ++i) {
if(arr[i] != curr) break;
}
}
return count;
}
int main() {
int T, N, i = 0;
if(scanf("%d", &T) != 1) return 1; // check for errors
while(T-- > 0) {
if(scanf("%d", &N) != 1) return 1;
int *arr = malloc(N * sizeof *arr);
if(arr == NULL) return 1; // check for errors
for(int j = 0; j < N; j++){
if(scanf("%d", &arr[j]) != 1) return 1;
}
int count = distinct(arr, N);
free(arr); // free after use
printf("Case #%d: %d\n", ++i, count);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
in visuals studio i try to make respectively sum of rows. but first sum multiplied by 4 . i didnt understand this situation
get_sum(int **q, int p, int n);
int main(void)
{
int num[3][5] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 };
get_sum(&num[0][0], 3, 5);
}
get_sum(int **q, int p, int n)
{
/*for (int i = 0; i < ; i++)
printf("%d\n", *(q + i));*/
for (int k = 0; k < p; k++)
{
int sum = 0;
for (int i = 0; i < n; i++)
{
sum =*(q + n*k + i)+sum;
printf("%d\n", sum);
}
}
}
If I understand you simply want to create a function that sums the elements of the array passed as a parameter, along with the dimensions of the array, then you have the right idea, but woefully wrong syntax.
Rather than verbally discussing each change, the simple example contains all the changes. Look over the changes and why they were made:
#include <stdio.h>
int get_sum (int (*q)[5], int p, int n);
int main (void)
{
int num[3][5] = {{ 10, 11, 12, 13, 14 },
{ 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24 }};
int sum = get_sum (num, 3, 5);
printf (" -----------\n sum : %d\n", sum);
return 0;
}
int get_sum (int (*q)[5], int p, int n)
{
int sum = 0;
for (int k = 0; k < p; k++) {
for (int i = 0; i < n; i++)
sum += q[k][i];
printf ("row[%2d] : %d\n", k, sum);
}
return sum;
}
(note: the loop output within get_sum provides are running-total of the sum after the addition of each row elements. You can tailor this to meet your needs.)
Example Use/Output
$ ./bin/get_sum
row[ 0] : 60
row[ 1] : 145
row[ 2] : 255
-----------
sum : 255
Let me know if you have any questions.
You are indexing a 1-D array as if it is a 2-D array, but there is no need to define it as 2-D, and anyway, you initialise it as if it were a 1-D array.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 }; // 1-D linear array
get_sum(num, 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
Program output
60
85
110
Alternatively if you do want a 2-D array and then index into it as if it were a 1-D array, you can do this. Note I have initialised the array differently but get_sum is the same.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[3][5] = {{10,11,12,13,14}, {15,16,17,18,19}, {20,21,22,23,24}};
get_sum(&num[0][0], 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I need to write a program that scans in a 2D array and then finds the minimum value in each row by using a function.
The prototype int RowMin(int *prow, int ncols) was given in the instructions. My problem is that I don't know for sure how to use the pointer. This was my best guess and it's not correct. The program crashes after I enter in the values of the array.
This is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int RowMin(int *prow, int c);
int main()
{
int a[MAX][MAX];
int r, c, min;
int i = 0, j = 0;
printf("Enter number of rows & columns of array:\n");
scanf("%d %d", &r, &c);
printf("\nEnter elements of 2-D array:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d", &a[i][j]);
}
}
for(i=0;i<r;i++)
{
min = RowMin(i, c);
printf("The min in row %d is %d",i, min);
}
return 0;
}
int RowMin(int *prow, int ncols)
{
int temp, i;
int a[*prow][ncols]; //this is where it is messing up
temp = a[*prow][0];
for(i=0; i<ncols; i++)
{
printf("Good5");
if(temp > a[*prow][i])
{
temp = a[*prow][i];
}
}
return temp;
}
Pass the address of the each row:
min = RowMin(a[i], c);
Then do this in your routine in order to find min in each row
int RowMin(int *prow, int ncols)
{
int min=prow[0], i;
for(i=0; i<ncols; i++)
{
if(min > prow[i])
{
min = prow[i];
}
}
return min;
}
The function call should look like this
min = RowMin(&a[i],c)
You should pass the address of each row.
The function should be modified like this
int minRow(int *ptr, int columns)
{
//ptr has the address of each row
int minElt = ptr[0]; //Contains the first Element
for(int i = 0; i < columns; ++i)
{
if( minElt > ptr[0] )
minElt = ptr[0]
}
return minElt;
}
In this loop
for(i=0;i<r;i++)
{
min = RowMin(i, c);
printf("The min in row %d is %d",i, min);
}
you have to pass a row of the array to the function. So the call will look like
min = RowMin( a[i], c );
Take into account that you should check that entered values of rows and columns are not greater than MAX. Or if your compiler supports variable length arrays you could use a variable length array when its sizes are set by entered values of r and c.
The function itself is also invalid. It can be written the following way
int RowMin( const int *prow, int ncols )
{
int i = 0;
int min = prow[i];
while ( ++i < ncols )
{
if ( prow[i] < min )
{
min = prow[i];
}
}
return min;
}
Correspondingly the function have to be declared like
int RowMin( const int *prow, int c );
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I wrote a shell sorting algorithm which works perfectly on integer values, but gives me segmentation fault when trying to sort float numbers. Could you help me with this ? Thank you.
We have a homework at the university and my teacher wrote this program with insert sort and it worked. The homework for us was to rewrite it to shell sort (which I think I did correctly) and maybe expand it further more to sort strings and numbers from files.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int int_cmp(const void *p1, const void *p2){
return *(int*)p1 - *(int*)p2;
}
int float_cmp(const void *p1, const void *p2){
if (*(float*)p1 == *(float*)p2){
return 0;
}
else if (*(float*)p1 < *(float*)p2){
return -1;
}
else {
return 1;
}
}
void shell_sort(void *v, int nr, int size, int(*p_cmp)(const void*, const void*)){
int i, j;
void *pv, *pi, *pj;
pv = malloc(size); //this is where I get segmentation fault
for (int gap = nr/2; gap > 0; gap/=2){
for (i = gap; i < nr; ++i){
for (j = i-gap; j >= 0; j-=gap){
pi = v;
pi = (char*)pi+j*size;
pj = (char*)pi+gap*size;
if (p_cmp(pi, pj) > 0){
memcpy(pv, pi, size);
memcpy(pi, pj, size);
memcpy(pj, pv, size);
}
else {
break;
}
}
}
free(pv);
}
}
int main(){
int a[20], n = 20;
float b[25], m = 25;
srand(time(NULL));
printf("Original integer array: ");
for (int i = 0; i < 20; ++i){
a[i] = rand() % 100;
printf("%i ", a[i]);
}
printf("Original float array: ");
for (int j = 0; j < 25; ++j){
b[j] = (float)rand()/(float)(RAND_MAX)*50;
printf("%f ", b[j]);
}
shell_sort(a, n, sizeof(int), int_cmp);
shell_sort(b, m, sizeof(float), float_cmp);
printf("\nInteger array after sort: ");
for (int i = 0; i < 20; ++i){
printf("%i ", a[i]);
}
printf("\nFloat array after sort: ");
for (int j = 0; j < 25; ++j){
printf("%f ", b[j]);
}
return 0;
}
free(pv); move to outside for-loop(after loop).
I have to display the following figure (The two triangles intercept) for a n given by the user, where n is odd. The figure is in this link: http://i.imgur.com/mQxarLz.jpg
*******
*****
***
*
*
***
*****
*******
I already wrote this code, but I don't know how to give the n, where n is odd. And my code doesn't compile; it says: "In the fifth row, syntax error before for".
#include <stdio.h>
int main (void) {
int n,i,k,m;
for(m=0;m<2;m++)
for (i=1;i<=n;i++){
if(m==0){
for(k = 1; k<=n-i; k++){
printf(" ");
}
}
}
for (k=1;k<2*i;k++){
printf("%s","*");
//printf("%d",i);
}
scanf("%d",&n);
for (k = 1; k<=i;k++)
for (k=1;k<(n-i)*2;k++)
for (i=1;i<=n;i++) {
printf("\n$");
}
return 0;
}
First, the answer to "how do I check whether an integer is odd": you simply divide by 2 and check if the remainder is 0 (even) or 1 (odd). In C and most related languages, this is what the modulo operator "%" does:
if ((n % 2) == 1) {
// The number is odd.
}
But you should make sure that you read your n right at the start, because in the code that you have submitted, n is read in your second "for" loop before you have actually written something to it. And that means, n contains garbage at that point.
Good programming is to solve problems in the most simple way you can find. This particular algorithm is really fundamental stuff, thus you shouldn't end up with anything much more complicated than this:
#include <stdio.h>
#include <stdbool.h>
void print_chars (char symbol, int n)
{
for(int i=0; i<n; i++)
{
printf("%c", symbol);
}
}
void print_triangle (int base_size, int height, bool pointing_up)
{
int star_count = pointing_up ? 1 : base_size;
for(int row = 0; row < height; row++)
{
int spaces = base_size - star_count;
print_chars (' ', spaces/2);
print_chars ('*', star_count);
print_chars (' ', spaces/2);
printf("%\n");
star_count += pointing_up ? 2 : -2;
}
}
int main (void)
{
print_triangle(7, 4, false);
print_triangle(7, 4, true);
}
Note that the above code will behave strange if the triangle's base isn't in sync with its height - I left that out intentionally, feel free to improve the program further with such.
#include <stdio.h>
void printAsterisk(int n, int length){
int i, slen = (length - n)/2;
for(i=0;i < slen;++i)
putchar(' ');
for(i=0;i < n;++i)
putchar('*');
putchar('\n');
}
/* non-recursive
void printTriangle(int n, int length){//n isn't required as an argument
int d= -2;
for(; n < length + 1; n += d){
if(n < 0) n += (d *= -1);
printAsterisk(n, length);
}
}
*/
void printTriangle(int n, int length){
if(n < 1) return;
printAsterisk(n, length);
printTriangle(n - 2, length);
printAsterisk(n, length);
}
int main(void){
int n;
do{
printf("input odd number:");
scanf("%d", &n);
}while(n % 2 == 0);
printTriangle(n, n);
return 0;
}