Programming principles and Algoritham

Unit 1 –Introduction to ‘C’ Language

1. What is C?

  • C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972 by Dennis Ritchie.
  • Any programming Language can be divided in to two categories.
    • Problem oriented (High level language)
    • Machine oriented (Low level language)

But C is considered as a Middle level Language.

  • C is modular, portable, reusable.

2. Feature of C Program

  • Structured language
    • It has the ability to divide and hide all the information and instruction.
    • Code can be partitioned in C using functions or code block.
    • C is a well structured language compare to other.
  • General purpose language
    • Make it ideal language for system programming.
    • It can also be used for business and scientific application.
    • ANSI established a standard for c in 1983.
    • The ability of c is to manipulate bits,byte and addresses.
    • It is adopted in later 1990.
  • Portability
    • Portability is the ability to port or use the software written .
    • One computer C program can be reused.
    • By modification or no modification.
  • Code Re-usability & Ability to customize and extend
    • A programmer can easily create his own function
    • It can can be used repeatedly in different application
    • C program basically collection of function
    • The function are supported by ‘c’ library
    • Function can be added to ‘c’ library continuously
  • Limited Number of Key Word
    • There are only 32 keywords in ‘C’
    • 27 keywords are given by ritchie
    • 5 is added by ANSI
    • The strength of ‘C’ is lies in its in-built function
    • Unix system provides as large number of C function
    • Some function are used in operation .
    • Other are for specialized in their application

3. C program structure

pre-processor directives

global declarations

main()

{

    local variable deceleration

    statement sequences

    function invoking

}

4. C Keywords

Keywords are the words whose meaning has already been explained to the C compiler. There are only 32 keywords available in C. The keywords are also called ‘Reserved words’.

auto        double      int         struct

break       else        long        switch

case        enum        register    typedef

char        extern      return      union

const       float       short       unsigned

continue    for         signed      void

default     goto        sizeof      volatile

do          if          static      while

5. C Character Set

A character denotes any alphabet, digit or special symbol used to represent information. Following are the valid alphabets, numbers and special symbols allowed in C.

  • Alphabets – A, B, ….., Y, Z a, b, ……, y, z
  • Digits – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • Special symbols – ~ ‘ ! @ # % ^ & * ( ) _ – + = | \ { }
    [ ] : ; ” ‘ < > , . ? /

6. Rules for Writing, Compiling and Executing the C program

  • C is case sensitive means variable named “COUNTER” is different from a variable named “counter”.
  • All keywords are lowercased.
  • Keywords cannot be used for any other purpose (like variable names).
  • Every C statement must end with a ;. Thus ;acts as a statement terminator.
  • First character must be an alphabet or underscore, no special symbol other than an underscore, no commas or blank spaces are allowed with in a variable, constant or keyword.
  • Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
  • Variable must be declared before it is used in the program.
  • File should be have the extension .c
  • Program need to be compiled before execution.

7. Data types & Placeholders

  • C has 5 basic built-in data types.
  • Data type defines a set of values that a variable can store along with a set of operations that can be performed on it.
  • A variable takes different values at different times.
  • General form for declaring a variable is:
    type name;
  • An example for using variables comes below:

#include<stdio.h>

main()

{

    int sum;

    sum=12;

    sum=sum+5;

    printf(“Sum is %d”,sum);

}

printf function will print the following:
Sum is 17
In fact %d is the placeholder for integer variable value that its name comes after double quotes.

  • Common data types are:
    • int – integer
    • char – character
    • long – long integer
    • float – float number
    • double – long float
  • Other placeholders are:

Placeholders        Format

%c                  Character

%d                  Signed decimal integer

%i                  Signed decimal integer

%e                  Scientific notation[e]

%E                  Scientific notation[E]

%f                  Decimal floating point

%o                  unsigned octal

%s                  String of character

%u                  unsigned decimal integer

%x                  unsigned Hexadecimal (lower)

%X                  unsigned Hexadecimal (upper)

%p                  dispaly a pointer

%%                  print a %

8. Control characters (Escape sequences)

Certain non printing characters as well as the backslash () and the apostrophe(‘), can be expressed in terms of escape sequence.

  • \a – Bell
  • \n – New line
  • \r – Carriage return
  • \b – Backspace
  • \f – Formfeed
  • \t – Horizontal tab
  • \” – Quotation mark
  • \v – Vertical tab
  • \’ – Apostrophe
  • \\ – Backslash
  • \? – Question mark
  • \0 – Null

9. Receiving input values from keyboard

scanf function used to receiving input from keyboard.
General form of scanf function is :

scanf(“Format string”,&variable,&variable,…);

Format string contains placeholders for variables that we intend to receive from keyboard. A & sign comes before each variable name that comes in variable listing. Character strings are exceptions from this rule. They will not come with this sign before them.

Note: You are not allowed to insert any additional characters in format string other than placeholders and some special characters. Entering even a space or other undesired character will cause your program to work incorrectly and the results will be unexpected. So make sure you just insert placeholder characters in scanf format string. The following example receives multiple variables from keyboard.

float a;

int n;

scanf(“%d%f”,&n,&a);

Unit-2

Expression & Operators Precedence – C Programming

