egsoftweb@gmail.com
 facebook.com/egsoftweb

Welcome to EGSoftWeb

Programming
Blogs and Tutorials

Blogs on programming, technology and programming tutorials.

Desktop
Application

Antivirus, encryption/decryption, folder locking tools and miscellaneous desktop applications.

Programming Library

C++ drawing library for plotting shape in 2D, 3D, animation and many other functions.

Android
Application

Just gambling around the android programming and need to make a few useful android applications and tricky android puzzle games.

if-else statements

 c tutorials |  Admin

Syntax:

if (expression) statement1;

else statement2;

where statement1 or statement2 may consist of a single statement, a block of statements, or an empty statement(;) . The else part is optional.

 

If expression evaluates to true (anything other than 0), the statement1 will be executed, otherwise the statement2  will be executed,(in case the else part exists.)

 

Example:

#include <stdio.h>

#define scanf scanf_s

int main()

{

      int number;

      printf("Enter any number: ");

      scanf("%d", &number);

 

      if (number)

      {

            printf("the number is not zero");

      }

      else

      {

            printf("the number is zero");

      }

 

      /*

      //Because there are only one statement,

      //above if-else statements can also be written as

        

      if (number)

      printf("the number is not zero");

      else

      printf("the number is zero");

      */

 

      getchar();

      return 0;

}

 

 

Nested if:

A nested if is an if that is the target of another if.

Example:

#include <stdio.h>

#define scanf scanf_s

int main()

{

      int number;

      printf("Enter any number: ");

      scanf("%d", &number);

      getchar();

 

      if (number > 0)

      {

            printf("the number is greater than zero\n");

            if (number > 10)

            {

                  printf("the number is also greater than 10\n");

                  if (number > 100)

                  {

                        printf("the number is even greater than 100\n");

                        printf("stop checking now...");

                  }

                  else

                        printf("the number is in (10-100] range\n");

            }

            else

                  printf("the number is between (0-10] range");

      }

      else

            printf("the number is either zero or negetive\n");

 

      getchar();

      return 0;

}

 

[Note: Here we can similarly understand Nested else.]

 

The if-else-if Ladder:

Syntax:

       if (expression1)

            statement1;

      else

            if (expression2)

                  statement2;

            else

                  if (statement3)

                        statement4;

            .

            .

            .

            .

            .

The conditions are evaluated from the top to down side.  

Operators in C

 c tutorials |  Admin

There are four main classes of operators:

arithmetic,

relational,

logical,

bitwise

 

In addition, there are some special operators, such as the assignment operator, for particular tasks.

 

Assignment Operator (In Short):

 

Syntax:             variable_name = expression;

 

Arithmetic Operators:

Operator

Action

+

Addition, also unary plus

-

Subtraction, also unary minus

*

Multiplication

/

Division

%

Modulus

++, --

Increment & Decrement

 

//example using arithmatic operators

#include <stdio.h>

int main()

{

     int a = 20, b = 10;

 

     int add = a + b;

     int sub = a - b;

     int mul = a * b;

     int div = a / b;

     int rem = a % b;

 

     int u_plus = +a;

     int u_minus = -a;

 

     printf(" + result: %d\n", add);

     printf(" - result: %d\n", sub);

     printf(" * result: %d\n", mul);

     printf(" / result: %d\n", div);

     printf(" %% result: %d\n", rem);

     printf(" unary + result: %d\n", u_plus);

     printf(" unary - result: %d\n", u_minus);

 

     getchar();

     return 0;

}

 

 

Increment and Decrement Operators:

There are two useful operators that simplify two common operations. These are the increment and decrement operators, ++ and --.

x = x+1; is the same as ++x;

x = x–1; is the same as --x;

Both the increment and decrement operators may either precede (prefix) or follow (postfix) the operand.

 

For example,

x = x+1; can be written ++x; or x++;

 

Difference between prefix & postfix increment or decrement operators:

When an increment or decrement operator precedes its operand, the increment or decrement operation is performed before obtaining the value of the operand for use in the expression.

 

If the operator follows its operand, the value of the operand is obtained before incrementing or decrementing it.

 

For example:

