Struct C: Packing Data

Structures in C Programming Language

struct cIf you have a collection of data, say a bunch of numbers, you can store them as a array type in C. If they are bunch of strings, you can store them as an array of strings. Lets say you have a series of strings, representing items of a grocery store shelf, and two other arrays of numbers containing inventory of the item and its sale price, then question is how do you keep track of this item ? The solution is not surprising if you consider the complex user defined data-type called structures, in the C language.

In this blog post, we are going to see how you can create composite data types, like item in the above example, which contains the remaining inventory, name of item and cost price. We will also discuss the extensions of structures to build data structures like singly linked list. Languages like C++ and Java have template structures to implement advanced data structures. [Read more…]

strlen C : Counting Strings

Strings in C Programming Language

strlen cStrings are essential elements in a programmer’s toolkit. They are one of the most commonly used elementary data types, while writing code, and debugging during the development; as also while formatting output for the user.

In this blog post we are going to see how you can create strings, write them to the output, read user input as strings, and count them. Compared to modern programming languages like Python, or Java, string handling in C is still primitive. [Read more…]

Java String Length: Counting Strings

java string lengthStrings in Java Programming Language

Strings are essential elements in a programmer’s toolkit. They are one of the most commonly used elementary data types, while writing code, and debugging during the development; as also while formatting output for the user. Strings in Java are first-class objects, with a wide set of methods to operate on them; it is a breeze to search, sort, compare, find things in a string, and query their length, emptiness, digit/letter nature etc, compared to old procedural languages like C or C++.

In this blog post we are going to see how you can create strings, write them to the output, read user input as strings, and count them. As a modern programming languages Java offers capabilities like other comparable systems in Python, or Ruby. String handling is way superior to C language.

[Read more…]

Java Static Functions : Conventions and Usage

Static Keyword in Java Language

java staticJava programming language and JVM (Java Virtual Machine) sandbox environment allows defining new types, by class declaration. In Java everything is an object, except for special boxed/unboxed boolean, numeric and string elementary data types. Some Java classes are not instantiable. Let me explain in this blog post, with two key examples of static functions, and static objects in Java language. In the blog post ‘Java Static Functions : Conventions and Usage’ we show conventions of static keyword in Java language, and usage with objects and functions. You can learn more on these lines at introductory programming in Java.

Some of the computer science techniques, patterns if you will, of problem solving are advanced algorithms and design patterns. These are patterns of problem solving that are widely applicable to computer programs used in advanced computer-science algorithms, to those used in GPS systems, and Google Maps for picking your routes. Many of these algorithms use advanced mathematical techniques you can learn. [Read more…]

C FILE I/O: Using File Storage

File Input/Output in C Programming Language

c file ioFiles are essential elements in computer storage which contain user data or represent a user document. Files are of image, text, audio, video or other binary data. In this blog post we are going to see how you can read from the disk, write to a disk, using the C FILE I/O interface. Compared to modern programming languages like Python, or Java, FILE I/O in C is still primitive. This blog post walks you  through two examples of FILE I/O in C language – a part of a beginners lessons in C.

File I/O Operations

If you a beginning C user, you may benefit from using the C compiler in small steps. In Windows you can use the Mingw GNU tool chain, Borland C/C++ compilers or Microsoft Visual Studio, or the shell in Linux. Start by typing in the shell,

$ gcc --version

and you should see the following output, then you are ready to dive into C development. [Read more…]

C ‘assert’: Design Invariants With Macros

Using Assertions for Robust Software Development

c assertDuring the course of the software development in C, there are deliverables for customers and deadlines, but developers will find bugs and issues in their design or execution, or both. How do software developers build programs and maintain it across these years with changing feature requests? On a simpler level, how do change software, code – programs, and algorithms – without losing the original functionality?

Software development learns from a maxim, ‘History repeats itself, if you don’t learn from your mistakes‘. In this blog post, you will learn about writing a simple C program and updating it as requirements change all the time using unit tests to capture this behavior. This could be your beginning, exciting baby steps to advanced graphics programming, and game development!

Meet the Assert Macro

If you a beginning C user, you may benefit from using the C compiler in small steps. In Windows, you can use the Mingw GNU tool chain, Borland C/C++ compilers or Microsoft Visual Studio, or the shell in Linux. Start by typing in the shell,

