Skip to main content

Programming in C

Amu_Ke_Fundye

Programming in C


Programming in C:

  • All C programs must have a function in it called main
  • Execution starts in function main
  • C is case sensitive
  • Comments start with /* and end with */. Comments may span over many lines.
  • C is a “free format” language
  • All C statements must end in a semicolon (;).
  • The #include <stdio.h> statement instructs the C compiler to insert the entire contents of file stdio.h in its place and compile the resulting file.
Character Set: The characters that can be used to form words, numbers and expressions depend upon the computer on which the program runs. The characters in C are grouped into the following categories: Letters, Digits, Special characters and White spaces.
C Tokens: The smallest individual units are known as C tokens. C has five types of tokens: Keywords, Identifiers, Constants, Operators, and Special symbols.
  • Keywords: All keywords are basically the sequences of characters that have one or more fixed meanings. All C keywords must be written in lowercase letters.
    • Example: break, char, int, continue, default, do etc.
  • Identifiers: A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9).
  • Constants: Fixed values that do not change during the execution of a C program.
    • Example: 100 is integer constant, ‘a’ is character constant, etc.
  • Operators: Operator is a symbol that tells computer to perform certain mathematical or logical manipulations.
    • Example: Arithmetic operators (+, -, *, /), Logical operators, Bitwise operators, etc.
  • Delimiters / Separators: These are used to separate constants, variables and statements.
    • Example: comma, semicolon, apostrophes, double quotes, blank space etc.
  • Strings: String constants are specified in double quotes.
    • Example: “gateexam” is string constant

Variable:

  • A variable is nothing but a name given to a storage area that our programs can manipulate.
  • Each variable in C has a specific type, which determines the size and layout of the variable’s memory.
  • The range of values that can be stored within that memory and the set of operations that can be applied to the variable.

Data Types

A data type in a programming language is a set of data with values having predefined characteristics such as integers and characters.
img-1

Different Types of Modifier with their Range:

img-1

Types of Operators:

  • Arithmetic operators (+, -, *, /, %, ++, –)
  • Assignment operator (=, +=, -=, *=, etc)
  • Relational operators (<, <=, >, >=, !=, ==)
  • Logical operators (&&, ||, !)
  • Bitwise operators (&, |, ~, ^, <<, >>)
  • Special operators (sizeof(), ternary operators)
  • Pointer operators (* – Value at address (indirection), & – Address Operator)

Type Conversions

  • Implicit Type Conversion: There are certain cases in which data will get automatically converted from one type to another:
    • When data is being stored in a variable, if the data being stored does not match the type of the variable.
    • The data being stored will be converted to match the type of the storage variable.
    • When an operation is being performed on data of two different types. The “smaller” data type will be converted to match the “larger” type.
      • The following example converts the value of  x to a double precision value before performing the division. Note that if the 3.0 were changed to a simple 3, then integer division would be performed, losing any fractional values in the result.
        • average = x / 3.0;
    • When data is passed to or returned from functions.
  • Explicit Type Conversion: Data may also be expressly converted, using the typecast operator.
    • The following example converts the value of x to a double precision value before performing the division. ( y will then be implicitly promoted, following the guidelines listed above. )
      • average = ( double ) x / y;
      • Note that x itself is unaffected by this conversion.

Expression:

  • lvalue: 
    • Expressions that refer to a memory location are called “lvalue” expressions.
    • An lvalue may appear as either the left-hand or right-hand side of an assignment.
    • Variables are lvalues and so they may appear on the left-hand side of an assignment
  • rvalue: 
    • The term rvalue refers to a data value that is stored at some address in memory.
    • An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
    • Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side.

C Flow Control Statements

Control statement is one of the instructions, statements or group of statement in a programming language which determines the sequence of execution of other instructions or statements. C provides two styles of flow controls.
  1. Branching (deciding what action to take)
  2. Looping (deciding how many times to take a certain action)
If Statement: It takes an expression in parenthesis and a statement or block of statements. Expressions will be assumed to be true, if evaluated values are non-zero.
Syntax of if Statement:
(i)
if (condition) statement
(ii)
if (condition)
{
statement1
statement2
:
}
(iii)
if (condition)
{ statements }
else
{ statements }
The switch Statement: The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed:
switch (control variable)
{
case constant-1: statement(s); break;
case constant-2: statement(s); break;
:
case constant-n: statement(s); break;
default: statement(s);
}
The Conditional Operators (? : ): The ? : operators are just like an if-else statement except that because it is an operator we can use it within expressions. ? : are a ternary operators in that it takes three values. They are the only ternary operator in C language.
flag = (x < 0) ? 0 : 1;
This conditional statement can be evaluated as following with equivalent if else statement.
 if (x < 0) flag = 0;
 else flag = 1;