DESCRIPTION OPERATORS ASSOCIATIVITY
Function Expression () Left to Right
Array Expression [] Left to Right
Structure Operator -> Left to Right
Structure Operator . Left to Right
Unary minus Right to Left
Increment/Decrement ++, — Right to Left
One’s compliment ~ Right to Left
Negation ! Right to Left
Address of & Right to Left
Value of address `*` Right to Left
Type cast (type) Right to Left
Size in bytes sizeof Right to Left
Multiplication `*` Left to Right
Division / Left to Right
Modulus % Left to Right
Addition + Left to Right
Subtraction Left to Right
Left shift <<  Left to Right
Right shift >>  Left to Right
Less than Left to Right
Less than or equal to <= Left to Right
Greater than Left to Right
Greater than or equal to >= Left to Right
Equal to == Left to Right
Not equal to != Left to Right
Bitwise AND & Left to Right
Bitwise exclusive OR ^ Left to Right
Bitwise inclusive OR | Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
Assignment =, *=, /=, %=, +=, -=, &=, ^=, |=, <<=, >>= Right to Left
Comma , Right to Left

 Console based I/O and related I/-

Input means to provide the program with some data to be used in the program and Output means to display data on screen or write the data to a printer or a file.

C programming language provides many built-in functions to read any given input and to display data on screen when there is a need to output the result.

In this tutorial, we will learn about such functions, which can be used in our program to take input from user and to output the result on screen.

All these built-in functions are present in C header files, we will also specify the name of header files in which a particular function is defined while discussing about it.


scanf() and printf() functions

The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.

#include<stdio.h>
 
void main()
{
    // defining a variable
    int i;
    /* 
        displaying message on the screen
        asking the user to input a value
    */
    printf("Please enter a value...");
    /*
        reading the value entered by the user
    */
    scanf("%d", &i);
    /*
        displaying the number as output
    */
    printf( "\nYou entered: %d", i);
}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered on screen.

You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is known as format string and this informs the scanf() function, what type of input to expect and in printf() it is used to give a heads up to the compiler, what type of output to expect.

Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning ends at whitespace.

We can also limit the number of digits or characters that can be input or output, by adding a number with the format string specifier, like "%1d" or "%3s", the first one means a single numeric digit and the second one means 3 characters, hence if you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case for output.

In C Language, computer monitor, printer etc output devices are treated as files and the same process is followed to write output to these devices as would have been followed to write the output to a file.

NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of characters read by it.

int i = printf("studytonight");

In this program printf("studytonight"); will return 12 as result, which will be stored in the variable i, because studytonight has 12 characters.

getchar() & putchar() functions

The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. You can use this method in a loop in case you want to read more than one character. The putchar() function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time. In case you want to display more than one characters, use putchar() method in a loop.

#include <stdio.h>

void main()
{
    int c;
    printf("Enter a character");
    /*
        Take a character as input and 
        store it in variable c
    */
    c =getchar();
    /*
        display the character stored 
        in variable c 
    */
    putchar(c);
}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.

gets() & puts() functions

The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function writes the string str and a trailing newline to stdout.

str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not able to understand this now.)

#include<stdio.h>

void main()
{
    /* character array of length 100 */
    char str[100];
    printf("Enter a string");
    gets( str );
    puts( str );
    getch();
}

When you will compile the above code, it will ask you to enter a string. When you will enter the string, it will display the value you have entered.

Difference between scanf() and gets()

The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as character too.

If you enter name as Study Tonight using scanf() it will only read and store Study and will leave the part after space. But gets() function will read it completely.

Header Files in C

Header files contain definitions of functions and variables, which is imported or used into any C program by using the pre-processor #include statement. Header file have an extension “.h” which contains C function declaration and macro definition.

header files in c

Each header file contains information (or declarations) for a particular group of functions. Like stdio.h header file contains declarations of standard input and output functions available in C which is used for get the input and print the output. Similarly, the header file math.h contains declarations of mathematical functions available in C.

Types of Header Files in C

  • System Header Files: It is comes with compiler.
  • User header files: It is written by programmer.

Why need of header files

When we want to use any function in our c program then first we need to import their definition from c library, for importing their declaration and definition we need to include header file in program by using #include. Header file include at the top of any C program.

For example if we use printf() in C program, then we need to include, stdio.h header file, because in stdio.h header file definition of printf() (for print message on screen) is written in stdio.h header file.

Syntax Header Files in C

             
#include<stdio.h>

How to use Header File in Program

Both user and system header files are include using the pre-processing directive #include. It has following two forms:

Syntax

#include<file>

This form is used for system header files. It searches for a file named file in a standard list of system directives.

Preprocessor Directives – 

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation (Proprocessor direcives are executed before compilation.). It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.

Preprocessing directives are lines in your program that start with #. The # is followed by an identifier that is the directive name. For example, #define is the directive that defines a macro. Whitespace is also allowed before and after the #.

The # and the directive name cannot come from a macro expansion. For example, if foo is defined as a macro expanding to define, that does not make #foo a valid preprocessing directive.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives :

  1. #include
  2. #define
  3. #undef
  4. #ifdef
  5. #ifndef
  6. #if
  7. #else
  8. #elif
  9. #endif
  10. #error
  11. #pragma

1. #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error. It has three variants:

#include <file>

This variant is used for system header files. It searches for a file named file in a list of directories specified by you, then in a standard list of system directories.

#include "file"

This variant is used for header files of your own program. It searches for a file named file first in the current directory, then in the same directories used for system header files. The current directory is the directory of the current input file.

#include anything else

This variant is called a computed #include. Any #include directive whose argument does not fit the above two forms is a computed include

2. Macro’s (#define)

Let’s start with macro, as we discuss, a macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.

Syntax

#define token value  

There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

1. Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

#define PI 3.1415  

Here, PI is the macro name which will be replaced by the value 3.14. Let’s see an example of Object-like Macros :

#include <stdio.h>  
#define PI 3.1415 
main() 
{  
   printf("%f",PI);  
}  

Output:

3.14000

2. Function-like Macros

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))    

Here, MIN is the macro name. Let’s see an example of Function-like Macros :

#include <stdio.h>  
#define MIN(a,b) ((a)<(b)?(a):(b))  
void main() {  
   printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
}  
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s