int x, y;

//then,

x = 10; y = ++x;

//sets x to 11 and y to 11. But,

 

x = 10; y = x++;

//sets x to 11 and y to 10.

 

Precedence of the arithmetic operators:

Highest

++     --

 

unary plus     unary minus

 

*     /     %    

Lowest

+     -

 

We can use parentheses() to alter the order of evaluation. Parentheses force an operation, or set of operations, to have a higher level of precedence.

 

Relational and Logical Operators:

Relational Operators:

Operator

Action

Greater than

>=

Greater than or equal

Less than

<=

Less than or equal

==

Equal

!=

Not equal

 

Logical Operators:

Operator    

Action   

&&

AND

||

OR

!

NOT

All relational and logical expressions produce a result of either true or false (1 or 0).

 

Examples: 

// example using relational operators

#include <stdio.h>

void print(int val)

{

     printf(" %d\n"val);

}

int main()

{

     print(2 > 1);

     print(2 < 1);

     print(2 >= 1);

     print(2 <= 2);

     print(2 == 0);

     print(2 != 1);

     getchar();

     return 0;

}

 

//example using logical operators

#include <stdio.h>

void printLogics(int pint q)

{

     printf("%d\t%d\t%d\t%d\t%d\n\n"pqp && qp || q, !p);

}

 

int main()

{

     printf("p\tq\tp&&q\tp||q\t!p\n\n");

     printLogics(0, 0);

     printLogics(0, 1);

     printLogics(1, 1);

     printLogics(1, 0);

     getchar();

     return 0;

}

 

The relative precedence of the relational and logical operators:

Highest

!

 

>     >=     <     <=

 

==     !=      

 

&&

Lowest

||

 

Bitwise Operators:

Operator

Action

&

AND

|

OR

^

Exclusive OR (XOR)

~

One`s complement (NOT)

>> 

Shift right

<< 

Shift left

 

Bitwise operators are used for testing, setting, or shifting the actual bits in a byte or word, which correspond to the standard char and int data types and variants.

 

[Note: Bitwise operator cannot be use on float, double, long double, void, or other more complex types.]

 

Examples:

 

//example using bitwise AND,OR,XOR and One`s complement

#include <stdio.h>

void printBitwiseOperations(int pint q)

{

     printf("%d\t%d\t%d\t%d\t%d\t%d\n\n"pqp&qp | qp^q, ~p);

}

int main()

{

     printf("p\tq\tp&q\tp|q\tp^q\t~p\n\n");

     printBitwiseOperations(0, 0);

     printBitwiseOperations(0, 1);

     printBitwiseOperations(1, 1);

     printBitwiseOperations(1, 0);

     getchar();

     return 0;

}

 

// example using bitwise shifting

/* A bit shift example. */

#include <stdio.h>

int main(void)

{

     unsigned int a, b, c, d, e;

     a = 1;

     /* left shifts */

     /* left shift a by 1, which is same as a multiply by 2 */

     b = a << 1;

     printf("Left shift %d: %d\n", a, b);

     c = b << 1;

     printf("Left shift %d: %d\n", b, c);

 

     /* right shifts */

     /* right shift i by 1, which is same as a division by 2 */

     d = b >> 1;

     printf("Right shift %d: %d\n", b, d);

     e = c >> 1;

     printf("Right shift %d: %d\n", c, e);

     getchar();

     return 0;

}

 

 

Assignment Operator (In Details):

 

Syntax:          

variable_name = expression;

 

A single equal sign is used to indicate assignment.

 

Left part of the syntax is called lvalue and right part is called rvalue.

 

Left part must be an object such as a variable and right part must be a value (any constant or value of an expression).

Type Conversion in Assignments:

When variables of one type are mixed with variables of another type, a type conversion will occur automatically. The value of the right side of the assignment is converted to the type of the left side.

 

Multiple Assignments:

Many variables can be assigned with the same value by using multiple assignments in a single statement.

 

For example,

int x, y, z;

x = y = z = 7;

 

 

Compound Assignments:

Syntax:

var = var operator expression 

can be rewritten as

var operator = expression

 

+=, -=, *=, /=, %= etc are Compound Assignments.

 