Loop Control Structure : Loops provide a way to repeat commands and control. This involves repeating some portion of the program either a specified numbers of times until a particular condition is satisfied.
  • while Loop:
initialize loop counter;
while (test loop counter using a condition/expression)
 {
      <Statement1>
      <Statement2>
       …
       < decrement/increment loop counter>
 }
  • for Loop:
for (initialize counter; test counter; increment/decrement counter)
 {
        <Statement1>
        <Statement2>
        …
 }
  • do while Loop:
initialize loop counter;
do
{
         <Statement1>
        <Statement2>
        …
}
while (this condition is true);
Example: Print numbers from 1 to 5 using for loop
#include <stdio.h>

int main()
{
int counter;
for(counter=1; counter <= 5; counter++) //loop 5 times
{  printf("%d ", counter);  }
return 0;
}
  • The break Statement: The break statement is used to jump out of a loop instantly, without waiting to get back to the conditional test.
  • The continue Statement: The ‘continue’ statement is used to take the control to the beginning of the loop, by passing the statement inside the loop, which have not yet been executed.
  • goto Statement: C supports an unconditional control statement, goto, to transfer the control from one point to another in a C program.

C Variable Types

A variable is just a named area of storage that can hold a single value. There are two main variable types: Local variable and Global variable.
  • Local Variable: Scope of a local variable is confined within the block or function, where it is defined.
  • Global Variable: Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.
Global variables are initialized automatically by the system when we define them. If same variable name is being used for global and local variables, then local variable takes preference in its scope.

Storage Classes in C

  • A variable name identifies some physical location within the computer, where the string of bits representing the variable’s value, is stored.
  • There are basically two kinds of locations in a computer, where such a value maybe kept: Memory and CPU registers.
  • It is the variable’s storage class that determines in which of the above two types of locations, the value should be stored.
We have four types of storage classes in C: Auto, Register, Static and Extern.
1. Auto Storage Class: Features of this class are given below.
  • Storage Location Memory
  • Default Initial Value Garbage value
  • Scope Local to the block in which the variable is defined.
  • Life Till the control remains within the block in which variable is defined.
Auto is the default storage class for all local variables.
2. Register Storage Class: Register is used to define local variables that should be stored in a register instead of RAM. Register should only be used for variables that require quick access such as counters. Features of register storage class are given below.
  • Storage Location CPU register
  • Default Initial Value Garbage value
  • Scope Local to the block il) which variable is defined.
  • Life Till the control remains within the block in which the variable is defined.
3. Static Storage Class: Static is the default storage class for global variables. Features of static storage class are given below.
  • Storage Location Memory
  • Default Initial Value Zero
  • Scope Local to the block in which the variable is defined. In case of global variable, the scope will be through out the program.
  • Life Value of variable persists between different function calls.
4. Extern Storage Class: Extern is used of give a reference of a global variable that is variable to all the program files. When we use extern, the variable can’t be initialized as all it does, is to point the variable name at a storage location that has been previously defined.
  • Storage Location: Memory
  • Default Initial Value: Zero
  • Scope: Global
  • Life: As long as the program’s execution does not come to an end.
Operator Precedence Relations: Operator precedence relations are given below from highest to lowest order:
img-1
Example: Displaying a character ‘A’ and its ASCII value.
#include <stdio.h>
int main()
{
char first_letter;
first_letter = ‘A’;
printf("Character %c\n", first_letter); //display character
printf("ASCII value %d\n", first_letter); //display ASCII value
return 0;
}

Functions

  • A function in C can perform a particular task, and supports the concept of modularity.
  • A function is a self-contained block of statements that perform a coherent task of some kind.
  • Making function is a way of isolating one block of code from other independent blocks of code.
Syntax of Function Definition:
return_data_type function_name (data_type variable1, data_type variable2, … )
{
         function_body
}
function definition in C programming consists of a function header and a function body.
  • Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions may perform the desired operations without returning a value. In this case, the return_type is the keyword void.
  • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
  • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
  • Function Body: The function body contains a collection of statements that define what the function does.
