How does odd number print increasing order? - c

#include <stdio.h>
#include<string.h>
void Magic(int in);
int Even(int n);
int main()
{
Magic(10);
}
void Magic(int in)
{
if(in == 0)
{
return;
}
if(Even(in))
{
printf("%i\n", in);
}
Magic(in - 1);
if(!Even(in))
{
printf("%i\n", in);
}
return;
}
int Even(int n)
{
return (n % 2) == 0 ? 1 : 0;
}
how does odd number print in increasing order?
It prints 10 8 6 4 2 1 3 5 7 9.
I know upto 10 8 6 4 2 but how come it prints 1 3 5 7 9? after decreasing order?

There are nested calls Magic(in - 1);. If number is even it is printed immediately and then Magic(in - 1); is called. Only when n is zero all functions print not even number in reverse order. The first odd number is printed by the deepest Magic() function:
Magic(10)
|print 10
|Magic(9)
| |Magic(8)
| | print 8
| | ...
| | Magic(1)
| | Magic(0)
| | return;
| | print 1
| | return
| | ...
| | return
| |print 9
| |return
|return

this is caused by the recursion of the function. the function is returning in the order it was called. if you want to print the odd numbers in decreasing order after the even numbers, you need to save them in a variable (array ) that is also passed to the magic function

Related

Why my table is not displayed if I do not put it [i]

