For Loop condition - c

#include <stdio.h>
#define all_mem (sizeof(x) /sizeof(x[0]))
int x[] ={1,2,3,4,5,6,7,8,9,10};
int main(void) {
// printf("The condition is %d",(all_mem-2));
int i;
for(i=-1;i<=(all_mem-2);i++)
{
printf("The number is %d",i);
}
return 0;
}
In the above code for loop is not even executing for a single time, i tried printing condition and its satisfies for loop condition. Any insights how macro expression in for loop condition is evaluated to the value less than -1?

The all_mem macro is returning a size_t value; integer promotion rules mean the comparison of i <= (all_mem - 2) is promoting i to a size_t, which means the value is huge, rather than -1. Try casting to ensure signed comparison:
for(i = -1; i <=(ssize_t)(all_mem- 2); ++i)

after making a few corrections to the code, forinstance, sizeof() returns a size_t, not an int the code worked perfectly.
Here is the modified code:
#include <stdio.h>
#define all_mem (sizeof(x) /sizeof(x[0]))
int x[] ={1,2,3,4,5,6,7,8,9,10};
int main(void)
{
printf( "all_mem = %ld\n", all_mem ); // << added for debugging
// printf("The condition is %d",(all_mem-2));
int i;
for(i=-1;i<=(int)(all_mem-2);i++) // <<
// << properly cast to int
// otherwise compiler raises warning and unsigned comparison made
{
printf("The number is %d\n",i);
}
return 0;
}
Here is the output from the above code:
all_mem = 10
The number is -1
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
When compiling, always enable all the warnings, then fix those warnings.
If the above statement had been followed, then you would have seen the problem, without our help.
(for gcc, at a minimum use: -Wall -Wextra -pedantic and I also add: -Wconversion -std=c99)

Related

Sum of odd numbers from 1 - 100 using RECURSION in C

Trying to figure out where I am going wrong in this code, I realize I keep getting 1 because that's what am I passing in the function but how else can I do this?
#include <stdio.h>
#include <stdlib.h>
int totalOdd();
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int n){
int odd = n;
if(odd >= 100){
return 0;
}
else{
totalOdd(odd+2);
}
return odd;
}
try this one
one :
#include <stdio.h>
#include <stdlib.h>
int totalOdd(int);
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int n)
{
int odd = n;
if(odd > 100){
return 0;
}
else{
return (n+totalOdd(odd+2));
}
}
in your code , addition was missing
#include <stdio.h>
#include <stdlib.h>
int totalOdd();
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int odd){
if(odd >= 100)
return 0;
return (odd + totalOdd(odd + 2));
}
Not a complete answer, because this sounds like homework, but here’s an example of how to write a very similar function, first recursively, and then a more efficient tail-recursive solution.
#include <stdio.h>
#include <stdlib.h>
unsigned long factorial1(const unsigned long n)
{
/* The naive implementation. */
if ( n <= 1U )
return 1; // 0! is the nullary product, 1.
else
return n*factorial1(n-1);
/* Notice that there is one more operation after the call to
* factorial1() above: a multiplication. Most compilers need to keep
* all the intermediate results on the stack and do all the multiplic-
* ations after factorial1(1) returns.
*/
}
static unsigned long factorial_helper( const unsigned long n,
const unsigned long accumulator )
{
/* Most compilers should be able to optimize this tail-recursive version
* into faster code.
*/
if ( n <= 1U )
return accumulator;
else
return factorial_helper( n-1, n*accumulator );
/* Notice that the return value is simply another call to the same function.
* This pattern is called tail-recursion, and is as efficient as iterative
* code (like a for loop).
*/
}
unsigned long factorial2(const unsigned long n)
{
return factorial_helper( n, 1U );
}
int main(void)
{
printf( "%lu = %lu\n", factorial1(10), factorial2(10) );
return EXIT_SUCCESS;
}
Examining the output of both gcc -O -S and clang -O -S on the above code, I see that in practice, clang 3.8.1 can compile both versions to the same optimized loop, and gcc 6.2.0 does not optimize for tail recursion on either, but there are compilers where it would make a difference.
For future reference, you wouldn’t solve this specific problem this way in the real world, but you will use this pattern for other things, especially in functional programming. There is a closed-form solution to the sum of odd numbers in a range. You can use that to get the answer in constant time. You want to look for those whenever possible! Hint: it is the sum, from i = 0 to 100, of 2 i + 1. Do you remember a closed-form formula for the sum of i from 0 to N? 0, 1, 3, 6, 10, 15, ...? The proof is often taught as an example of a proof by induction. And what happens to a sum from 0 to N when you multiply and add by constants?
As for my example, when I have had to compute a factorial function in a real program, it was for the purpose of computing a probability distribution (specifically, the Poisson distribution) for a simulation, and I needed to calculate the factorial of the same numbers repeatedly. Therefore, what I did was store a list of all the factorials I’d already calculated, and look up any number I saw again in that list. That pattern is called memoization.