Syntax of Function Declaration:
return_type function_name( parameter list );
A function declaration tells the compiler about a function name and how to call the function.
Example-1: Multiplication of two numbers using function
#include <stdio.h>
int multiplication(int, int); //function declaration (prototype)
int multiplication(int x, int y) 
{ x = x * y; return x; } //function definition 
int main() 
{ 
   int i, j, k; 
   scanf("%d%d",&i, &j);
   k = multiplication(i, j); // function call
   printf("%d\n", k); 
   return 0; 
}
Example-2: Program to calculate factorial of given number
#include <stdio.h>
void factorial( int );    /* ANSI function prototype */
void factorial( int n )
{
    int  i, factorial_number = 1;
    for( i = 1; i <= n; ++i )
      factorial_number *= i;
    printf("The factorial of %d is %d\n", n, factorial_number );
}

main()
{
 int  number = 0;
 printf("Enter a number\n");
 scanf("%d", &number );
 factorial( number );
}
There are 4 types of functions based on return type:
  1. Function with arguments but no return value
  2. Function with arguments and return value
  3. Function without arguments and no return value
  4. Function without arguments but return value.
While calling a function in C program, there are two ways in which arguments can be passed to a function.
  • Call by Value: If we pass values of variables to the function as parameters, such kind of function calling is known as call by value.
  • Call by Reference: Variables are stored somewhere in memory. So, instead of passing the value of a variable, if we pass the location number / address of the variable to the function, then it would become ‘a call by reference’.
A function can call itself such a process is called recursion.
Functions can be of two types: (i) Library functions, and (ii) User-defined functions

Pointers

A pointer is a variable that stores memory address. Like all other variables, it also has a name, has to be declared and occupies some spaces in memory. It is called pointerbecause it points to a particular location.
  •  ‘&’ =Address of operator
  •  ‘*’ = Value at address operator or ‘indirection’ operator
  • &i returns the address of the variable i.
  • *(&i) return the value stored at a particular address printing the value of *(&i) is same as printing the value of i.
Pointers are useful due to  following reasons:
  • They enable us to access a variable that is defined outside a function.
  • Pointers are more efficient in handling data tables and sometimes even arrays.
  • Pointers tend to reduce the length and complexity of a program.
  • They increase the execution speed.
  • Use of pointers allows easy access to character strings.
NOTE:
  • int *p; /* p is going to store address of integer value (size of memory is 2 bytes) */
  • float *q; /* q is going to store address of floating value (size of memory is 2 bytes) */
  • char *ch; /*ch is going to store address of character variable (size of memory is 2 bytes) */
Pointer Declaration: data-type *pointer-name;
NULL Pointers: Uninitilized pointers start out with random unknown values, just like any other variable type.
  • Accidentally using a pointer containing a random address is one of the most common errors encountered when using pointers, and potentially one of the hardest to diagnose, since the errors encountered are generally not repeatable.
Example: Program to swap two integer numbers using pointers.
#include <stdio.h>
void swap(int *a,int *b);
int main()
{
   int a,b;
   a = 5;
   b = 10;
   printf("\nBefore swapping a= %d: b= %d", a, b);
   swap(&a, &b); //call function
   printf("\nAfter swapping a= %d: b= %d", a, b);
   return 0;
}

void swap(int *a, int *b)
{
   int x;
   x = *b;
   *b = *a;
   *a = x;
}

Pointers and Strings:

An array of characters is called a string. Strings in C are handled differently than most other languages. A pointer is used to keep track of a text string stored in memory. It will point to the first character of the string. By knowing the beginning address and the length of the string, the program can locate it.
  • Example: char *a; a = “Hello World!”;
Constant pointer: A pointer is said to be constant pointer when the address its pointing to cannot be changed.
  • Syntax: <type-of-pointer> *const <name-of-pointer>
  • Example: int * const p;
C Pointer to Constant: This type of pointer cannot change the value at the address pointed by it.
  • Syntax: const <type-of-pointer> *<name-of-pointer>;
  • Example: const int * p;
Pointer to Pointer: It is a special pointer variable that can store the address of an other pointer variable. This means that its perfectly legal for a pointer to be pointing to another pointer.
  1. Syntax: <type-of-pointer> ** <name-of-pointer>;
  2. Example: int **p;
Array of Pointers: An array of pointers can be declared as follows.
  • Declaration Syntax: <type> *<name>[<number-of-elements];
  • Example: int *p[3];
Pointer to an Array: Pointer to an array can be declared as follows.
  • Declaration Syntax: <type> (*<name>) [<number-of-elements];
  • Example: int (*p)[3];
Function Pointers: Function pointer is same as pointer to a function.
  • Syntax: <return type of function> (*<name of pointer>) (type of function arguments);
  • Example: int (*f)(int, int); //declaration .