I would like to know what the [i] is for, and why my table is not displayed if I do not put it in.
Thank you!
#include <stdio.h>
void affiche(int* tableau, int taille);
int main()
{
int tableau[5] = { 12,15,50,20 };
affiche(tableau, 4);
return 0;
}
void affiche(int *tableau,int taille)
{
int i;
for (i = 0; i < taille; i++)`
{
printf("%d\n", tableau[i]);
}
}
[i] is the C language syntax for array notation.
tableau is an array of 5 integers.
int tableau[5] = {12,15,50,20}
In memory tableau has 5 slots allocated to it due to the above declaration.
Slots 0 through 3 are your initialization values.
Slot 4 is uninitialized (though modern c compilers might set this value to null or zero (0).
tableau
+-----------------------+
index | 0 | 1 | 2 | 3 | 4 |
+-----------------------+
value | 12 | 15 | 50 | 20 | ? |
+-----------------------+
inside function affiche(...) this statement
printf("%d\n", tableau)
tries to print to console a single integer (%d) followed by a newline (\n)
But tableau is an array of 5 integers.
So you need the array index to select a specific integer individually like this:
printf("%d\n", tableau[0]) // output: 12
printf("%d\n", tableau[1]) // output: 15
printf("%d\n", tableau[2]) // output: 50
printf("%d\n", tableau[3]) // output: 20
printf("%d\n", tableau[4]) // output: unknown, possible exception
or by function call to affiche(tableau, 4); which ends at index 3
void affiche( int *tableau, int taille)
{
int i;
for( i = 0; i < taille; i++){
printf( "%d\n", tableau[i] );
}
}
Which outputs:
12
15
50
20

How to add items to array in a function using pointers?

I am trying to write this function that takes an array input and assigns random numbers between 1-52 to the array. Then prints back the numbers. I get an error message on the 4th line that says expression is not assignable. Is my use of pointers incorrect or is it not possible to add content to array with pointers?
void shuffleDeck(int *deck[]) {
int i;
for(i=0;i<=52;i++)
rand()%53 = deck[i]; // I get an error message on this line
}
int main() {
srand(time(NULL));
int deck[2000];
shuffleDeck(deck);
int i;
for(i=0;i<=52;i++){
printf("%d", deck[i]);
}
return 0;
}
Assigment direction is from right to left
So in this expression
deck[i] = rand()%52 + 1;
First is called function rand()
Then the result of function %52
Then 1 is added
And finnally its assigned to deck[i]
Array (what you have in main) is
0 1 2 3 4
+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
^-------------------------- arr[0]
While Array of pointers (what your function expects) is
0 1 2 3 4
+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0
+---+---+---+---+---+
------^
| +---+---+---+---+---+
| | 0 | 0 | 0 | 0 | 0 | 1
| +---+---+---+---+---+
| +---+---+---+---+---+
| | 0 | 0 | 0 | 0 | 0 | 2
| +---+---+---+---+---+
|
----------------------------- arr[0][0]
When array is passed to function, then arr[] and *arr are the same. But only as function arguments!
%53 returns 0-52,so if you need 1-52, use %52 + 1 (0-51 + 1 = 1-52)
If you cant solve it, here is code with fixed bugs.
void shuffleDeck(int deck[]) {
int i;
for(i=0;i<=52;i++)
deck[i] = rand()%52 + 1;
}
int main() {
srand(time(NULL));
int deck[2000];
shuffleDeck(deck);
int i;
for(i=0;i<=52;i++){
printf("%d", deck[i]);
}
return 0;
}

Why the first prime number always becoming 1 instead of 2

Here i am trying to implement sieve of erastosthene in c.The program works fine except one major problem.I manually set the first prime number to be of value 2.But at the end when i loop through all the prime numbers array and print them ,the first value becomes 1 instead of 2.Can't figure out why this problem arises.Any help would be much appreciated.
#include<stdio.h>
#include<math.h>
int main(){
int n = 64;
int i,j,limit=sqrt(n)+2,nPrime=0;
int prime[50]={0},mark[64]={0};
mark[1]=1;
prime[nPrime++] = 2;
printf("%d\n",prime[0]); // initialized to 2
for(i=4;i<=n;i=i+2){
mark[i] = 1;
}
for(i=3;i<=n;i=i+2){
if(!mark[i]){
prime[nPrime++] = i;
if(i<=limit){
for(j=i*i;j<=n;j=j+i*2){
mark[j]=1;
}
}
}
}
int k;
int size = sizeof(prime)/sizeof(prime[0]);
printf("%d\n",prime[0]); // changed to 1;
for(k=0;k<size && prime[k]!=0;k++){
printf("%d ",prime[k]);
}
}
The problem is in this loop:
for(i=4;i<=n;i=i+2) {
mark[i] = 1;
}
The condition should be i < n, because with <= it will take the value 64, and that would be out of bounds.
When you set mark[64] = 1 you are modifying memory that does not belong to the mark array, in this case it turn out to be the first element of the prime array. If you test out other indexes, you could end up getting a segfault.
If you set manually mark[64] = 56, you will see that prime[0] == 56
Because local variable are declared on stack, in your case the variable mark[64] which is an array of 64 integer (64 * 4 = 256 bytes) occupies the first 256 bytes of the stack then the array prime (50 * 4 = 200 bytes) occupies the next 200 bytes as shown below:
Stack
|-----------|
| other |
| variables |
| |
prime[49]->|-----------| addr = 0x000001C8
| |
| prime |
|(200 bytes)|
prime[0]->| |
mark[63]->|-----------| addr = 0x00000100
| |
| |
| mark |
|(256 bytes)|
| |
mark[0]->|-----------| addr = 0x00000000
When you write mark[64] = 1, you are actually writing the four bytes of prime[0] = 1.

How to find Square of a number inside a Factorial while loop in C?

I'm trying to create a program that not only calculate the factorial of a number but also display an output where the factorial is less than the square of that number.
These are the requirements:
You type in a number between 3 to 9.
It displays in output both its factorial and its square.
If the factorial of the number inserted is less than the square of the number, Output the string "Gotcha!"
This is my code so far. Thank you
#pragma once
#include <stdio.h>
#define MIN 3
#define MAX 9
#define _CRT_SECURE_NO_WARNINGS
int main()
{
int i, fact = 1, num;
printf("Enter a number:\n");
scanf_s("%d", &num);
while (num >= MIN || num <= MAX)
{
for (i = 1; i <= num; i++)
{
fact = fact*i;
}
if (num < MIN || num > MAX)
{
printf("Out of range. Please try again.\n");
scanf_s("%d", &num);
}
else
{
printf("Factorial of %d is: %d\n", num, fact);
return 0;
}
}
}
Just calculate the square of the number by multiplying it by itself.
square = num * num;
printf("Square of %d is: %d\n", num, square);
if (fact < square)
printf("Gotcha!\n");
r.e. pragmatic approach, I agree with bodangly.
r.e. theory behind your question, lets dig into that a little...
edit: didn't look deeply enough, instead of never my answer should have been "mostly never (only twice for n=2 and n=3).
To recap your question:
Given 'n' find out if the "factorial of n" is less than the "square of n".
We can summarize this as:
n! < n^2
Let's flip this around to make it easier to manipulate:
n! < n^2
n^2 > n!
n * n > n * (n-1) * (n-2) * .. * 1
If we divide each side by n, we get the following.
n > (n-1) * (n-2) * .. * 1
n > (n-1)!
So the question becomes: for what value(s) of n is n > (n-1)! ?
(spoiler alert: not very often)
Let's look to see when n > (n-1)!
Consider this table...
+------------+----+-----+----------+-------------------------+
| n > (n-1)! | n | n-1 | (n-1)! | notes... |
+------------+----+-----+----------+-------------------------+
| no | 0 | -1 | undef | (-1)! is undefined |
| no | 1 | 0 | 1 | 0! is 1 by definition |
| yes | 2 | 1 | 1 | 1! is 1 by definition |
| yes | 3 | 2 | 2 | ( or 2 * 1 ) |
| no | 4 | 3 | 6 | ( or 3 * 2 * 1 ) |
| no | 5 | 4 | 24 | ( or 4 * 3 * 2 * 1 ) |
+------------+----+-----+----------+-------------------------+
Which means n > (n-1)! is only true for n=2 and n=3.
Try something like this:
#include <stdio.h>
#define MIN 3
#define MAX 9
#define _CRT_SECURE_NO_WARNINGS
enum {NO_ERRORS, ERROR};
enum {FALSE, TRUE};
int main()
{
int i, fact = 1, num, valid = FALSE, sqr;
while(!valid){
printf("Enter a number:\n");
scanf("%d", &num);
if (num < MIN && num > MAX){
printf("Out of range. Please try again.\n");
}else{
valid = TRUE;
}
}
/* get the factorial */
for (i = 1; i < num; i++){
fact = fact * i;
}
/* get the square */
sqr = num * num;
/* output */
if( fact < sqr){
printf("%s\n", "Gotcha!");
}else{
printf("Factorial of %d is: %d\n", num, fact);
}
return NO_ERRORS;
}
Thanks

Pattern Programmings

I am having difficulty understanding the logic behind drawing patterns with * and numbers in C.
For example, I am drawing this pattern:
*
* *
** **
* *
*
Some things that I understand in this programs are to take various for loops for printing * and whitespaces, but it's getting difficult to determine the conditions for them.
In the above example I think I need to draw half the triangle and the remaining is the reverse of it.
So please help me to understand the logic I should consider to draw such patterns every time.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j=0,k,l,m,o,n=6;
clrscr();
printf(" ");
for(i=0;i<=3;i++)
{
for(j=2;j>0;j--)
{
printf(" ");
for(k=0;k<=(2*i);k++)
{
printf("*");
// getch();
}
}
// getch();
printf("\n");
}
getch();
}
This is how I tried coding, I am not getting the conditions for nested for loop.
-2 -1 0 1 2
+---+---+---+---+---+
-2 | . | . | X | . | . |
+---+---+---+---+---+
-1 | . | X | O | X | . |
+---+---+---+---+---+
0 | X | X | O | X | X |
+---+---+---+---+---+
1 | . | X | O | X | . |
+---+---+---+---+---+
2 | . | . | X | . | . |
+---+---+---+---+---+
Points are not drawn if (col = 0 and abs(row) != 2) or either row or col is 2 and other is non-zero. You can implement these conditions in your code.
For(row = -2 to 2)
For(col = -2 to 2)
if ( (col = 0 and abs(row) != 2) or (abs(row) = 2 and col != 0) or (abs(col) = 2 and row != 0) )
draw space character
else
draw *
line break
#include<stdio.h>
#include<conio.h>
int main()
{
int n=3,i,j,k,l,m;
clrscr();
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
printf(" ");
for(k=0;k<=i-1;k++)
printf("*",k+1);
for(m=0;m<1;m++)
{
if(i<=0)
printf("*");
else
printf(" ");
}
for(l=i-1;l>=0;l--)
printf("*",l+1);
printf("\n");
}
for(i=0;i<n-1;i++)
{
for(j=0;j<=i;j++)
printf(" ");
for(k=0;k<n-i-2;k++)
printf("*",k+1);
for(m=0;m<1;m++)
{
if(i==1)
{}
else
printf(" ");
}
for(l=1;l>0;l--)
printf("*",l+1);
printf("\n");
}
getch();
return 0;
}
Finally I got my solution by myself.

Resources