Why iterate each digit in a number and find evenly divided digits not working?

I am writing a code in which a input is taken to run some no of test case and in each test case we have to iterate the number through each number and we have to divide it with the initial number taken and if it gives remainder 0 then we need to increment the count otherwise we need not increment the count and at last we will print the count.
The number 12 is broken into two digits, 1 and 2. When 12 is divided
by either of those digits, the calculation's remainder is 0; thus, the
number of evenly-divisible digits in 12 is 2
Compiler Message
Floating Point Exception
The code is given below and when running in a c compiler the program abruptly stops after taking the input.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int t;
int n[t],b,rem;
int count =0;
scanf("%d",&t);
for(int a0 = 0; a0 < t; a0++){
scanf("%d",&n[a0]);
}
for(int i=0;i<t;i++){
b =n[i];
while (n[i]) {
rem = n[i] % 10;
if(b%rem == 0)
count++;
n[i] = n[i] / 10;
}
printf("%d\n",count);
}
return 0;
}
.
You can create an array of a given size before the size being set.
Another error (logical one), is that you didn't reset the counter for each number.
Your initial problem, is that you didn't pay attention of division by 0.
This may be a solution:
int main(){
int t;
scanf("%d",&t);
int n[t];
for (int a0=0; a0<t; a0++){
scanf("%d",&n[a0]);
}
for (int i=0; i<t; i++){
int count = 0;
int b=n[i];
while (n[i]) {
int rem = n[i] % 10;
if (rem!=0 && b%rem==0)
count++;
n[i] = n[i] / 10;
}
printf("%d\n",count);
}
return 0;
}
In your code, at the point you're writing int n[t], t is not initialized. As the initial value of an unitialized automatic local variable is indeterminate and using that invokes undefined behavior, so your code exhibits UB.
You need to move the definition of int n[t] after you successfully scan the value of t from user.
After that, from the property of % operator, quoting C11, chapter §6.5.6, (emphais mine)
The result of the / operator is the quotient from the division of the first operand by the
second; the result of the % operator is the remainder. In both operations, if the value of
the second operand is zero, the behavior is undefined.
so, you need to make sure, rem is not 0 while doing if(b%rem == 0). You should put a check on rem != 0 && .... to avoid this scenario.
That said, just a suggestion: VLAs are not the mandatory part of standard C anymore (C11 onwards), so you can make use of a pointer and allocate dynamic memory using malloc() and family.

Finding trailing 0's in factorial of a number

