Pascal triangle using a function - c

well I've got it how to construct the pascal triangle and the code
below is flawless but...in this code i am making the 1 to appear in
first row by creating a new for loop especially for it... is there a
way to generate pascal triangle without using an exclusive for loop
for the 1 to appear in first... any help is much appreciated :)
//pascal triangle with ncr function
#include <stdio.h>
#include <conio.h>
int ncr(int i,int j);
int main()
{
int i,j,v,n,f,s;
printf("Enter the number of rows required\n");
scanf("%d",&n);
f=n;
//this is what i am exclusively using for printing 1 in 1st row
for(;f>0;f--)
{
printf(" ");
}
printf("1\n");
//is there a way to generate the above 1 using only the below for loop
for(i=1;i<=n;i++)
{
for(s=n-i;s>0;s--)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
v=ncr(i,j);
printf("%d ",v);
}
printf("\n");
}
}
int ncr(int i,int j)
{
int k;
float ans=1;
for(;j>=1;j--)
{
ans=((ans*i)/j);
i--;
}
k=ans;
return(k);
}

If you look carefully, you'll notice that the ncr function is defined inside the main method. Move the implementation of ncr outside of main.
Also, noticed by #BLUEPIXY, your implementation of ncr has an excess ;:
int ncr(int i,int j); //<<right here
{
//...
EDIT Solution to second problem (see Pascal's Triangle on Wikipedia)
The "first" row of the triangle is actually the zeroth row. Your outer loop starts with i = 1 and therefore the "first" row contains 1C0 and 1C1. The "first" or zeroth row should actually contain only 0C0. New loop:
//notice how the i here has changed to 0
for(i=0;i<=n;i++)
{
for(s=n-i;s>0;s--)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
v=ncr(i,j);
printf("%d ",v);
}
printf("\n");
}

Related

Program to remove the duplicate elements from an array in c

I've tried to write a program that removes the duplicate values from an array. I've partly managed to do so since my program is able to remove any ONE of the numbers which are repeated TWICE in the array. So the problem is that if a number is repeated thrice only one of the number is removed, i.e. the other two is still left in the array, also if more than one number is repeated even then only the number which comes first in the array is removed. I really cannot understand what's wrong with my code and why is it unable to remove numbers that are repeated more than two times. I've already surfed through the internet regarding this issue and though I got different ways to remove the duplicate elements, I still don't know what's wrong with my code.
#include <stdio.h>
#include <stdlib.h>
int dup(int [],int);
int main()
{
int i,n,index,a[20];
printf("Enter n value \n");
scanf("%d",&n);
printf("Enter array values \n");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=0;i<n;++i)
{
index=dup(a,n);
if(index==-1)
{
printf("No duplicate elements");
break;
}
else
{
a[index]=0;
for(i=index;i<n;i++)
a[i]=a[i+1];
n-=1;
}
}
printf("Output: \n");
for(i=0;i<n;++i)
printf("%d\n",a[i]);
return (EXIT_SUCCESS);
}
int dup(int a[],int size)
{
int i,j,pos=-1;
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(a[i]==a[j])
{
pos=j;
return pos;
}
}
}
if(pos==-1)
return pos;
}
OUTPUT
Enter n value
5
Enter array values
12
24
3
12
24
Output:
12
24
3
24
It clearly fails to remove the other repeated element "24". Also if a number was repeated thrice only one of the number would be removed.
for(i=0;i<n;++i) // <-------------------------------------- for i
{
index=dup(a,n);
if(index==-1)
{
printf("No duplicate elements");
break;
}
else
{
a[index]=0;
for(i=index;i<n;i++) // <--------------------------- for i
a[i]=a[i+1];
n-=1;
}
}
You are using the same loop variable for two loops, one nested inside the other. This cannot work. Use different variables. Live demo.
The Problem seem to lie in the if condition in second loop.
for (k = j; k < size; k++) {
arr[k] = arr[k + 1];
}
Simply put this piece of code after your if condition
if(a[i]==a[j])
and it will work.
My mistake, at first glence I thought you had problem with n after running this it worked.
#include <stdio.h>
#include <stdlib.h>
int dup(int [],int);
int main()
{
int i,n,index,a[20], count;
printf("Enter n value \n");
scanf("%d",&n);
count = n;
int j;
printf("Enter array values \n");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=0;i<n;++i)
{
index=dup(a,n);
if(index==-1)
{
printf("No duplicate elements");
break;
}
else
{
a[index]=0;
for(j=index;j<n;j++)
a[j]=a[j+1];
n-=1;
}
}
printf("Output: \n");
for(i=0;i<n;++i)
printf("%d\n",a[i]);
return (EXIT_SUCCESS);
}
int dup(int a[],int size)
{
int i,j,pos=-1;
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(a[i]==a[j])
{
pos=j;
return pos;
}
}
}
if(pos==-1)
return pos;
}
OUTPUT
Enter n value
5
Enter array values
12
24
3
12
24
Output:
12
24
3
You should name your iterator variables better so you might not confuse them in nested loops, or as you do, use the same twice in a nested loop.
This skips all variables after your first removal.
and you don't have to do this
if(pos==-1)
return pos;
skip the if as it is not necessary and if at this position posis not -1then you would have no return which would be UB I think.