For example, x = x+5 can be written as x += 5;

 

All binary operators (that require two operands) can be used as Compound assignment operator.

 

 

? Operator (ternary operator):

Syntax:

 

Exp1 ? Exp2: Exp3;

 

means Exp1 is calculated and if Exp1 is 1 or(true) then Exp2 is calculated otherwise Exp3 is calculated.

 

For example a variable can be assigned according to a condition like

variable = condition ? variable1 : variable2;

if condition is 1 then variable= variable1 otherwise variable= variable2

 

 

& and * (address and pointer Operators):

Address operator (&): As a unary operator, returns the memory address of its operand.

 

For example,

m = &var;

 

Here m equals the memory address of var.

 

Pointer operator (*): As a unary operator, returns the value of the object located at the address that follows it.

 

For example:

v = *m;

the value of var is assigned to v.

 

// simple example using address and pointer Operators.

#include <stdio.h>

int main(void)

{

     int target, source; 

     int *m;

     source = 2500;

     m = &source;

     target = *m;

     printf("%d", target);

     return 0;

}

 

 

Compile-Time Operator sizeof:

sizeof is a unary compile-time operator that returns the size( in bytes) of the variable or  parenthesized type that it precedes.

For example,

// example sizeof operator

#include <stdio.h>

int main()

{

     double f = 3.1415;

     printf("%d "sizeof f);

     printf("%d"sizeof(int));

     return 0;

}

 

 

Comma Operator (,):

The left side of the comma operator is always evaluated as void. The expression on the right side becomes the value of the total comma-separated expression.

For example,

 

x = (y=3, y+1);

Here, 3 is assigned to y and then value of x is calculated as y+1.

Parentheses are necessary with the comma operator because comma operator has a lower precedence than the assignment operator.

 

 

The Dot (.) and Arrow (–>) Operators:

These operators are used to access elements/members of structures, unions. The dot operator is used when working with a structure or union directly while arrow operator is used with a pointer to a structure or union.

 

For example:

// example using dot (.) and arrow (->) operator

struct Circle

{

     float radius;

     float centerX;

     float centerY;

};

 

struct Circle c = { 2.0F, 4.5F, 6.7F };

 

struct Circle *p = &c; /* address of c into p */

 

#include <stdio.h>

int main()

{

     printf("Radius using dot operator= %f", c.radius);

     printf("\nRadius using arrow operator = %f", p->radius);

     getchar();

     return 0;

}

 

 

The [ ] and ( ) Operators:

Parentheses () are operators that increase the precedence of the operations inside them. For example,

int a,b,c,d,e;

a =2;

b=3;

c=4;

d=5;

e = ((a+b)*(c+d))*c;

Here expression (a+b) and (c+d) are calculated first then ((a+b)*(c+d)) and then ((a+b)*(c+d))*c;

 

Square brackets [ ] perform array indexing. Given an array, the expression within square brackets provides an index into that array.

For example:

// example using [] operator

#include <stdio.h>

int main(void)

{

     char pi[10] = {`3`,`.`,`1`,`4`,`1`,`5`,`2`,`9`,`6`,`\0`};

     printf("%s", pi);

     printf("\n");

     printf("%c", pi[1]);

     printf("\n");

     printf("%c", pi[9]);

     getchar();

     return 0;

}

 

 

operators list with Precedence :

Highest

( )     [ ]     –>     .

 

!     ~     ++     --     -     (type)     *     &     sizeof

 

*     /     %

 

+     -

 

<<     >>

 

<     <=     >     >=

 

==     !=

 

&

 

^

 

|

 

&&

 

||

 

?:

 

=     +=     –=     *=     /= etc.

Lowest

,

 

 

List of operators in C

 c tutorials |  Admin

Arithmetic operators

Operator Name

Syntax

Basic assignment

a = b

Addition

a + b

Subtraction

a - b

Unary plus

+a

Unary minus

-a

Multiplication

a * b

Division

a / b

Modulo (integer remainder)

a % b

Increment (Prefix)

++a

Increment (Postfix)

a++

Decrement (Prefix)

++a

Decrement (Postfix)

a++