#include <stdio.h>
main() {
int n;
scanf("%d", &n);
int zz, count;
int i = 5;
while(zz >= 1) {
zz = n / i;
count += zz;
i = i * 5;
}
printf("%d", count);
}
This is code to find trailing 0's in factorial of a number.
It's giving different output in Ubuntu than on Windows.
You can find out at least a few of the issues by enabling warnings during compilation. In this case (output from clang -Wall -Wextra the_file.c):
tst.c:3:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main() {
^
tst.c:10:9: warning: variable 'count' is uninitialized when used here [-Wuninitialized]
count += zz;
^~~~~
tst.c:6:18: note: initialize the variable 'count' to silence this warning
int zz, count;
^
= 0
tst.c:6:9: warning: variable 'zz' is used uninitialized whenever function 'main' is called [-Wsometimes-uninitialized]
int zz, count;
~~~~^~
tst.c:8:11: note: uninitialized use occurs here
while(zz >= 1) {
^~
tst.c:6:11: note: initialize the variable 'zz' to silence this warning
int zz, count;
^
= 0
3 warnings generated.
You should fix all of those first.
I'm not sure exactly what you're asking, but there are a couple problems with your code I can point out:
Indent your code. Indenting code is mandatory.
Try to put whitespace around operators. It goes a long way towards making your code more readable.
Don't use scanf. You will be much happier if you avoid the entire scanf family of functions.
You're using zz and count without initializing them. C does not initialize variables to any particular value; you always must initialize them yourself.
You should really change main to int main. They do the same thing, but the latter is easier to read.
If you add some test cases explaining what your code is supposed to do, it will be easier to answer your question.
Uninitialized variable
int zz, count;
int i = 5;
while(zz >= 1) { // what is zz?
i = i * 5; overflows. Undefined behavior. Different result on different systems is not unexpected.
--
There is no need to compute the factorial. Just count the number of 5s in n.
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
printf("%d", n/5);
}
15! --> 1307674368000
9! --> 362880
To have a trailing 0, the factual needs a product of some multiple of 5 and a multiple of 2. Every other number in the factorial combination is even and every 5th is a multiple of 5.
public static void main(String[] args) {
int n=23;
String fact= factorial(BigInteger.valueOf(23)).toString();
System.out.format("Factorial value of %d is %s\n", n,fact);
int len=fact.length();
//Check end with zeros
if(fact.matches(".*0*$")){
String[] su=fact.split("0*$");
//Split the pattern from whole string
System.out.println(Arrays.toString(fact.split("0*$")));
//Subtract from the total length
System.out.println("Count of trailing zeros "+(len-su[0].length()));
}
}
public static BigInteger factorial(BigInteger n) {
if (n.equals(BigInteger.ONE) || n.equals(BigInteger.ZERO)) {
return BigInteger.ONE;
}
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}

Hacker Rank : Project Euler#1

I am new to competitive programming and I did a problem on Hacker Rank. The question statement is as follows:
"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
Input Format
First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.
Output Format
For each test case, print an integer that denotes the sum of all the multiples of 3 or 5 below N."
Constraints
1≤T≤10^5
1≤N≤10^9
I've written the following code which successfully satisfies 3 test cases and fails at remaining two.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int func(int p,int n)
{
int j;
n=n-1;
j=n/p;
return (p*j*(j+1))/2;
}
int main()
{
unsigned long int n;
int t,j,count;
scanf("%d",&t);
if(t>=1 && t<=100000){
for(j=0;j<t;j++)
{
scanf("%lu",&n);
if(n>=1 && n<=1000000000)
{
count=func(3,n)+func(5,n)-func(15,n);
printf("%d\n",count);
}
}}
return 0;
}
What is the mistake in my code. Why isn't it getting accepted?
There are a couple of issues.
You are indeed overflowing your int when returning from func. Also, your printf statement should be printf("%llu\n", count);
So, the return from func, count, and the local variable j, should all be unsigned long long and your print out should reflect that as well. You need to make j unsigned long long because of the arithmetic in the return statement for func(this is at least the case in VS 2013).

c variable turning into -17918 when incremented

hi i am making a programming language that will run on the nintendo gameboy in c
which is why you will see some functions like waitpad();
but this question is unrelated the the gameboy librarys
for some reason when ever i try to increment a certain variable in my main.c file:
#include <stdio.h>
#include <gb/gb.h>
#include "convert.h"
#include "display.h"
#include "input.h"
#include "functions.h"
#include "interpreter.h"
unsigned char cnt[5] = {1,2,3,4,5};//cnt is short for counters
unsigned char k = 0;
unsigned char running = 1;
unsigned char memory[2048];
unsigned char code[2048];
int main()
{
Clear_mem();
Clear_code();
while(running == 1) {
display(cnt[0],cnt[1],cnt[2],cnt[3],cnt[4]);
printf("cnt[0] = %d\n", cnt[0]);
cnt[0]++;//turns into -17918
printf("Press Start To Enter Next Character\n");
waitpad(J_START);
code[k] = input();
interpret(code[k]);
k++;
}
return 0;
}
cnt[0] turns into -17918
can anyone see any problem that would cause it to behave this way?
You ask if anyone sees a problem, well - yes, here is a problem:
unsigned char k = 0;
unsigned char running = 1;
unsigned char code[2048];
while(running == 1) {
code[k] = input();
k++;
}
If k >= 2048, then code[k] = ... will cause a memory-override.
After a memory-override, pretty much anything can happens (undefined behavior).
Having said that, the value of k can be larger than 2047 only if CHAR_BIT is larger than 11.
Add #include <limits.h> to your program and make sure that CHAR_BIT is not larger than 11.
You have to convert it to an integer, because that's what you're trying to print:
printf("cnt[0] = %d\n", (int) cnt[0]);
When you're using a variadic function like printf, you have to make sure you're passing the right type. Check your compiler warning settings, new compilers can easily detect these kind of problems.
if you want to print the character value of your character variable you should print it like this:
printf("cnt[0] = %c\n", cnt[0]);
If you print it using %d the expansion of the character to a size of int could be negative for characters over half a character's size (0x80 and up).
If you insist on printing it as an int cast the variable like this:
printf("cnt[0] = %d\n", (int)cnt[0]);

Resources