Printing numbers - c

I am writing a program to display as below
when n=3
1 2 3
7 8 9
4 5 6
when n=5
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10
my program is
#include<stdio.h>
#include<conio.h>
int main()
{
int n=5,r=1,c=1,i=1,mid=0;
if(n%2==0)
mid=(n/2);
else
mid=(n/2)+1;
printf("mid = %d\n",mid);
while(r<=n)
{
while(c<=n)
{
printf("%d ",i);
c++;
i++;
}
r++;
if(r<=mid)
i=i+n;
else
i=i-(2*n);
printf("\n");
c=1;
}
getch();
return 0;
}
when I give n=3, I am getting my expected output. but when I give n=5 I am getting as below
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
11 12 13 14 15
Could someone please help how to achieve expected output.

Using you code the solution is
#include<stdio.h>
#include<conio.h>
int main()
{
int n=5,r=1,c=1,i=1,mid=0;
int maxRow = n;
if(n%2==0){
mid=(n/2);
maxRow--;
}
else
mid=(n/2)+1;
printf("mid = %d\n",mid);
while(r<=maxRow)
{
while(c<=n)
{
printf("%d ",i);
c++;
i++;
}
r++;
if(r<=mid)
i=i+n;
else if (r >= n)
i=n+1;
else
i=i-((1+(r-mid))*n);
printf("\n");
c=1;
}
getch();
return 0;
}
As you can see:
the i=i-(2*n); is changed. What you wrote wasn't generic, but specific for the n=3 case.
I added else if (r >= n).
Last thing you must use a specific variable for the outer while because of n must be decremented if n is even.
Some tips:
Give to your variables explanatory names
To make your code more readable declare variables 1 per line, if you want to init them.
Live empty lines between code chunks.
int main ()
{
int squareDim=5;
int row=1;
int col=1;
int valueToPrint=1;
int mid=0;
int maxRow = squareDim;
if(squareDim%2==0)
{
mid=(squareDim/2);
maxRow--;
}
else
{
mid=(squareDim/2)+1;
}
printf("mid = %d\n",mid);
while(row<=maxRow)
{
while(col<=squareDim)
{
printf("%d ",valueToPrint);
col++;
valueToPrint++;
}
row++;
if(row<=mid)
{
valueToPrint=valueToPrint+squareDim;
}
else if (row >= squareDim)
{
valueToPrint=squareDim+1;
}
else
{
valueToPrint=valueToPrint-((1+(row-mid))*squareDim);
}
printf("\n");
col=1;
}
return 0;
}

Related

Eratosthenes prime numbers