Comparison operators/relational operators

Operator Name

Syntax

Equal to

a == b

Not equal to

a != b

Greater than

a > b

Less than

a < b

Greater than or equal to

a >= b

Less than or equal to

a <= b

Logical operators

Operator Name

Syntax

Logical negation (NOT)

!a

Logical AND

a && b

Logical OR

a || b

Bitwise operators

Operator Name

Syntax

Bitwise NOT

~a

Bitwise AND

a & b

Bitwise OR

a | b

Bitwise XOR

a ^ b

Bitwise left shift

a << b

Bitwise right shift

a >> b

Compound assignment operators

Operator Name

Syntax

Addition assignment

a += b

Subtraction assignment

a -= b

Multiplication assignment

a *= b

Division assignment

a /= b

Modulo assignment

a %= b

Bitwise AND assignment

a &= b

Bitwise OR assignment

a |= b

Bitwise XOR assignment

a ^= b

Bitwise left shift assignment

a <<= b

Bitwise right shift assignment

a >>= b

Member and pointer operators

Operator Name

Syntax

Subscript

a[b]

Indirection("object pointed to by a")

*a

Address-of ("address of a")

&a

Structure dereference("member b of object pointed to by a")

a->b

Structure reference ("member b of object a")

a.b

Other operators

Operator Name

Syntax

Function call

a(a1, a2)

Comma

a, b

Ternary conditional

a ? b : c

Sizeof

sizeof(a) or sizeof(type)

Alignof (since C++11)

alignof(type) or or _Alignof(type)

Conversion (C-style cast)

(type)a

 

Storage Class Specifiers

 c tutorials |  Admin

There are 4 types of storage classes.

 1) extern

 2) static

 3) register

 4) auto


These are used to tell the compiler that how to store a variable in memory.

Syntax:           storageClass type var;


extern:

“The meaning of extern keyword is that an object is defined with external linkage elsewhere in the program. “

 

There are 3 types of linkage,

 1) external

 2) internal

 3) none

 

Global variables and functions have external linkage. They can be accessed from all files throughout a program. 

 

While global variables and functions declared as static have internal linkage. These can only be accessed within the file in which they are declared.

 

Local variables are the examples of none type linkage because they exist only in the block in which they are defined.

 

For example:

//example using extern
#include <stdio.h>
int main(void)
{
            
extern int var1, var2; /* use global vars */

            printf("%d %d", var1, var2);

            getchar();
            
return 0;
}
/*global definition of first and last */
int var1 = 100, var2 =200;


In the above example, variables var1, var2 are used with
external keyword to show the compiler that these are global variables and defined elsewhere in the program. Here elsewhere means either they may be defined in the same file or may be in another file.

 

It means extern keyword can also be used to declare a variable without defining it. But if it is not defined anywhere else in program compiler can show error. So it is also need to keep in mind that we must define the variable.

 

extern can also be applied to a function declaration, but doing so is redundant, because all functions are by default extern.   

 

Another Example using extern:

//file1.c
int ig1,ig2;
char ic;
int main(void)
{
            /* . . . */
}
void func1(void)
{

        ig1 = 123;
}

// file2.c
extern int ig1, ig2;
extern char ic;
void func2(void)
{    

  ig1 = ig2 / 10;
}
void func3(void)
{      

  ig2 = 10;
}

In the above example global variables ig1,ig2 and ic are used in another file using extern keyword.

 

static:

As discussed earlier, static variables and static functions are examples of internal linkage. They can’t be accessed outside of the file or block in which they are defined, also they keep their existence in their file or block.

 

For example, static global variables can be used in a file to protect it from changing its value from another file throughout the program.

 

Example:

// example using static Local

int func(void)

{

            static int static_num = 0;

            static_num = static_num + 10;

            return static_num;

}

 

#include <stdio.h>

int main()

{

            int s1 = func();

            int s2 = func();

 

            printf("%d %d", s1, s2);

            getchar();

            return 0;

}

 

// example using static Global

#include <stdio.h>

static float static_pi = 3.1415;

float getCircleArea(float radius);

 

float getCircleArea(float radius)

{

            float area = static_pi*radius*radius;

            return area;

}

 