How to sort 2d array column wise and row wise for given columns and rows by users

guys, this is my first time in stackoverflow
I want to sort array of random numbers row wise and column wise
after this I have to search for a given key but I am stocked in
the first part.
the problem is user should choose dimension of array between (2-5000) and elements in array is between (4-25 milion) and each element can be from 0 until int MAX and number of column and row is equal to each other
I found good code but I did not understand how to change it in order to satisfy the limit of my programm I tried to #define my 2d array like this
define R 5000
define C 5000
but it is wrong
this is the code I am trying to write
#include<stdio.h>
#define R 500
#define C 500
void sort_rows(int *arr,int n)
{
int i;
for(i=1;i<n;i++)
{
int key=arr[i];
int j=i-1;
while(j>=0 && key<arr[j])
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
void sort_column(int arr[500][500],int c)
{
int key,k;
int i,j;
for(i=0;i<c;i++)
{
for(j=1;j<c;j++)
{
key=arr[j][i];
k=j-1;
while(k>=0 && arr[k][i]>key)
{
arr[k+1][i]=arr[k][i];
k--;
}
arr[k+1][i]=key;
}
}
}
int main()
{
int arr[R][C];
int r,c;
int i,j,size_row,size_column;
printf("Enter Number of rows and columns(2-5000)");
scanf("%d%d",&r,&c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
arr[i][j]=rand()%(r*c)+1;
}
printf("Original array:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
size_row=((sizeof(arr)/sizeof(arr[0][0])/(sizeof(arr[0])/sizeof(arr[0][0]))));
printf("%d",size_row);
for(i=0;i<size_row;i++)
{
sort_rows(arr[i],sizeof(arr[i])/sizeof(arr[i][0]));
}
size_column=sizeof(arr)/sizeof(arr[0]);
for(i=0;i<size_column;i++)
{
sort_column(arr,size_column);
}
printf("Sorted Array:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
any help would be great
You have declared your array with R and C that you defined with #define, but you read new values, r and c, from user and work on it.
You should define your array dimensions with the values you will use.
Also, you have passed an integer to sort_column which considered as call by value, but you should pass array pointer to be able to edit your array, and that is call by reference.
Hope that helps.
You usually can't. A 50000x50000 2D array has 50000x50000x(int size) bits.
This is (with int size equals 4 bytes) 10 GB of memory, more than your system usually allows.
The are ways to change OS limits, but it is easier in this case to make your array global.
This code has a lot of awkward lines that look either unnecessary or wrong, so I've shortened and changed it a little to make it work like intended to.
Keep in mind that these functions you got are running insertion sort, a pretty inefficient sorting algorithm (O(n^2)). The program will take A LOT of time to run with big instances. You might want to look for better algorithms, like merge sort and quick sort.
Modified algorithm:
#include <stdio.h>
#include <stdlib.h>
#define R 50000
#define C 50000
int arr[R][C];
void sort_rows(int *arr,int n)
{
int i;
for(i=1;i<n;i++)
{
int key=arr[i];
int j=i-1;
while(j>=0 && key<arr[j])
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
void sort_column(int arr[][C],int r,int c)
{
int key,k;
int i,j;
for(i=0;i<r;i++)
{
for(j=1;j<c;j++)
{
key=arr[j][i];
k=j-1;
while(k>=0 && arr[k][i]>key)
{
arr[k+1][i]=arr[k][i];
k--;
}
arr[k+1][i]=key;
}
}
}
int main()
{
int r,c;
int i,j,size_row,size_column;
printf("Enter Number of rows and columns(2-%d,2-%d)",R,C);
scanf("%d%d",&r,&c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
arr[i][j]=rand()%(r*c)+1;
}
printf("Original array:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
for(i=0;i<r;i++)
{
sort_rows(arr[i],c);
}
sort_column(arr,r,c);
printf("Sorted Array:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}

Creating a function for a random number 2D array

So, I have this code which I need to turn into a function:
int main(void) {
int i=0,seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
printf("\nSeed value is:%d\n\n",seed);
srand(seed);
int a[5][5];
int x,y;
printf("Matrix A:\n");
for(x=0;x<5;x++) {
for(y=0;y<5;y++) {
a[x][y] = rand() %51 + (-25);
printf("%d ",a[x][y]); }
printf("\n"); }
printf("\n\n");
So basically, it produces a 2D 5x5 array of random numbers. This works fine, however my next task is applying a function to this code, with the function name of:
void generate_matrices(int a[5][5])
I have tried multiple times, the closest I got to a successful code was:
#include <stdio.h>
#include <stdlib.h>
void generate_matrices(int a[5][5]);
int main(void) {
int a, seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
srand(seed);
printf("\nSeed value is:%d\n\n",seed);
generate_matrices(a);
return 0;
}
void generate_matrices(int a[5][5]) {
int y,z;
printf("Matrix A:\n");
for(y=0;y<5;y++) {
for(z=0;z<5;z++) {
a[y][z] = rand() %51 + (-25); }
printf("%d ",a[y][z]); }
printf("\n");
}
But this returns the error, "expected 'int(*)[5]' but arguement is of type 'int'.
All/any help is muchly appreciated. To be fair on my part, I have done 90% of the code. This is the only bit I need help with so that I can apply this to the rest of my code.
Cheers!
You have declared a as a single integer on this line int a, seed;
When you call the function with generate_matrices(a); you are passing a single integer instead of a pointer to an array.
Change your declaration line to int a[5][5], seed;
generate_matrices(a); will pass a pointer to the first element in your 5 * 5 array, to the function.
You should really print the results in main and not in the function, then you will know that the array has been modified and is available for use in the body of your program.
You have used unconventional placement of braces '}' and this makes it harder to see what belongs in each part of your for loops.
You have the print statements in the wrong places - as a result only part of the matrix is printed.
This is what it should be (just the results - in main):
printf("Matrix\n ");
for (y = 0; y < 5; y++) {
for (z = 0; z < 5; z++) {
printf("%d\t ", a[y][z]);
}
printf("\n");
}
If you use int a[5][5] and call the function with generate_matrices(a);
a function void generate_matrices(int a[5][5]) {...} compiles without error
#include<stdio.h>
#include<stdlib.h>
void modify(int b[5][5]);
int main()
{
srand(4562);
int i,j,arr[5][5];
modify(arr);
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",arr[i][j]=rand() %51 + (-26)); }
}
return 0;
}
void modify(int b[5][5])
{
int i,j;
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
b[i][j]; }
}
}
So this is the closest I have come to completing it. It produces the number of elements I want, also within the range I want. However its not producing the 5x5 grid I need. Where have I gone wrong?
EDIT: I'm not going for neatness at the moment, I just want to get the program working how I want it too and then i'll neaten it up.
EDIT 2: Never mind, realised what I didn't include. Its fine now. Thanks for the help.

Odd-Even Sort using cuda Programming

I'm trying to implement odd-even sort program in cuda-c language. But, whenever I give a 0 as one of the elements in the input array, the resulted array is not properly sorted.In other cases, however, it is working for other input.I don't understand what is the problem with the code.Here is my code:
#include<stdio.h>
#include<cuda.h>
#define N 5
__global__ void sort(int *c,int *count)
{
int l;
if(*count%2==0)
l=*count/2;
else
l=(*count/2)+1;
for(int i=0;i<l;i++)
{
if(threadIdx.x%2==0) //even phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
{
int temp=c[threadIdx.x];
c[threadIdx.x]=c[threadIdx.x+1];
c[threadIdx.x+1]=temp;
}
__syncthreads();
}
else //odd phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
{
int temp=c[threadIdx.x];
c[threadIdx.x]=c[threadIdx.x+1];
c[threadIdx.x+1]=temp;
}
__syncthreads();
}
}//for
}
int main()
{int a[N],b[N],n;
printf("enter size of array");
scanf("%d",&n);
print("enter the elements of array");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("ORIGINAL ARRAY : \n");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
int *c,*count;
cudaMalloc((void**)&c,sizeof(int)*N);
cudaMalloc((void**)&count,sizeof(int));
cudaMemcpy(c,&a,sizeof(int)*N,cudaMemcpyHostToDevice);
cudaMemcpy(count,&n,sizeof(int),cudaMemcpyHostToDevice);
sort<<< 1,n >>>(c,count);
cudaMemcpy(&b,c,sizeof(int)*N,cudaMemcpyDeviceToHost);
printf("\nSORTED ARRAY : \n");
for(int i=1;i<=n;i++)
{
printf("%d ",b[i]);
}
}
Your kernel code had two main errors that I could see:
On the odd phase (for even length array, or even phase for odd length array), your last thread will index out of bounds at c[threadIdx.x+1]. For example, for 4 threads, they are numbered 0,1,2,3. Thread 3 is odd, but if you access c[3+1], that is not a defined element in your array. We can fix this by restricting each phase to work on all threads but the last one.
You were using __syncthreads() inside a conditional statement that would not allow all threads to reach the barrier. This is a coding error. Read the documentation. We can fix this by adjusting what code is inside the conditional regions.
In the main code, your final printout statements were indexing incorrectly:
for(int i=1;i<=n;i++)
that should be:
for(int i=0;i<n;i++)
You also have typo here:
print("enter the elements of array");
I assume that should be printf.
The following code has the above errors fixed, and seems to run correctly for me for arrays up to length 5 (your hardcoded limit on N). Even if you increased N, I'm not sure this would work beyond the size of a warp and certainly would not work beyond the threadblock size, but hopefully you are aware of that already(if not, read the doc link about __syncthreads()).
"Fixed" code:
#include<stdio.h>
#include<cuda.h>
#define N 5
#define intswap(A,B) {int temp=A;A=B;B=temp;}
__global__ void sort(int *c,int *count)
{
int l;
if(*count%2==0)
l=*count/2;
else
l=(*count/2)+1;
for(int i=0;i<l;i++)
{
if((!(threadIdx.x&1)) && (threadIdx.x<(*count-1))) //even phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
intswap(c[threadIdx.x], c[threadIdx.x+1]);
}
__syncthreads();
if((threadIdx.x&1) && (threadIdx.x<(*count-1))) //odd phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
intswap(c[threadIdx.x], c[threadIdx.x+1]);
}
__syncthreads();
}//for
}
int main()
{int a[N],b[N],n;
printf("enter size of array");
scanf("%d",&n);
if (n > N) {printf("too large!\n"); return 1;}
printf("enter the elements of array");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("ORIGINAL ARRAY : \n");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
int *c,*count;
cudaMalloc((void**)&c,sizeof(int)*N);
cudaMalloc((void**)&count,sizeof(int));
cudaMemcpy(c,&a,sizeof(int)*N,cudaMemcpyHostToDevice);
cudaMemcpy(count,&n,sizeof(int),cudaMemcpyHostToDevice);
sort<<< 1,n >>>(c,count);
cudaMemcpy(&b,c,sizeof(int)*N,cudaMemcpyDeviceToHost);
printf("\nSORTED ARRAY : \n");
for(int i=0;i<n;i++)
{
printf("%d ",b[i]);
}
printf("\n");
}
The usual recital about proper cuda error checking belongs here.

Please help me debug my Insertion Sort Program

I can't figure out what is going wrong with it.
If input: 4,56,5,2 then output shown is: 2,4,0,1304.
If input: 27,54,43,26,2 then output shown is: 2,26,0,1304,0
If input: 34,87,54,4,34 then output shown is: 4,34,0,1304,0
Basically, only first two sorted nos are being shown in output and on other places either 1304 or 0 is showing for any set of input.
#include <conio.h>
#include <stdio.h>
void main()
{
int a[10],b[10];
int i,size,j,k;
clrscr();
printf("please tell how many nos you want to enter");
scanf("%d",&size);
printf("Enter the nos");
for (i=0;i<size;i++) scanf("%d",&a[i]);
b[0]=a[0];
//insertionSort algo ---->
for (j=1;j<size;j++)
{
for (k=j-1;k>=0;k--)
//handling comparision with b[0]
if (k==0&&(a[j]<b[0])) {
b[1]=b[0];
b[0]=a[j];
}
//handling comparison with b[1:size-1]
if (k>0&&(a[j]<b[k])) { b[k+1]=b[k]; }
if (k>=0&&(a[j]>=b[k])) { b[k+1]=b[k]; break; }
}
for (i=0;i<size;i++) printf("%d\n",b[i]);
getch();
}
Use a algorithm that's more simple:
After reading the numbers, copy array A to B to keep the original input.
For ascending sort, set i = 0, j = i + 1
loop j until end of array, if B[j] < B[i] then exchange the two numbers.
Increase i, set j = i + 1, go to step 3. unless i >= size.
print arrays A and B
The algorithm can be optimized later.
Here are the minimal changes with /* comments */ to make your program work:
#include <conio.h>
#include <stdio.h>
void main()
{
int a[10],b[10];
int i,size,j,k;
clrscr();
printf("please tell how many nos you want to enter");
scanf("%d",&size);
printf("Enter the nos");
for (i=0;i<size;i++) scanf("%d",&a[i]);
b[0]=a[0];
//insertionSort algo ---->
for (j=1;j<size;j++)
for (k=j-1;k>=0;k--)
{ /* the inner loop must contain all the if statements */
//handling comparision with b[0]
if (k==0&&(a[j]<b[0])) {
b[1]=b[0];
b[0]=a[j];
break; /* done; don't mess with b[0+1] below */
}
//handling comparison with b[1:size-1]
if (k>0&&(a[j]<b[k])) { b[k+1]=b[k]; }
if (k>=0&&(a[j]>=b[k])) { b[k+1]=a[j]; break; } /* =a[j] */
}
for (i=0;i<size;i++) printf("%d\n",b[i]);
getch();
}

Resources