$ gcc --version

and you should see the following output, then you are ready to dive into C development.

gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

Copyright (C) 2011 Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO

warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Follow along by typing into a file these lines of code and save it as ‘assert_true.c’

#include <stdio.h>

#include <assert.h>


typedef unsigned char bool;

bool TRUE = 1;
bool FALSE = 0;


int main() {
    assert( TRUE );
    assert( 1 + 1 ) ;
    assert( 1 + 1 > 0 );
    assert( 1 + 1  –  4 ) ; 
}

To compile and execute the program you can run the commands,

$ gcc assert_true.c -o assert_true
$ ./assert_true

And you can see no real output except the next prompt, which means you code did not trigger any assertion faliures. Lets try again with another program, and save it as ‘assert_fail.c’

#include <stdio.h>
#include <assert.h>

typedef unsigned char bool;

bool TRUE = 1;
bool FALSE = 0;


int main() {
    assert( FALSE );
    assert( 1 - 1 ) ;
    assert( 1 - 1 > 0 );
    assert( 1 - 1  -  4 > 0 ) ; 
}

To compile and execute the program you can run the commands,

$ gcc assert_fail.c -o assert_fail
$ ./assert_fail
assert_fail: assert_fail.c:10: main: Assertion `FALSE' failed.

Aborted

Your empirical experiments have shown you something about assert macro; i.e. on True evaluation of expression assert is quiet, on false evaluation of the statement it triggers the assert_fail and aborts the program execution.

Syntax of Assert Macro

The assert is a macro in C language. To include the assert function in your program you can add the header file definition,

#include <assert.h>

where the assert macro evaluates the expression and aborts execution when the said expression has a false value in C. If the expression evaluates to NULL, false, 0, then assertion is said to have occurred. Only calls like setjmp, and longjmp and atexit have a change of completing after the assert() has triggered. For more details read the manual page on Linux for assert function.

	$ man assert 

should bring up a page like,

 

ASSERT(3)                  Linux Programmer's Manual                 ASSERT(3)


NAME

       assert - abort the program if assertion is false


SYNOPSIS

       #include <assert.h>


       void assert(scalar expression);


DESCRIPTION

       If  the  macro  NDEBUG  was  defined  at the moment <assert.h> was last

       included, the macro assert() generates no code, and hence does  nothing

       at all. 

Program Design

Programmers use the assert macro to raise errors to catch unexpected behavior of their code. For example, if you wrote a program to calculate the volume of a solid, or area of a polygon, you can include an assertion that the volume, or area, respectively should not be zero; i.e. assert area > 0

Examples – Using Assertions in Factorial Function

Factorial of a number, N, is defined to be the product of numbers from 1 to N; i.e. N! = 1*2*3* … N. Clearly a straightforward way to calculate factorial is using a for-loop, but we prefer to use a recursive definition. This recursive form is equivalent, and accurate, mathematical definition of factorial function is using the notation; i.e. N! = (N-1)!*N. Here we can use the assert macro to ensure the result of factorial is always positive.

Clearly a way of writing this as a program in iterative and recursive ways would be,

#include <stdio.h>
#include <assert.h>

typedef unsigned char bool;

bool TRUE = 1;
bool FALSE = 0;

/* recursive way of writing factorial */

int fact( int n ){
    if ( n == 0 ) {
        return 1;
    }
    return fact( n - 1)*n;
}


int main() {
      int fact_val;
      int i;

      for( i=0; i < 10; i++ ) {       	     
       	 fact_val = fact(i);
         /*factorial is always non-zero*/
       	 assert( fact_val > 0 );
         printf("%d! = %d\n",i,fact_val);
     }

     return 0;
}

Running the Program

You can download C package for your platform from the source website, C.org, and run the tests and programs as, $gcc fact_assert.c -o fact_assert && ./fact_assert, is the command to interpret the code and then run the program

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880

Bugs and Fixes

There are various bugs in the function in the program few of which are,

  1. Function does blows up with negative inputs. You need to have include guards or asserts.

  2. Numerical overflow for large input n

It is left as an exercise to the reader to update the code for the following and run it on the C interpreter to see a message which shows the 2 unittest have passed, and happy ‘OK’ message is printed on screen.

Summary

Software developers use assertions to enforce invariants in the design of programs, and testing those programs against regression. The C assert macro is one of key tools to enforce invariants in code, and in testing enabling users and developers of programs to progress without regression. Learn more about regression testing and software design. Learning C can lead you to other things like programming your iPhone, and more complex projects.

Binary Number System : Counting With Ones And Zeros

Introduction to Number Systems

binary number systemNumber systems in mathematics are devised to keep track of the several aspects of computing, and calculation including arithmetic – basics of addition, subtraction, multiplication and division – among other conceptual issues. Everyday, we balance our accounts, pay bills, and settle grocery lists using the well known decimal system initially taught as a part of grade school education. Computer arithmetic is however carried out in the binary system. For example, programming languages are used to instruct the computers in these binary languages.

To learn from this article, it is best to make a distinction between numbers as a concept and its written forms as number system. For example, the number one hundred is written as ‘C’ in Roman numeral system, 100 in decimal system we use daily, and 64 in hexadecimal (base-16) system – and regardless of the system of representation, we have the same properties of hundred – it is even, composite, power of 10 raise to two, etc. The ancients knew something about counting with fingers, because words and digits have its etymology tracing back to the fingers and toes.

Binary System Compared to Decimal System

The decimal system is a method of computing and natural system of counting where we have 10-digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 to represent numbers. Rules of decimal arithmetic are easy and we know these in practice,

  1. Addition rules are, 0 + 1 → 1, 2+3 → 5, 9 + 0 → 9, 9 + 8 → 17 etc

  2. Subtraction rules are, 0 – 1 → -1, 5 – 9 → -4, etc.

  3. Multiplication rules are, 0*1 → 0, 1*1 → 1, 8*5 → 40, etc.

  4. Division rules are defined such, when 40/5 → 8 | 40 = 5*8, etc.

    Fractional numbers in the decimal system are written to the right of a decimal point. Each position to the left of decimal point is valued at 10 raised to a negative power.

To write the number five-tenths plus 7 hundredths we will use a notation like, 5/10 + 7/100 = 0.57 = 5*10^-1 + 7*10^-2.

Note: This article uses the computer programming notation for exponent or power operation ‘^’ to write, 1/10 = 10^-1, and 1/100 = 1/(10*10) = 1/(10^2) = 10^-2.

Elementary Operations in Binary Arithmetic

In this section we will see how you can carry out elementary binary operations like, addition, subtraction, multiplication and division.

  1. Addition rule are: 1 + 1 → 10, 0 + 0 → 0, 0 + 1 → 1, 1 + 0 → 0

  2. Multiplication rules are: 1 x 1 → 1, 1 x 0 → 0, 0 x 1 → 0, 0 x 0 → 0

  3. One’s complement of binary digit: ~1 =0 , ~0 = 1. Complement can be thought of as logical negation at digit level. Ones complement of a number is doing the ones complement at every digit. i.e. 1’s complement of (10110)2 → (01001)2

  4. Logical operations on binary digits:

    1. AND: 0 AND 0 → 0, 0 AND 1 → 0, 1 AND 0 -> 0, 1 AND 1 → 1

    2. OR: 0 OR 0 → 0, 0 OR 1 → 1, 1 OR 0 -> 1, 1 OR 1 → 1

    3. XOR: 0 XOR 0 → 0, 0 XOR 1 → 1, 1 XOR 0 -> 0, 1 XOR 1 → 1

  5. Subtraction rules are same as addition except the second operand is converted to two’s complement notation before addition. For example,

  6. Division is carried out using fractional binary numbers, including a decimal point.

Some conventions

Two’s complement of a number, usually used in binary subtraction, is defined as the taking the one’s complement (or just complement we talked about earlier in 3). Twos complement of(10110)2 is got by taking the 1’s complement (10110)2 → (01001)2 and adding 1 →. (01010)2.

The leading bit position in the number (left-most) (10110) is called most significant bit (MSB), is ‘1’, and the (right-most) bit is called least-significant bit (LSB), ‘0’ in this case.

Example – Converting Binary to Decimal in Python

In this example we will write a Python program to convert a binary number to decimal. We will also handle the fractional binary numbers.

  1. Initialize return value to 0
  2. First start at the MSB, and upto the decimal point, and repeat steps 3-4
  3. Find the power of two at the position, if the bit-position is 1, or use 0.
  4. Add return value to the previous result of step-3.
  5. Repeat 3-4 till you reach decimal point.
  6. For each bit position upto end of number repeat the steps 7-8
  7. If bit position is 0, continue to next right-most, otherwise add the negative power of 2 raised to offset from the decimal point
  8. Add return value to this number calculated in the 7.
  9. Repeat 7-8 till end of the number.

To illustrate manually, this algorithm works out as follows,

(101.101)2 = 1 x 2^2 + 0x2^1 + 1×2^0 + 1×2^-1 + 0x2^-2 + 0x2^-3

= 1 x 4 + 0 x 2 + 1 x 1 + 1 x ½ + 0x ¼ + 1 x 1/8

= 5 + ½ + 1/8

= 5.625

Putting it all together we get the Python code, and saving it as ‘bin2dec.py’

     1	def bin2dec( binstr ):

     2	    dec_pos = binstr.find('.')

     3	    assert( dec_pos != -1 )

     4	    

     5	    val = 0.0

     6	    for itr in range(0,dec_pos):

     7	        pow2 = int(binstr[itr])*2**(dec_pos-itr-1)

     8	        val = val + pow2

     9	    

    10	    for itr in range(dec_pos+1,len(binstr)):

    11	        neg_pow2 = int(binstr[itr])*2**(dec_pos-itr)

    12	        val = val + neg_pow2

    13	    return val

    14	if __name__ == "__main__":

    15	   print bin2dec('1011.11')

    16	   print bin2dec('101.101')

which you can run on the Python shell, and you will see the following results, when you input

$ python bin2dec.py 
11.75
5.625

Summary

Number systems in mathematics are devised to keep track of the several aspects of computing, and calculation including arithmetic – basics of addition, subtraction, multiplication and division – among other conceptual issues. Everyday we balance our accounts, pay bills, and settle grocery lists using the well known decimal system, initially taught as a part of grade school education. Computer arithmetic is however carried out in the binary system. These are foundations for large and complex programs like web crawlers, machine learning software, and other intelligent systems.

JavaScript Exit: Control an Early Termination in Your Code

JavaScript exitIf you are new to web programming, coming from a procedural language like C, or C++ or even Java, it is a lot of new ideas and concepts. One of the most important things to ask about in your code in a procedural program is when to exit or stop the routine and return to the host processing system.

In web programming, there is a separation between the client-side and the server-side code. We will mostly focus on the latter – JavaScript. Various languages, including JavaScript, the new Dart-lang from Google, and earlier VB Script from Microsoft, are supported in the web browser to enhance user experience by programming the HTML pages on the client-side browsers.

This blog post focuses on the challenges of client-side programming when you have to abort or exit processing events, or exit from your JavaScript code. The challenge, to someone from a procedural background, is the non-availability of the usual routines like exit(), abort(). Read on about client-side programming and challenges of writing code that exits early from processing. [Read more…]

Python Else If: Using Conditional Statements

python else if Computers do not understand English or Spanish or any other native human language. To tell a computer to perform specific actions to completing a task reliably, and sometimes even repeatedly, it needs to have instructions; which are somewhat similar in nature to the recipes used in a kitchen for making delicious food, and a scrumptious meal.

These instructions are what we call a programming language. So if you are curious to learn about how to make your computer say your name out loud when you login everyday morning, or have your computer balance your monthly accounts, or pull a file from the Internet comic strip every day, you have come to the right place.

[Read more…]

JavaScript Sleep: Scheduling Tasks Asynchronously

sleep JavaScript If you are new to web programming, it is a whole new world of ideas and concepts in addition to algorithmic ideas, which you may already be familiar. But you have easy ways to catch up, so don’t worry yet!

One key idea in web programming is the separation between the client-side and the server-side code; languages and frameworks like Django, Ruby-on-Rails allow you to serve up content from the server-side. Whereas JavaScript, the new Dart-lang, and in the past VB Script from Microsoft, are techniques used to shape user experience by programming the HTML pages on the client-side browsers.

This blog post focuses on the challenges of client-side programming when you have to delegate events at specified times, without using sleep() like methods usually available in the traditional programming languages. Read on about client-side programming and challenges of writing code asynchronously. [Read more…]