int main()

{

            float a1 = getCircleArea(1.5);

            float a2 = getCircleArea(1.6);

            float a3 = getCircleArea(1.7);

            printf("%f %f %f", a1, a2, a3);

            return 0;

}

 

In above the example first shows a program using static local variable (static_num), used in the function func and this function is called 2 times in the program with storing its return value to s1 and s2 integer variables. In the first call of function func static integer local variable (static_num) is initialized with a zero value and then it is incremented with the value 10. On time of second call it will not defined and initialized again with zero because it is used as static (it is already in the memory that is permanent until the program stop) and so it will jump to next statement and again incremented with value 10. So the output will be 10 20.

 

In the second, the value of mathematical constant pi is taken into a static float global variable (static_pi) and used to calculate area of a circle of given radius. We can use this variable in this file anywhere but cannot use it in any other file.

 

register:

The register specifier specifies that the variable is stored in the register of the CPU not in the memory, where normal variables are stored. So operations on a register variable can be much faster than on a normal variable because the register variable was actually held in the CPU and did not require a memory access to determine or modify its value.

 

This keyword mostly used with of type int, char or pointer type. 

 

Example:

Type Qualifiers

 c tutorials |  Admin

A type qualifier is applied just before a type to make a new qualified type.

For example before int, if we add const (a type qualifier) the type const int will represent a constant integer datatype. And so an object defined with type const int can only initialized but may not be changed throughout the program.

Type qualifiers is used to controls the variable in a manner that how it is accessed or modified.

Type qualifiers have 3 types:

 1) const

 2) volatile

 3) restrict

[Note: third one (restrict) is available in only c99 and above compiler versions.]

const:

As before discussed variable of const type may not be changed throughout the program. These variable stored in Read Only Memory. Also we must initialize with the definition.

For example:

const float pi = 3.1415; is OK

but we cannot write

const float pi;

pi = 3.1415;

is wrong because pi is redefined here. When we declare a variable it automatically assigned with some garbage value.

More examples:

const char exp = ‘E’;

const int ten = 10;

etc.

volatile:

This qualifier indicates that the value of a variable of volatile type may be changed between different accesses, even if it is not modified in the program.

 

or

 

A volatile type variable’s value may be changed in a way not explicitly specified by the program.

 

For example, if 0x56 is assumed to be the value of a port that can be changed by external conditions only, then below declaration would prevent any possibility of accidental side effects:

const volatile char *port = (const volatile char *)  0x56;

 

restrict:

restrict keyword basically used with pointers declaration.

restrict keyword says to compiler that only the pointer itself or a value directly derived from it, will be used to access the object to which it points.

 

The Basic Data Types

 c tutorials |  Admin

 

Data type`s keyword

Data type

char

character

int

integer

float

floating-point

double

double floating-point

void

valueless

Five foundational data types of C language:

 

These types are the basic data types in C language. The size and range of these datatype depends on processor and compiler used.

For example: In 16 bit environments, such as DOS or Windows 3.1, an int is 16 bits. For most 32-bit environments, such as Windows 95/98/NT/2000, an int is 32 bits.

[Note: C99 and above versions also have three more datatype: _Bool, _Complex, and _Imaginary.]

 

 

Type Modifiers in C language:

Type Modifiers are of 4 types:

 1) signed

 2) unsigned

 3) long

 4) short

These type modifiers can be used with the basic datatype to make a new type with modified size/range.

For example: unsigned char, unsigned int, long float etc.

unsigned char has same size (1 byte) as char but range starts with 0 and ends with 255 while char starts with -128 and end with 127.

Note that some combinations are not allowed as they have not any meaning. For example, long and short cannot be used with char. Similarly signed and unsigned cannot be used with float and double. Also short cannot be used with float and double but long can be used.

When a type modifier is used by itself alone (means when it does not precede a basic type), then it is assumed as int. See below table.

 

Specifier

Same As

signed

signed int

unsigned

unsigned int

long

long int

short

short int

 

Here a simple code is given to print data type`s size and range.  Right shift is used for calculating powers of 2 to get range and `sizeof` operator is used for calculation of size.