I have created a program to search for prime numbers. It works without problems until the entered number is smaller than 52, when it is bigger output prints out some blank (0) numbers and I don't know why. Also other numbers have blank output.
My code is:
#include <stdio.h> //Prime numbers
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
int c[100], n, a[50], d, e, b = 1;
void sort() {
for (int i = 1; i < n; i++) {
if (c[i] > 1) {
a[b] = c[i];
printf("%d %d %d\n", a[1], b, i);
b++;
e = 2;
d = 0;
while (d <= n) {
d = c[i] * e;
c[d - 1] = 0;
e++;
}
}
}
}
int main() {
printf("Enter number as an limit:\n");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
c[i] = i + 1;
}
sort();
printf("Prime numbers between 1 and %d are:\n", n);
for (int i = 1; i < b; i++) {
printf("%d ", a[i]);
}
return 0;
}
Here is output for 25:
Enter number as an limit:
25
2 1 1
2 2 2
2 3 4
2 4 6
2 5 10
2 6 12
2 7 16
2 8 18
2 9 22
Prime numbers between 1 and 25 are:
2 3 5 7 11 13 17 19 23
But for 83 is:
Enter number as an limit:
83
2 1 1
2 2 2
2 3 4
2 4 6
2 5 10
2 6 12
2 7 16
2 8 18
2 9 22
2 10 28
2 11 30
2 12 36
2 13 40
2 14 42
2 15 46
2 16 52
0 17 58
0 18 60
0 19 66
0 20 70
0 21 72
0 22 78
0 23 82
Prime numbers between 1 and 83 are:
0 3 5 7 11 0 17 19 23 29 31 37 0 43 47 53 0 61 67 71 73 79 83
Blank spots always spots after 17th prime number. And always the blank numbers are the same. Can you help me please what is the problem?
The loop setting entries in c for multiples of c[i] runs too far: you should compute the next d before comparing against n:
for (d = c[i] * 2; d <= n; d += c[i]) {
c[d - 1] = 0;
}
As a matter of fact you could start at d = c[i] * c[i] because all lower multiples have already been seen during the previous iterations of the outer loop.
Also note that it is confusing to store i + 1 into c[i]: the code would be simpler with an array of booleans holding 1 for prime numbers and 0 for composite.
Here is a modified version:
#include <stdio.h>
int main() {
unsigned char c[101];
int a[50];
int n, b = 0;
printf("Enter number as a limit:\n");
if (scanf("%d", &n) != 1 || n < 0 || n > 100) {
printf("invalid input\n");
return 1;
}
for (int i = 0; i < n; i++) {
c[i] = 1;
}
for (int i = 2; i < n; i++) {
if (c[i] != 0) {
a[b] = i;
//printf("%d %d %d\n", a[0], b, i);
b++;
for (int d = i * i; d <= n; d += i) {
c[d] = 0;
}
}
}
printf("Prime numbers between 1 and %d are:\n", n);
for (int i = 0; i < b; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Output:
chqrlie$ ./sieve4780
Enter number as a limit:
25
Prime numbers between 1 and 25 are:
2 3 5 7 11 13 17 19 23
chqrlie$ ./sieve4780
Enter number as a limit:
83
Prime numbers between 1 and 83 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79
Your problem seems to be caused by the fact that you have declared an array with size 50, but in fact it goes further than that: imagine you want to use Eratosthenes' procedure to find the first 10,000 prime numbers. Does this mean that you need to declare an array of size 10,000 first (or even bigger), risking to blow up your memory?
No: best thing to do is to work with collections where you don't need to set the maximum size at declaration time, like a linked list, a vector, ..., like that you can make your list grow as much as you like during runtime.

Code for Binary search in C not working properly

I can't fix the logical error because I don't know what is wrong in this code. Every input, it shows "element not found". I would really appreciate it if someone can help me in this. Also in this code, I have assumed we'll be taking the size of the array as an odd number, what to do if we decide to take an even number as size?
#include<stdio.h>
int main(){
int size;
printf("Enter the number of elemets(odd number) : ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements in ascending order : ");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
int element;
int flag=0;
printf("Enter element to be found : ");
scanf("%d",&element);
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(element<arr[mid]){
high=mid-1;
}
else if(element>arr[mid]){
low=mid+1;
}
else if(element==arr[mid]){
printf("Element %d found at pos %d ",element,mid);
flag=1;
break;
}
}
if(flag==0){
printf("Element not found");
}
return 0;
}
The problem is your while test. You have:
while(low<high) {
...
}
This will fail when low == high if the desired value is at that position. It is easily fixed by changing the test to:
while(low <= high) {
...
}
This is all that's needed to fix it. You don't need to add any special cases to "fix it up". Just make sure your array is in ascending order and it should work.
EDIT: Refer to the better answer by #TomKarzes
My old answer is:
You missed a boundary case of high==low
#include<stdio.h>
int main(){
int size;
printf("Enter the number of elements(odd number) : ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements in ascending order : ");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
int element;
int flag=0;
printf("Enter element to be found : ");
scanf("%d",&element);
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(element<arr[mid]){
high=mid-1;
}
else if(element>arr[mid]){
low=mid+1;
}
else if(element==arr[mid]){
printf("Element %d found at pos %d ",element,mid);
flag=1;
break;
}
}
if(low==high && arr[low]==element) //Added 1 extra condition check that you missed
{
printf("Element %d found at pos %d ",element,low);
flag=1;
}
if(flag==0){
printf("Element not found");
}
return 0;
}
For starters for the number of elements of the array you shell use the type size_t. An object of the type int can be small to accommodate the number of elements in an array.
This condition of the loop
int high=size-1;
while(low<high){
//...
is incorrect. For example let's assume that the array has only one element. In this case high will be equal to 0 and hence equal to left due to its initialization
int high=size-1;
So the the loop will not iterate and you will get that the entered number is not found in the array though the first and single element fo the array actually will be equal to the number.
You need change the condition like
while ( !( high < low ) )
//...
This if statement within the else statement
else if(element==arr[mid]){
is redundant. You could just write
else // if(element==arr[mid]){
It would be better if the code that performs the binary search will be placed in a separate function.
Here is a demonstrative program that shows how such a function can be written.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int binary_search( const int a[], size_t n, int value )
{
size_t left = 0, right = n;
int found = 0;
while ( !found && left != right )
{
size_t middle = left + ( right - left ) / 2;
if ( value < a[middle] )
{
right = middle;
}
else if ( a[middle] < value )
{
left = middle + 1;
}
else
{
found = 1;
}
}
return found;
}
int cmp( const void *a, const void *b )
{
int left = *( const int * )a;
int right = *( const int * )b;
return ( right < left ) - ( left < right );
}
int main(void)
{
const size_t N = 15;
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < N; i++ )
{
size_t n = rand() % N + 1;
int a[n];
for ( size_t j = 0; j < n; j++ ) a[j] = rand() % N;
qsort( a, n, sizeof( int ), cmp );
for ( size_t j = 0; j < n; j++ )
{
printf( "%d ", a[j] );
}
putchar( '\n' );
int value = rand() % N;
printf( "The value %d is %sfound in the array\n",
value, binary_search( a, n, value ) == 1 ? "" : "not " );
}
return 0;
}
Its output might look for example the following way
0 2 2 3 4 5 7 7 8 9 10 12 13 13
The value 5 is found in the array
4 8 12
The value 10 is not found in the array
1 2 6 8 8 8 9 9 9 12 12 13
The value 10 is not found in the array
2 3 5 5 7 7 7 9 10 14
The value 11 is not found in the array
0 1 1 5 6 10 11 13 13 13
The value 7 is not found in the array
0 3 3 3 4 8 8 10 11 12 14 14 14 14
The value 3 is found in the array
0 5 5 10 11 11 12 13 13 14 14
The value 12 is found in the array
3 4 5 7 10 13 14 14 14
The value 14 is found in the array
0 3 3 7
The value 2 is not found in the array
1 6 9
The value 10 is not found in the array
2 2 3 3 4 4 4 5 5 6 8 8 9 13 13
The value 11 is not found in the array
11 11 13
The value 11 is found in the array
0 0 0 1 2 5 5 5 7 7 8 9 12 12 14
The value 6 is not found in the array
8 8 13
The value 1 is not found in the array
2 2 4 4 5 9 9 10 12 12 13 13 14 14
The value 14 is found in the array

I have some spacing error in my pascals triangle using C programming

The spacing is off in my code, can anyone help. I have attempted it (shown below)
#include <stdio.h>
int factorial(int n){
int fact = 1;
if(n == 0){
return 1;
} else {
for(int i = 1; i <= n; i++){
fact = fact * i;
}
return fact;
}
}
int choose(int n, int r)
{
int ans;
ans = (factorial(n))/((factorial(r))*(factorial(n-r)));
return ans;
}
void triangle(int numOfRows){
for(int n=0; n<numOfRows; n++)
{
for(int i=1; i<=numOfRows-n; i++){
printf(" "); // Note the extra space
}
for(int r=0; r<=n; r++)
{
printf("%5d ",choose(n,r)); // Changed to %3d
}
printf("\n");
}
}
int main(){
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
while(rows > 0 && rows <=13){
triangle(rows);
printf("Enter the number of rows: ");
scanf("%d", &rows);
}
return 0;
}
The expected output should be:
Thanks i'd appreciate it (this is also my first time using this site, so sorry for bad format stuff).
The program needs to work up to 13 rows (which is shown in my while loop in my main functions).
You need to make a couple of changes to have the triangle aligned to the left as in the expected output.
First, you are adding 3 extra spaces in the first loop with the printf(" "), that is fixed using < instead of <= in the loop condition.
Second, there are 4 extra chars added due to the "%5d " in the second printf call, you need to avoid that for the first iteration (when r == 0) using just "%d ".
Here's how the triangle() function will look like after the changes:
void triangle(int numOfRows) {
for(int n = 0; n < numOfRows; n++) {
for(int i = 1; i < numOfRows-n; i++) {
printf(" ");
}
for(int r = 0; r <= n; r++) {
printf(r == 0 ? "%d " : "%5d ", choose(n, r));
}
printf("\n");
}
}
And some example output (works up to 13 without a problem, at least on my 64-bit Linux with both gcc and clang):
Enter the number of rows: 3
1
1 1
1 2 1
Enter the number of rows: 4
1
1 1
1 2 1
1 3 3 1
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Enter the number of rows: 13
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1

Program to code zigzag matrix

Recently, I encountered with a problem that asked me to write a dynamic code that print n x n matrix in a zigzag pattern. Please help me with the code to get the output stated below.
Output:
rows: 5
cols: 5
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
The Code that I've tried so far is in static:
#include <stdio.h>
int main(){
int arr[3][3]={1,2,3,
4,5,6,
7,8,9};
int i, j, k;
for(i=0; i<3; i++){
printf("%d",arr[0][i]);
}
printf("\n");
for(j=2; j>=0; j--){
printf("%d",arr[1][j]);
}
printf("\n");
for(k=0; k<3; k++){
printf("%d",arr[2][k]);
}
printf("\n");
return 0;
}
Now I want the same thing to be done with the user stating rows and columns of an array..
This should work for you:
#include <stdio.h>
int main() {
int rows, columns;
int rowCount, columnCount, count = 0;
printf("Please enter rows and columns:\n>");
scanf("%d %d", &rows, &columns);
for(rowCount = 0; rowCount < rows; rowCount++) {
for(columnCount = 1; columnCount <= columns; columnCount++) {
if(count % 2 == 0)
printf("%4d " , (columnCount+(rowCount*columns)));
else
printf("%4d " , ((rowCount+1)*columns)-columnCount+1);
}
count++;
printf("\n");
}
return 0;
}
Input:
5 5
Output:
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
Simple dynamic logic with k variable
#include <stdio.h>
int main() {
int i,j,k=1,row,col;
printf("Enter row and col \n>");
scanf("%d %d", &row, &col);
for (i = 1; i <=row; i++)
{
for (j = 1; j <=col; j++)
{
if(i%2==0) k--;
printf("%4d",k); // it have to be in center of both condition
if(i%2!=0) k++;
}
k=k+col;
printf("\n");
}
return 0;
}
Input :
7 7
Output :
1 2 3 4 5 6 7
14 13 12 11 10 9 8
15 16 17 18 19 20 21
28 27 26 25 24 23 22
29 30 31 32 33 34 35
42 41 40 39 38 37 36
43 44 45 46 47 48 49

deletion of first two element of array declared statically not working

I am under a situation in a c that suppose i have code below:
#include <stdio.h>
main()
{
int size=8;
int data[18]={12,9,1,7,4,5,3,11};
int i,newS;
printf("check1 \n");
newS= size+1;
data[newS]=data[0] +data[1];
printf("news %d \n",data[newS]);
printf("check2 \n");
for(i=0;i<21;i++)
{
if (data[i] <data[newS] )
{
printf("check3 \n");
data[newS+1]= data[newS] +data[i] ;
newS++;
}
else
{
printf("check4 \n");
}
}
for(i=0;i<21;i++)
{
printf("%d ",data[i]);
}
printf("\n");
}
I expect it to produce result like this : 12 9 1 7 4 5 3 11 21 33 42 43 50 54 59 62 73 18 18 8. But i don't know why it has one "0" just after "11".How to remove this zero ?
The output obtained by corresponding code is this (which is not expected):
12 9 1 7 4 5 3 11 0 21 33 42 43 50 54 59 62 73 18 18 8
Here is the solution i have made to my problem of removing zero : (below is the code for future reference of any user).
#include <stdio.h>
main()
{
int size=8;
int data[18]={12,9,1,7,4,5,3,11};
int i,newS;
printf("check1 \n");
newS= size;
data[newS]=data[0] +data[1];
printf("news %d \n",data[newS]);
printf("check2 \n");
for(i=0;i<21;i++)
{
if (data[i] <data[newS] )
{
printf("check3 \n");
data[newS+1]= data[newS] +data[i] ;
//break;
newS++;
}
else
{
printf("check4 \n");
}
}
for(i=0;i<21;i++)
{
printf("%d ",data[i]);
}
printf("\n");
}
1) The topic of the question keeps changing. This is needlessly frustrating. If you have two questions, either express them both or break them into two separate posts.
2) Hint: What's the index of the last element of an 8-value array?
3) For delection -- restoring my original answer -- shift all the higher-indexed values downward one space in the array, and decrease the length by one.

Resources