Combinations of * and ++
  • *p++ accesses the thing pointed to by p and increments p
  • (*p)++ accesses the thing pointed to by p and increments the thing pointed to by p
  • *++p increments p first, and then accesses the thing pointed to by p
  • ++*p increments the thing pointed to by p first, and then uses it in a larger expression.

Pointer Operations:

  • Assignment: You can assign an address to a pointer. Typically, you do this by using an array name or by using the address operator (&).
  • Value finding (dereferencing): The * operator gives the value stored in the pointed-to location.
  • Taking a pointer address: Like all variables, pointer variables have an address and a value. The & operator tells you where the pointer itself is stored.
  • Adding an integer to a pointer: You can use the + operator to add an integer to a pointer or a pointer to an integer. In either case, the integer is multiplied by the number of bytes in the pointed-to type, and the result is added to the original address.
  • Incrementing a pointer: Incrementing a pointer to an array element makes it move to the next element of the array.
  • Subtracting an integer from a pointer: You can use the – operator to subtract an integer from a pointer; the pointer has to be the first operand or a pointer to an integer. The integer is multiplied by the number of bytes in the pointed-to type, and the result is subtracted from the original address.
  • Note that there are two forms of subtraction. You can subtract one pointer from another to get an integer, and you can subtract an integer from a pointer and get a pointer.
  • Decrementing a pointer: You can also decrement a pointer. In this example, decrementing ptr2 makes it point to the second array element instead of the third. Note that you can use both the prefix and postfix forms of the increment and decrement operators.
  • Subtraction: You can find the difference of two pointers. Normally, you do this for two pointers to elements that are in the same array to find out how far apart the elements are. The result is in the same units as the type size.
  • Comparisons: You can use the relational operators to compare the values of two pointers, provided the pointers are of the same type.

Problems with Pointers:

  • Assigning Value to Pointer Variable
  • Assigning Value to Uninitialized Pointer
  • Not de-referencing Pointer Variable (forgetting to use * before vaiable)
  • Assigning Address of Un-initialized Variable
  • Comparing Pointers that point to different objects
  • Dangling pointers (Using free or de-allocating memory or out of scope)

Regards
Amrut Jagdish Gupta

Comments

Popular posts from this blog

Undecidability

Amu_Ke_Fundye Undecidability Decidable Problem If there is a Turing machine that decides the problem, called as Decidable problem. A decision problem that can be solved by an algorithm that halts on all inputs in a finite number of steps. A problem is decidable, if there is an algorithm that can answer either yes or no. A language for which membership can be decided by an algorithm that halts on all inputs in a finite number of steps. Decidable problem is also called as totally decidable problem, algorithmically solvable, recursively solvable. Undecidable Problem A problem that cannot be solved for all cases by any algorithm whatsoever. Equivalent Language cannot be recognized by a Turing machine that halts for all inputs. The following problems are undecidable problems: Halting Problem:  A halting problem is undecidable problem. There is no general method or algorithm which can solve the halting problem for all possible inputs. Emptyness Problem:...

ALU and Data Path

Amu_Ke_Fundye ALU and Data Path The CPU can be divided into a data section and a control section. The   data section , which is also called the   datapath. Datapath The registers, the ALU, and the interconnecting bus are collectively referred to as the datapath.  Each bit in datapath is functionally identical.  The datapath is capable of performing certain operations on data items. The  control section  is basically the  control unit ,  which issues control signals to the datapath . Bus : A Bus is a collection of wires or distinct lines meant to carry data, address and control information. Data Bus : it is used for transmission of data. The number of data lines corresponds to the number of bits in a word. Address Bus : it carries the address of the main memory location from where the data can be accessed. Control Bus : it is used to indicate the direction of data transfer and to coordinate the timing of ...

Funny Shortcut to Remember Periodic Table

Amu_Ke_Fundye Funny Shortcut to Remember Periodic Table THE PERIODIC TABLE The periodic table is a tabular display of the chemical elements, organized on the basis of their atomic number's , electron configurations, and chemical properties.In order to appreciate the general trends in chemistry and to explain the deviations of some from these general trends we need to to have good knowledge about the position of those elements in periodic table. This knowledge is also extremely important for competitive exams. So, here I present a way to memorize this using some funny easy shortcut sentences. THE FIRST 18 ELEMENTS (H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar)  H ie  He   Li es  Be cause  B oron  C an N ot  O xide  Fl orine.. N e w  Na tions  M ight  Al so  Si ng  P eaceful  S ong  Cl early  A gain  THE ...