C Language

 

 


See the Below code Contents

Overview of C

Keyword, Constants, Variables and data types

  • C features
  • Character Set
  • Reserved Keywords
  • Identifiers
  • Constants (Two types)
    • Primary Constants
    • Secondary Constant
  • Escape sequence
  • Data types
  • Variables

Operations and Expressions

  • Header files
  • Command Statements
  • Operators

Functions

  • Predefined functions
    • stdio.h
    • ctype.h
    • math.h
    • string.h

Decision making, Branching and Looping

  • if
  • if..else
  • switch
  • while

Array

Pointer

File management


How C developed?

  • B Language(Basic Combined Programming Language [BCPL]) was modified by Dennis Ritchie and was implemented AT bell laboratory in year 1972.

Application

  • System OS
  • Mobile Programs
  • Game Programs

 Compiler

  • Windows
    • Microsoft – Visual Studio
    • Bortland   –  Turbo C, Turbo C++
  • Linux
    • Gcc compiler

C Features

  • High level structured language (using functions)
  • Fast and efficient
  • Build in functions
  • Programming task became simple
  • It has a 32 keywords
  • Highly Portable(Any kind of machine can run)
  • Case sensitivity

Character Set

  • Alphabets            –    A, B, …. Y, Z     a, b, …. y, z
  • Digits                  –    0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • Special symbols  –    ~ `! @ # $ %  ^ & * ( ) _ – + = | \ { } [ ] : ; ” ’ < > , . ? /
  • White space        –    Blank space, Horizontal tab, Carriage return, New line , Form feed.

Reserved Keywords

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • sizeof
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
    • void functions can’t return a value
  • volatile
  • while

Identifiers

  • Rules
    • Should not use keyword as a identifier
    • First letter should be English word
    • May use Uppercase and Lowercase letters
    • Can use _  underscore as a first letter of Identifier
    • Identifiers are case sensitive(below both identifiers are not same)
      • Ab  -valid identifier ab  -valid identifier
    •  Eg:
      • Valid Identifiers
        • Sum
        • basic_pay
        • a1
      •  Invalid Identfiers
        • 8a  – First letter should not be numbers
        • auto  – auto is a keyword

Constants (Two types : Primary, Secondary)

  • When the program execution time constants should not be change their value(A constant is an entity that doesn’t change)

Primary Constants

  • Numeric Constants (Three Types)
    • Integer or fixed point Constant (Three Types)
      • Decimal
        • Decimal constants  are 0 to 9 numbers
        • Integer constants are also called as Decimal constants
        • Eg
          • 86 , 94 , -133
      • Octal
        • Octal constants  are 0 to 7 numbers
        • First number should be ‘0
        • Eg
          • 0137 , -0567 , 034
      • Hexadecimal
        • Hexadecimal constants  are 0 to 9 and A to F
        • First number should be start with ‘0x’ or ‘0X’
        • Eg
          • 0X73A , 0x89FA
    • Real or floating point Constant (Two types)
      • floating points may contain  .  dot point.
      • Rules
        • Should use 0 to 9 numbers
        • Dot point may come front or back
        • Sign symbols should be put front of the float numbers
      • Eg
        • 537.36 , -158.77
      • Floating points are two types
        • Fractional form
          • dot points are consider as fractional forms
          •  Eg
            • -0.567 , .64 , 24.0
        • Exponential form
          • Rules
            • May use mantissa and exponent symbols
            • Should not use .dot point in exponent
            • Should have at-least one digit in   exponent
            • Eg
              • 0.2571e-5
                • mantissa – 0.2571
                • exponent – -5
  • Character Constant
    • Character constant are come with two single quotes ()
    • Eg
      • 'A'  – (ASCII-65)
      • 'O'  – (ASCII-48, EBCDIC-240)
      • 'a' – (ASCII-97, EBCDIC-129)
      • 'z'  – (ASCII-122, EBCDIC-269)
      • %  – (ASCII-37, EBCDIC-108)
  • String Constant
    • String constant are come with two double quotes ()
    • Eg
      • "ARUN"  – Valid
      • "2020"  – Valid
      • "A" – Valid
      • "ABC  – Invalid
      • 'sum'  – Invalid

Secondary Constant

  • Array
  • Pointer
  • structure
  • union
  • enum

Escape sequence

Escape sequence is a character constant or string constants, its a non graphical character or printable.

  • \a  – alarm character
  • \b  – back space

  • \f  – form feed
  • \n  – new line

  • \r – carriage return

 

  1. Carriage return is known as cartridge return and often shortened to CR, <CR> or return.
  2. It is a control character  or mechanism used to reset a device position to the beginning of a line of text.
  3. It is closed associate with the line feed and newline concepts.
  • \t  – horizontal tab

  • \v  – vertical tab
  • \\  – back slash
  • \?  – question mark
  • \'  – single quote
  • \"  – double quote
  • \000  – character representation \xbh  – character representation
  • \0  – nul character

Data types

  • Data types in any of the language means that what are the various type of data the variables can have in that particular language.
  • Whenever a variable is declared it becomes necessary to define data type that what will be the type of data that variable can hold.
  • char , int , float and double  are basic datatype
  • short , long , signed  and unsigned  are data type modifier (Qualifier)
  • Rules
    • Every variable should have any one of the following data type
Types bit Size Range
char (or) signed char 8 (1byte) -128 to 127
unsigned char 8 (1byte) 0 to 255
int (or) signed int 16 (2byte) -32,768 to 32,767
unsigned int 16 (2byte)  0 to 65,535
short int or signed short int 8 (1byte)  -128 to 127
unsigned short int 8 (1byte)  0 to 255
long int (or) signed long int 32 (4byte)  -2,147,483,648 to 2,147,483,647
unsigned long int 32 (4byte)  0 to 4,294,967,295
float 32 (4 byte) 3.4E-38 to 3.4E+38
double 64 (8 byte) 1.7E-308 to 1.7E+308
long double 80 (10 byte)  3.4E-4932 to 1.1E+4932

The various general types of data are:

  1. Number type data
    1. Integer Type
      • int
    2. Float type (three types)
      • float
      • double
      • long double
  2. Character type data
    • char
  3. String type data
  4. Boolean type data

 Variables

  • When the program execution time variable may be change their value.(A variable is an entity that does change)
  • Eg
    • Sum , average , basic_pay , basic-pay , A0  etc (valid variables)
  •  Declaring a variable
    • Rules
      • should be declare datatype of variable.
      • data types name should be declare data type’s
      • if declare multiple variable in single data type, separate each by  ,  operator
      • Every declaration should end with ;  semicolon
    • Syntax
      • datatype variable_1, variable_2, .....variable_n ;
      • Eg:
        • int a, b , c;      //here a,b, c are integer variables
        • float salary;    //here salary is a floating type variable.
    • Use of variable declaration
      • Compiler can allocate a memory when we declared data type variable
  • Variable Initializing
    • Syntax
      • datatype variable_name = initial value;
      • Eg: int sum = 1;
  • Assigning value to Variable (Assigning Operator = )
    • Syntax
      • Variable_name = value; Ex: x = 20;
      • variable_name = variable; Ex: y = x;
      • variable_name = expression; Ex:  z = x+y;
  • variable is associated with two types :
    • Data type : int , float , char , double , long , signed , unsigned , etc.
    • Storage class : automatic , static , extern , register

Header files (Two types)

  1. Predefined Header files
    • Syntax :  #include<file_name>  (Stored in Specified directories)
      • If a header file is included with in < >  then the compiler searches for the particular header file only with in the built in include path.
  2. User defined Header files
    • Syntax : #include “file_name”  (Stored in Locally saved programs)
      • If a header file is included with in  , then the compiler searches for the particular header file first in the current working directory,if not found then in the built in include path.

Command Statements

  • /* Commands */     // Commands in paragraph
  • // commands         // command in single line

Operators

  1. Arithmetic Operators
    • Unary Operators
      • Eg: +5 , -8 .
    • Binary  Operators
      • Eg
        • X = 5+6;  (Addition +  Operator)
        • X = 20-10;  (Subraction -  Operator
        • X = 5*3;  (Multiplication *  Operator)
        • X = 5/3;  (Division /  Operator)
        • X = 5%3;  (Modular %  Operator) -remainder
  2. Relational Operators
    • A>B;  (Greater than)
    • A<B;  (lesser than)
    • A>=B;  (Greater than equal to)
    • A<=B;  (Lesser than equal to)
    • A==B;  (equal to)
    • A!=B;  (not equal to)
  3. Logical Operator
    • A && B;  (AND)
    • A || B;  (OR)
    • !A=A;  (NOT)
  4. Increment and Decrements Operator
    • Increment Operator
      • ++x;  (pre increments)
      • x++;  (post increments)
        • Eg:
        • S++;    //    ++, as it is single machine instruction (INC) internally.(recommended)
        • S = S+1;     //     ++, as it wil take two machine cycle internally.(not recommended)
    • Decrements Operator
      • --x;  (pre Decrements)
      • x--;  (post Decrements)
  5. Short hand assignment Operators
  6. conditional operators (Ternary Operator)

syntax :  expression 1 ? expression 2 : expression 3;

  • Rule
    • if expression 1 is true then expression 2 is executed
    • else expression 1 is false then expression 3 is executed
  • Advantage : Using  ?:  reduce the number of line codes and improve the performance of application.
  • Example Invalid:In this below example this is an error in this line i>45? return(*P): return (*q);  We cannot use return keyword in the terenary operators.

     
  • Example Valid  : In this below example a  is lesser than b . so the b value
  • More examples :
    • Find largest number among 3 numbers using ternary operator

  1. Bit wise Operators (Can only used on integrals, no floats and doubles)
    • Bitwise logic
      • &     AND
      • |    OR
      • ^    XOR
      • ~    ONE’S COMPLEMENT (Unary Operator)

         
    • Bit-wise Shift
      • <<     LEFT SHIFT
      • >>  RIGHT SHIFT
    • Reference Videos:
      1. https://www.youtube.com/watch?v=d0AwjSpNXR
  2. Special Operators

Functions

  • A function cannot be defined inside the another function, but a function can be called inside a another function.
  • Functions cannot return more than one value at a time. because after returning a value the control is given back to calling function
  • Any function including  main()  can be called recursively.
  • C has two kind of functions
    • Pre – defined Library functions
      • stdio.h
      • math.h
      • string.h
      • conio.h
      • ctype.h
      • graphics.h
    • User –  defined functions
      • Function declaration syntax:  returntype function_name(type_1, type_2,....);
      • Function definition syntax:
      • Function call syntax :  function_name ();
      • Function passing arguments syntax:  function_name (arg_1, arg_2, ...);
        • Arguments (Two types)
          • formal arguments : Formal arguments or dummy arguments are comes in function definition.
          • actual arguments : Actual arguments are comes with arguments when function call.
      • Function Name : If two function are declared in a same name, it gives "Error: Multiple declaration of function_name())" .
      • Return value : A function can return floating point value, integer, decimal, Boolean,
      • Return statement :
        • A function may have any number of  return  statements each returning different values and each  return  statements will not occur successively.
        • Yes. If a function contains two  return  statements successively, the compiler will generate “Unreachable code” warnings

           
      • Return Type :
        • If a function return type is declared as  void  it cannot return any value
        • If return type for a function is not specified, The default return type for a function is int .
      • Type of User Defined functions
        • function with no arguments and no return value.
        • function with arguments and no return value.
        • function with arguments and return value.
        • function with no arguments and return value.
  • Functions Arguments : C can accept upto 127 maximum number of arguments in a function.
  • Calling functions ( A function can be called either call by value or call by reference)
    • call by value : Actual argument value is copied to formal arguments.
    • call by reference : Actual argument address is copied to formal arguments.
  • Advantage of functions
    • Using top-down modular programming.
    • User can understand easily when separate many function.
    • Reduce the code repetition.
    • Can change function into program.
    • Program testing is very simple.
  • Disadvantage of functions
    • Difficult to understand function structure.
    • Users can’t understand easily some like recursive function.
    • Program execution control sequence is not in run time
    • Can’t return more than one value.
    • can’t see separate function use.

 

Pre – defined functions

stdio.h  (Input output statements)

  • These statements are used to get and put a data to computers
  • Ex:
    • Can put a data to computer via keyboard.
    • Can get a data and see that in Monitor.
  • Input output statements are used as a functions in c language
  • stdio.h  file contains that statements statements
  • So if we use these functions should include stdio.h , functions are
    • scanf()
    • printf()
    • getchar()
    • gets()
    • putchar()
    • puts()

scanf()  function

  • Syntax :  scanf("control strings", &variable_1, &variable_2....&variable_n);
    • control sting :  %w  -( % – conversion specification indicator, W -width of input data)
    • &  – address of the variable
  • Rules
    • Should use comma  ,  to separate the different variables
    • Same data type variable and data specifier should use.
  • Examples
    • scanf("%d", &a);
    • scanf("%f", &a);
    • scanf("%d %f %d", &a, &b, &c);
    • scanf("%c", &sex);
    • scanf("%s%c", &name, &sex);
    • scanf("%4d", &a);
    • scanf("%5f", &a);
    • scanf("%20s", &name);
printf() function
  • syntax :  printf("control strings", list);

    • data format : %w.p  data-type
    • %  -conversion specification indicator
    • w  –  width of theoutput data (optional)
    • p  – point (dot)
  • Examples ;
    • printf("%d",x); 
    • printf("%3d",x); 
    • printf("%5d",x); 
    • printf("%-5d",x); 
    • printf("%07d",x); 
    • printf("%4d",-x); 

getchar()  function

  • Syntax: var = getchar();

gets()  Function

  •  Syntax : var = gets()

putchar()  function

  • Syntax : putchar(var);

puts()  Function

  • Syntax : puts("ArunEworld")

ctype.h  (characters statements)

  • Use of this functions is know which type of characters
    • isdigit() 
    • isalpha() 
    • isupper() 
    • islower() 
    • ispunct() 

isdigit()  function

  • Used to check is character  is numeric digit or not.
  • Syntax :  int isdigit(c); 
    • here c  is a variable or constant.
  • Returns : True – Non-zero, false – Zero.

isalpha()  function

  • Used to check is character  is alphabet or not.
  • Syntax :  int isalpha(c); 
    • here c  is a variable or constant.
  • Returns : True – Non-zero, false – Zero.

isupper()  function

  • Used to check is character  is upper or not.
  • Syntax :  int isupper(c); 
    • here c  is a variable or constant.
  • Returns : True – Non-zero, false – Zero.

islower()  function

  • Used to check is character  is lower or not.
  • Syntax :  int lower(c); 
    • here c  is a variable or constant.
  • Returns : True – Non-zero, false – Zero.

ispunct()  function

  • Used to check is character  is punctuation or not.
  • Syntax :  int ispunct(c); 
    • here c  is a variable or constant.
  • Returns : True – Non-zero, false – Zero.

string.h  functions

    • String is a  collection of characters in between the double quotation  " 
    • In C language does not have a data type like string, so we can get this from array of characters
    • Last character of sting should be null characters '/0' .
    • Generally compiler will add the null characters when read a string from computer.
    • Dose not appear null characters '/0'  when print the string in computer display
    • Data length is number of characters in the string with null characters.
    • Declaring string :Syntax –  char string_name[size];  //size-maximum number of characters including ‘0/’.
      • Example : char city [10];
    •  Initializing string :Syntax –  static char variable_name [size] = str;
      • Example
        • static char city[] = "ArunEworld"; 
        • static char city[10] = "ArunEworld";
        • static char city[10] = {'A','r','u','n','E','w','m','o','r','l','d'}; 
    •  Reading string 
      • scanf()
        • Example :  char name[50]; scanf(%s", name); 
      • getchar()
      • gets()
    • Printing String
      • printf()
        • printf("%s", var_name); 
      • puts()
        • puts(var_name); 
    • string  handling functions
      • strlen() 
      • strcpy() 
      • strcat() 
      • strcmp() 
      • strrev() 
      • strupr() 
      • strlwr() 
      • strrev() 

strlen()  functions

  • Syntax ; int strlen(char *string);

strcpy(destination, source);  functions

  • Syntax : void strcpy(char *string_!, char *string);

strcat()  functions

  • syntax ; void strcat( char *string_!, char *string_2);

strcmp()  functions

  • Syntax : int strcmp(char *string_1, char *String_2);  // strcmp return   (Zero) if both the strings are equal , else return -1
  •  Example :

strrev()   functions

  • syntax: char *strrev(char *string_1);

strupr()   functions

  • syntax : char* strupr(char *string_1);

strlwr() 

  • syntax : string *strlwr(char *string_1);

recursive function

  • When a recursive call is made, the function/process clones itself and then process that funtion. This leads to time and space constrains
  • In a loop, there is no recursive call involved that saves a lot of time and space too.
  • too many recursive calls may result into stack overflow . because when a function is called its return address is stored in stack
  • After sometime the stack memory will be filled completely. Hence  stack overflow  error will occur

Format specifier

  • %i   – Can be used to input integer in all the supported format.
  • %c  – single character
  • %d  – decimal character
  • %e  – floating point value
  • %f  – floating point value
  • %g  – floating point value
  • %h  – short integer
  • %i  – decimal/hexa decimal/octal integer
  • %ld  – long integer
  • %o  – octal integer
  • %s  – string
  • %u  – unsigned decimal integer
  • %x  – hexa decimal integer
  • [...]  – string which may include white spaces

Clear screen (clrscr)


How a negative integer is stored?

  • Get the two’s compliment of the same positive integer.

Eg:

 


Storage class

  • Storage classes only decides scope, visibility and lifetime of that variable.
  • Storage classes tells where will be the variable to stored.
  • What is the default initial value of the variable
  • Scope : The scope of a variable refers extent to which different part of programs have access to the variable,(Where the variable is visible).
  • Lifetime:  Lifetime means how long the variable persist in memory (or) when the variable’s storage is allocated and deallocated, scope also affects a variable’s lifetime.
  • variable types(Global variable)
    • Global variable. (outside of the function, include main() is called it)
      • life time : only destroy when program terminates
      • scope : only the programs
    • locaal variable. (inside the function
      • life time : when enters inside the function its allocated the memory, and destroy when goes to out of function.
      • scope : only that inside the function.
  • syntax:
    • storage_class_specifier data_type variable_name;
  • Specifiers  : auto
    • Lifetime : Block (or) inside function (or) within function
    • Scope : Block
    • Default initialize : Uninitialized
  • Specifiers  : register
    • Lifetime :  Block (stack or CPU register)
    • Scope : Block
    • Default initialize :  Uninitialized
  • Specifiers  : static
    • Lifetime :  Program
    • Scope : Block or compilation unit
    • Default initialize :  Zero
  • Specifiers  : extern
    • Lifetime :  Program
    • Scope : Block or compilation unit
    • Default initialize :  Zero
  • Specifiers  : (none)1
    • Lifetime :  Dynamic (heap)
    • Scope : nil
    • Default initialize :  Uninitialized

 auto    or local         –

  • A variable declare in the inside a function without any storage class specification or specified auto called auto variable.
  • Auto can only be used within functions
  • They are crated when a function is called and are destroyed automatically when the functions exits.
  • By defalt they are assigned garbage value by the compiler.
  • local variable (All the local variables are stored in a memory called as stack memory)
  • By default every local variable of the function is auto storage class.
  • Example

 

 Global variable

  • A variable declared outside any function is a global variable.
  • its value can be changed by any function in the program.
  • initializing
    • int – 
    • char  – \0
    • float  –
    • double  -
    • pointer  – null

extern                    –

  • The extern  keyword is used before a variable to inform the compiler that this variable is declared somewhere else.
  • The extern  declaration does not allocate storage for variables.
  • Used to resolve the scope of global symbol
  • Eg : Example Using extern  in same file

register    –

  • used to define local variables that should be stored in a register instead of RAM memory (eg :Quick access such as counters.)
  • register variable has faster access than a normal variable.
  • frequently used variables are kept in register.
  • only few variable can be placed inside register.
  • Note : if we try to take “Register’s” Address its gives Compile error, we cannot take the address of a register variable.

static

  • static means its take only single or same memory.
  • static is initialized only once and remains into existence till the end of program
  • static assigned 0 (zero) as default value by the compiler.
  • A static local variables retains its value between the function call and the default value is 0.
  • If a global variable is static then its visibility is limited to the same source code.
  • The following function will print 1 2 3 if called thrice.
  • Example

    •  
  • What is a static function?
    • A function’s definition prefixed with static keyword is called as a static function.
    • You would make a function static if it should be called only within the same source code (or) that are only visible to other functions in the same file
    • static has different meanings in in different contexts.
    • When specified on a function declaration, it makes the function local to the file.
    • When specified with a variable inside a function, it allows the vairable to retain its value between calls to the function

storage class specifier

  • typedef     –    typedef is the storage class specifier.
    •  its does not reserve the storage.
    • It is used to alias the existing type. Also used to simplify the complex declaration of the type.
  • reference links

volatile

  • Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time

  Operators

  • arithmetic                        : +, -, *, /, %
  • assignment                        : =
  • augmented assignment            : +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
  • bitwise logic                    : ~, &, |, ^
  • bitwise shifts                    : <<, >>
  • boolean logic                    : !, &&, ||
  • conditional evaluation            : ? :
  • equality testing                : ==, !=
  • calling functions                : ( )
  • increment and decrement            : ++, —
  • member selection                : ., ->
  • object size                        : sizeof
  • order relations                    : <, <=, >, >=
  • reference and dereference        : &, *, [ ]
  • sequencing                        : ,
  • subexpression grouping            : ( )
  • type conversion                    : (typename)

Address of Operator (Address of variable

  • &   // Address of Operator        –    It cannot be used on constants.It cannot be used on variable which are declared using register storage class.

main() -function

  • main()  – main is a function. Every function has a pair of parentheses ()
  • Can a program be compiled without main() function?
  • Yes, it can be but cannot be executed, as the execution requires main() function definition.

function

  • () - function    -Every function has a pair of parentheses ()

semicolon

  • ;  // Any C statement always ends with a ;

Comma Operator

  • ,  Comma Operator – can be used to separate two or more expressions
  • Eg: printf(hi) , printf(Hello);

scope or block

  • A local block is any portion of a C program that is enclosed by the left brace {  and the right brace } .
  • anything between the two braces is contained in a local block.
  • {}                // scope or block
    • Increment Operator
      • ++x (pre increments)
      • x++ (post increments)
      • Eg:
        • S++;     //    ++, as it is single machine instruction (INC) internally.(recommended)
        • S = S+1;     //     ++, as it wil take two machine cycle internally.(not recommended)
    • Decrements Operator
      • --x (pre Decrements)
      • x-- (post Decrements)

Boolean Operator

  • ==     Equal
  • !=     Not equal
  • >      Greater than
  • >=     Greater than or equal
  • <     Less than
  • <=     Less than or equal
  • &&     Logical AND
  • ||    Logical OR
  • !    Logical NOT

Decision making, Branching, Looping statements

 Control Statements (Two types)

  • C program is executing sequentially line by line from the first statement to last statement.
  • But we can change this sequentially execution in c, by using control statements
  • Types
    • Unconditional statements (goto statement)
      • It will change the execution order without any checking process
      • Syntax :  goto label_name_position; label_name_position : ArunEworld;
      • Rules
        • label should be  a valid identifier.
        • label  should be end with colon  : 
        • Does not require to declare a label . 
    • Conditional statements (Two types)
      • It will change the execution order with checking process.
      •  types
        • Decision making statements(five types)
        • Looping statements (Three types)
      • Note : return statement or return keyword  cannot be used with conditional operators(terynary).

Note : C programming language assumes True and False

  • True     =  non-zero and non-null. // eg: 1, Arun, True
  • False    =    zero or null.    //eg : 0, nil, false

 Decision Making statements (five types)

  • It will change the execution order with checking process.
  •  types
    • Simple if Statements
    • if- else  statements
    • else ...if ladder statements
    • nested if  statements
    • switch  statements

Simple if Statements

  •  It will change the execution order from one place to another place (or) skip the execution of group of statements (or) Execute the group of statements with checking one condition.
  • Syntax : if(Boolean_expression) goto label;  (or)   if(Boolean_expression) statement; (or)
  • Note : statement(s) will execute if the Boolean expression is true.
  • Rules
    • Test conditions should be in brackets  ()
    • Test condition should be Relational /Logical expression
    • Should use open { and } close braces, if use group of statements 
    • examples
      • if (a<b) big =1; 
      • if (a=1) goto ArunEworld; 
  • Example Programs 
    • Evaluate_mark_of_students_using_if_statement.c
    • Evaluvate_sale_tax_using_if_statement.c

if- else statements

  • Execute the group of statement if test condition is true, else test  condition is false it will execute the another group of statements
  • Syntax :  if(Boolean_expression) statement_1; else statement_2; (or)

     
  • Rules
    • Test conditions should be in brackets ()
    • Test condition should be Relational /Logical expression
    • Should use open  {  and } close braces, if use group of statements 
    • examples
      • if (a<b) big =b; else big =a; 
      • if (a=1) goto ArunEworld; else goto Arun; 
      • if (a<b) { s=a+b; d =a-b; } else m = a+b; 
  • Example Programs 
    • check_given_marks_fail_or_pass_using_if_else_statement.c
    • Biggest_number_using_if_statement.c

else ...if  ladder statements

  • else..if is can use to checking more than one conditions, Execute the group of statement if test condition_1 is true, else..if test  condition_2 is true it will execute the another group of statements, else above two test condition is false execute another group of statements
  • Syntax :

(or)

  • Rules
    • Test conditions should be in brackets  ()
    • Test condition should be Relational /Logical expression
    • Should use open {  and } close braces, if use group of statements 
    • examples

       

      • if (a>b) goto ArunEworld; elseif(b>a) goto Arun; else goto Eworld; 
      • if (a<b) { s=a+b;d =a-b; } eslesif(b>a){ d =a-b; b= a-b;} else {m = a+b; a=a+b;} 
  • Example Programs 
    • Display_Day_using_if_elseif_statement.c

nested if  statements

  • Syntax    :
  • Examples : Biggest_of_three_numbers_using_nested-if.c

switch statements

  • group of if..else statements collection is called switch statement.
  • Syntax :
  • Rule
    • Expression  must have an integral or enumerated type.
    • Constant-expression must be the same data type as the variable in the switch.
  • Example: Display_Day_using_switch_statement.c

nested switch

  • Syntax    :

     

Looping control statements (Three types)

While Loop

  • Syntax :     while(condition)     //The condition may be any expression, and true is any nonzero
  • value. The loop iterates while the condition is true.

 

Do..while Loop

  • Syntax :

     
  •     Rules:
    • condition is true while statement break the do loops

for Loop

  • Syntax    :

     
  • Rules:
    • init  – The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.You are not required to put a statement here, as long as a semicolon appears.
    • condition  –    Next, the condition is evaluated. If it is true, the body of the loop is executed.If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’ loop.
    • increment     –    After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment statement.This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

nested for loops

  • Syntax :

     

nested while loops

  • Syntax    :

     

Infinite Loop

  • A loop running continuously for indefinite number of times is called infinite loop.

Infinite For Loop:


  •  

Infinite While Loop:


  •  

Infinite Do-While Loop:


break

  • Break can appear only with in the looping control and switch statement.
  • The purpose of the break is to bring the control out from the used blocks.
  • Syntax :    break;

continue

  • Syntax : continue;

Array

  • It is very difficult to define more variables name when use more data.
  • So can create a array to solve this difficult(single variable name and more data).
  • If the index of the array size is exceeded, the program will crash. But the modern compilers will take care of this kind of errors.
  • We cannot initialize the size of array dynamically. Constant expression is required.
  • Rules
    • only store the same data types in array structures
    • Arrays are always passed by reference
  • What is Base address of array??
    •  Eg :  a[10] = {0,1,2,3,4,5,6,7,8,9}     // The starting address of the array is called as the base address of the array.
  • When we pass an array as a function argument, the base address of the array will be passed.
  • Array three types
    • One Dimensional Array
    • Two Dimensional Array and
    •  Multi Dimensional Array

 One Dimensional Array

  • When declare one index value is called One dimensional array
  • Syntax:  data_type array_name [ size];
    • data_type  – What kind of array data type
    • array_name  – name of the array
    • size  – array size
  • Syntax Declaration:
    • int a[100];  //Data type- int (2Byte), array_name – ‘a’, size – 100, Memory Occupies- 200 byte (100×2).
    • float s [50];  //Data type- float(4byte), array_name – ‘s’, size – 50, Memory Occupies- 200 byte (50×4).
    • char name[15];  // Data type- char(1byte), array_name – “name”, size – 15, Memory Occupies- 15 byte (15×1).
  • Declaration :  int a[100];
  • Reading : for(i=0; i<100; i++) scanf("%d", &a[i]);
  • Writing :  for(i=0; i<100; i++) printf("%d", a[i]);
  • Memory Representation :
  • Array initialization Syntax :  data_type array_name [size] = {list_of_values}; 
    • Examples
      • static int age [3] = {10,20,30};  //its means – a[0]=10; a[1]=20; a[3]=30;
      • static float salary[] = {1000,2200,3300};  //salary[0]=1000; salary[2]=3300;
      • static char a[10] = "ArunEworld";  //its means – a[0]=’A’; a[1]=’r’; like… a[9]=’d’;
  • Example Programs

Two Dimensional Array

  • When declare two index value is called two dimensional array
  • Two dimensional arrays can consider as a table. size_1 is row size and size_2 is column size.
  • Syntax:  data_type array_name [ size_1] [size_2];
    • data_type  – What kind of array data type
    • array_name  – name of the array
    • size_1 , size_2 – two dimensional array size
  • Syntax Declaration:
    • int a[100] [20];  //Data type- int (2Byte), array_name – ‘a’, size_1(row) – 100,size_2(column)-20, Memory Occupies- 200 byte (100×2).
  • Declaration :  int a[10][15];
  • Reading : for(i=0; i<10; i++) for(j=0; j<15; j++) scanf("%d", &a[i][j]); 
  • Writing : for(i=0; i<10; i++) for(j=0; j<15; j++) printf("%d", a[i][j]); 
  • Memory Representation :
  • Array initialization Syntax :  data_type array_name [size_1] [size_2] = {v1, v2,.....vn}; 
    • Examples
      • static int mark[3][2] = {60,70,80, 35,90,18};  //its means – a[0][0]=60; a[0][1]=70; a[0][3]=30; a[1][0]=35; a[1][1]=90; a[1][2]=18;
      • static mark[3][2] = {{50},{0},{35}; //a[0][0]=50; a[0][1]=50; a[0][3]=0; a[1][0]=0; a[1][1]=35; a[1][2]=35;
  • Example Programs
    • Two_dimensional_array_read_row_column.c
    • Two_dimensional_array_print_row_column.c
    • Matrix_transpose_using_two_dimensional_array.c
    • Diagonal_elements_using_two_dimensional_array.c
    • Sum_of_diagonal_elements_using_two_dimensional_array.c
    • Sum_of_all_matrix_elements_using_two_dimensional_array.c
    • Add_a_given_matrix_elements_using_two_dimensional_array.c
    • Multiply_matrix_elements_using_two_dimensional_array.c
    • Largest_and_smallest_elements_using_two_dimensional_array.c

Multi Dimensional Array

  • In C, can use 3 or more dimension called as multi dimensional array
  • Multi Dimension limit is based on the compiler
  • Syntax: data_type array_name [size-1][size_2]….[size_n]; 
    • data_type  – What kind of array data type
    • array_name  – name of the array
    • size  – array size
  • Example : 
    •   int a[10][10][10];  //Data type- int (2Byte), array_name – ‘a’, size – 2000(10x10x10x2), Memory Occupies- 2000bytes

 

Array disadvantage:

  • One disadvantage of using arrays to store data is that arrays are static structures and therefore cannot be easily extended or reduced to fit the data set.
  • Arrays are also expensive to maintain new insertions and deletions

Pointer

  • It’s a pointer variable which can hold the address of another pointer variable.
  • That two variables should be same data type.
  • It de-refers twice to point to the data held by the designated pointer variable.
  • //Eg:    int x = 5, *p=&x, **q=&p;     //Therefore ‘x’ can be accessed by **q.
  • Advantage
    • Use pointer to increase the speed of program execution
    • Reduce program complexity
    • To use pointer to access the inside function’s variable value.
    • To use pointer to transfer the data from outside or inside the functions.
  • Access the address of the variable syntax :  &variable_name
  • Declaring pointers syntax: datatype *var;  Example : int *a;
  • Initializing pointer syntax :  pointer_name =&variable_name;  Example : int *a; int x; a =&x;
  • Pointer expressions : +  for addition, -  for subtraction, ++  for incremanet, --  for decrement.

What is a NULL pointer?

  • A pointer pointing to nothing is called so.
  • NULL pointer is always initialized.
  • NULL pointer assignment :  char *q=0;  (or) char *q=(char*)0;  (or) char *p=NULL;
  • Example
    • What is (void*)0 ? //Representation of NULL pointer
  • NULLMacro is defined in locale.h , stddef.h , stdio.h , stdlib.h , string.h , time.h , and wchar.h

What is a dangling pointer?

  • A pointer initially holding valid address, but later the held address is released or freed.
  • Then such a pointer is called as dangling pointer.

Near pointer

  • Near pointer occupies 2 bytes in DOS

What is Far Pointer?

  • far pointer occupies 4 bytes in DOS

huge pointer

  • huge pointer occupies 4 bytes in DOS

What is the advantage of declaring void pointers?

  • When we do not know what type of the memory address the pointer variable is going to hold, then we declare a void pointer for such.

What is a pointer to a function?

  • A pointer holding the reference of the function is called pointer to a function.

What is pointer to pointer in C?

  • one pointer refers to the address of another pointer

What is Function Pointer?

  • syntax : int(*fun)(int, int, int);
  • A function pointer is a variable that stores the address of a function that can later be called through that function pointer.
  • This is useful because functions encapsulate behavior.

What is a pointer on pointer?

  • It’s a pointer variable which can hold the address of another pointer variable.
  • It de-refers twice to point to the data held by the designated pointer variable.
  • Eg: int x = 5, *p=&x, **q=&p;
    • Therefore x  can be accessed by **q .

Pointer and Array

  • int (*ptr)[10]; //  ptr is a pointer to an array of 10 integers.

 


Memory Allocation

  • Static Memory allocation
    • In case of static memory allocation, memory is allocated at compile time and memory can’t be increased while executing the program. It is used in array
  •  Dynamic memory allocation
    • In case of dynamic memory allocation, memory is allocated at run time and memory can be increased while executing the program. It is used in linked list.
    • The following functions are used in Dynamic memory allocation
      • malloc()    –    allocates single block of requested memory. It has garbage value initially.
      • calloc()     –    allocates multiple block of requested memory. It initially initializes all bytes to zero.
      • realloc()    –    reallocates the memory occupied by malloc()  or calloc()  functions.
      • free()         –    frees the dynamically allocated memory.

Difference b/w Static and dynamic memory allocation?


Structure ( struct  keyword)

  • Structure is the group of heterogeneous data structure which can store data of different data types or Structure is a collection of variables of different types under a single name
  • In the case of array, we can store the data of same data type but what if we have to save data of different data type in structure
  • Keyword struct  is used for creating a structure.
  • Note : Structure elements cannot be initialized
  • Can use single structure name for  more type of data in structure and union.
  • Storage area is not reserved by the compiler to structure definition.
  • Structure is a user defined data structure.
  • Syntax :
  • Rules
    • Use declare semicolon  };  at end of structure. (Don’t forget the semicolon in  the ending line.)
  • structure variable declaration
    • struct defined : (Ex: struct struct_name var_1, var_2;
    • struct define : (ex : struct struct_name { data_type member_1; data_type member_2;} var_1, var_2;
  • Referencing structure members :  struct_var-name . member_variable
  • Structure cannot be compared using ==
  • In Stucture bit cant set in float variable.
  • structure initializing : static struct structure_name var-name= {var_1, var_2,...var_n};

Example

In a school we need to store data like name, roll no, address and percentage. But we are able to store only one data type at a time. So, C programming provides structure data type which can store data of different types such as integer, float, character etc. In the case of above school, we can initialize structure as :

 

 Nested structure [structure with structure]

 

  • A structure containing an element of another structure as its member is referred so.

What is a self-referential structure?

  • A structure containing the same structure pointer variable as its element is called as self-referential structure.

When to user ->  (arrow) operator.

  • If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used.

Array of structure :Syntax : struct structure_name var_name [size];


Union

  • Syntax :  union union_name {data_type_1 member_1; data_type_2 member_2; };
  • Declaration :  union union_name {data_type_1 member_1; data_type_2 member_2; }uv_1,uv_2;
  •  

What is the difference between union and structure?

  • The difference between structure and union is, … The amount of memory required to store a structure variable is the sum of the size of all the members.
  • On the other hand, in case of unions, the amount of memory required is always equal to that required by its largest member.

 


Enum

  • --  or ++  are con’t be done on enum value.

getch()

    The getch() function reads a single character from keyboard. It doesn’t uses any buffer, so entered data is not displayed on the output screen.

getche()

  • The getche() function reads a single character from keyword but data is displayed on the output screen. Press Alt+f5  to see the entered character.

sprintf  function

  • sprintf()    //    Prints the formatted output onto the character array.

scanf  function

  • syntax :    scanf("<format string>", <Address of variables>);

fputc() Function :

  • Syntax    :    fputc(character, file_pointer);

File Management

File Initialize object of the type

  • FILE // which contains all information necessary to control the stream

File Functions

  • Fopen()  // Open a new file or open an existing file.
    • Syntax :   FILE *fopen( const char * filename, const char * mode );
  • fclose()  // close a file.
    •  Syntax :   int fclose( FILE *fp);
  • fputc()  // Writing a file.
    • Syntax :  int fputc( int c, FILE *fp );
  • fgetc() // Reading a file.
    •  Syntax :  int fgetc( FILE * fp );

Syntax

  • fopen(file_name”,"mode); 

File Modes

Normal file handling

  • r  – Open an existing file for Read purpose
  • w  – Open an existing file for Write purpose
  • a  –  Open a file for writing in append mode. If file not exist, then create new file.
  • r+  – Open a file for both Read and Write
  • w+  – Opens a file for Read and Write. If a file is not existing it creates one, else if the file is existing it will be over written.
  • a+  –    

 Binary file handling

  • rb  – Read (Binary file)
  • wb  – write (Binary file)
  • ab  – append (Binary file)
  • rb+  –
  • wb+  –
  • ab+  –
  • r+b  – reading (Binary file)
  • w+b  – (Binary file)
  • a+b  – (Binary file)

 



Reference Links

  • https://www.tutorialspoint.com/cprogramming/c_file_io.htm

<

div data-blogger-escaped-style=”text-align: center;”>

<span style=”font-family: inherit;” data-blogge

 

 


Find largest number among 3 numbers using ternary operator

Output