# Tag: c

Entries for tag "c", ordered from most recent. Entry count: 3.

Warning! Some information on this page is older than 6 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Pages: 1

# How to check if an integer number is a power of 10?

Wed
04
Oct 2017

I was recently asked a test question to write a function that would check whether a given integer number is a power of ten. I didn't know the answer immediately because I never solved this puzzle before, so I needed to think about a solution. I quickly came to a conclusion that there are many possible solutions, so I later decided to write them down and share with you.

Number is a power of 10 if it's equal to 10, 100, 1000 etc. 1 is also 0-th power of 10. Other numbers like 2, 3, 11, 12 etc. are not powers of 10. 0 and all negative numbers should also be rejected.

Below you can find 5 different solutions - all of them correct, but some of them more efficient than others. Example code is in C, but you can easily implement the same algorithms in Java or any other programming language.

First thing that came to my mind was to convert the number to a string and check whether it contains '1' followed by '0'-s.

`int IsLog10_v1(int32_t x){    // Convert x to string.    char buf[12];    itoa(x, buf, 10);    const size_t bufLen = strlen(buf);    // Check if string contains '1' followed by '0'-s.    if(buf[0] != '1')        return 0;    for(size_t i = 1; i < bufLen; ++i)    {        if(buf[i] != '0')            return 0;    }    return 1;}`

Another option is to convert the number to floating-point format, use "real" log10 function, and check if the result is an integer. Note that double must be used here, because float has too small precision and would incorrectly return 1 for inputs like: 999999999, 1000000001.

`int IsLog10_v2(int32_t x){    // Convert x to double. Calculate log10 of it.    double x_d = (double)x;    double x_log10 = log10(x_d);    // Check if result is integer number - has zero fractional part.    return x_log10 - floor(x_log10) == 0.0;}`

If we want to operate on integer numbers only, we may come up with a recursive algorithm that checks whether the number is greater than zero, divisible by 10 and then calls the same function for x/10.

`int IsLog10_v3(int32_t x){    if(x <= 0)        return 0;    if(x == 1)        return 1;    if(x % 10 != 0)        return 0;    // Recursion.    return IsLog10_v3(x / 10);}`

Because it's a tail recursion, it's easy to convert it to iterative algorithm (use loop instead of recursive call).

`int IsLog10_v4(int32_t x){    if(x <= 0)        return 0;    // Same algorithm as v3, but converted from recursion to loop.    for(;;)    {        if(x == 1)            return 1;        if(x % 10 != 0)            return 0;        x /= 10;    }}`

Finally, the most efficient solution is to notice that there are only few possible powers of 10 in the range of 32-bit integers, so we can just enumerate them all.

`int IsLog10_v5(int32_t x){    // Just enumerate all possible results.    return        x == 1 ||        x == 10 ||        x == 100 ||        x == 1000 ||        x == 10000 ||        x == 100000 ||        x == 1000000 ||        x == 10000000 ||        x == 100000000 ||        x == 1000000000;}`

You can find full source code as a simple, complete C program together with tests on my GitHub, as file: IsLog10.c.

# Hotkey for Macro Inserting Text

Wed
03
Aug 2011

I recently code in C - an ancient language with no support for namespaces. To code a bigger system and not create name conflicts, prefixes for all public identifiers must be used. But they not only make the code less readable, but also take lots of time to type. I thought that at least the second issue can be minimized by setting up some macro that would insert predefined text (like "rendering_"), whenever I press a hotkey button (like Pause/Break).

I couldn't find such feature in my Visual C++ 2010 Express, so I decided to look for some general tool for Windows that can trigger a script when a hotkey is pressed. I found AutoHotkey - a free application with its own scripting language that claims to be successor of AutoIt, which I used some time ago. After reading some documentation, I coded following script:

```Pause::
SetKeyDelay -1
send rendering_
return

+Pause::
SetKeyDelay -1
send RENDERING_
return```

If you have AutoHotkey installed, just save this code to a file, give it "ahk" extension and double-click to run it. Program will create a system tray icon for this script indicating that it's running in the background. From now on you can just press Pause key to insert text "rendering_" to whatever input control you are focused, or Shift+Pause to insert "RENDERING_". It really speeds up coding in C :)

# C primer for C++ programmers

Sun
27
Sep 2009

I've never learnt pure C programming language, only C++. It does not mean I never use global variables or fopen function, but I it makes no sense for me to code in pure C when there is a C++ compiler available. But today I've decided to skim the classic book "The C Programming Language" by Brian W. Kernighan and Dennis Ritchie. Here is what I've found out:

You can actually code in C using Visual C++. To do this, you need to: (+) Create empty project, (+) Add a file with .c extension, (+) Enter project options, (+) Nagivate to Configuration Properties / C/C++ / Advanced, (+) Set "Compile As" to "Compile as C Code (/TC)".

The C language is similar to C++ except it lacks features such as:

• Classes with all the object oriented programming support like encalsupation, inheritance and polimorphism. Of course you can still code in object oriented style just like you do using FILE* or HWND types, but you must use structures and pointers for that purpose.
• Structures cannot have member functions, constructors, destructors or overloaded operators. They can contain only member variables. There are also no private, protected or public sections.
• Memory allocation with new and delete operators. You have to use malloc and free functions and cast void* to the pointer of your type.
• static_cast, dynamic_cast, const_cast, reinterpret_cast operators. There is only old good (type)expr cast available.
• bool type, as well as false and true keywords. You have to use int, char or other integer type instead and assign/check for zero/non-zero values.
• Single line comments starting with (//). There are only multiline comments between (/*) and (*/).
• All the C++ standard libarary including containers, iterators, algorithms, strings and streams. There is a standard C library available from headers such as stdlib.h, stdio.h, math.h, string.h, float.h etc.
• References (&), so you have to use pointers (*).

There are some differences between C++ and C though. For example, you don't have to state type of function parameter or return type if you want to it to default to int. Following lines are equivalent:

```int MyFunc1(int a, int b) { }
MyFunc2(a, b) { }```

Compiler is generally more liberal when it comes to type checking and function calling. You can call function with more arguments than expected and it only generates warning. You can declare function with empty parameter list like MyFunc() which means unknown parameter list! To explicitly state that a function takes 0 parameters you have to write MyFunc(void).

Local variables can be defined only before any other statements in a block. You also cannot define a variable inside for loop. Example:

```void Func(void)
{
int a = 1; // OK
Foo();
int b = 2; // Error!
{
int c = 3; // OK
}
}```

C requires different syntax for using structures. If you define a structure like this:

`struct Struct1 { int x; };`

You have to prefix the name of this type with "struct" keyword each time you use it, just like this:

`struct Struct1 *myObj;`

But luckily typedef construct works in C, so the common solution to this problem is to use it like this:

```typedef struct { int x; } Struct1;
...
Struct1 *myObj;```

Comments | #c++ #c #visual studio

Pages: 1