Basic Concept of C

 

Introduction & History

Ø  C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.

Ø  It is a very popular language, despite being old.

Ø  C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Why Learn C?

Ø  Many later languages have borrowed syntax/features directly or indirectly from the C language.

Ø  Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C language.

Ø  So,  if a person learns C programming first, it will help him to learn any modern programming language as well.

Ø  As learning C help to understand a lot of the underlying architecture of the operating system.

Features

Ø  The main features of the C language include:

Ø  General Purpose and Portable

Ø  Low-level Memory Access

Ø  Fast Speed

Ø  Clean Syntax

Ø  These features make the C language suitable for system programming like an operating system or compiler development.

Advantages & Disadvantages



Structure of C Program



Components of a C Program

Header Files Inclusion – Line 1 [#include <stdio.h>]

Ø  The first and foremost component is the inclusion of the Header files in a C program.

Ø  A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.

Ø  All lines that start with are processed by a preprocessor which is a program invoked by the compiler.

Ø  In the before example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C.

Ø  Some of the C Header files:

Ø  stdio.h – Defines core input and output functions

Ø  stdlib.h – Defines numeric conversion functions and memory allocation

Ø  string.h – Defines string handling functions

Ø  math.h – Defines common mathematical functions.

            Main Method Declaration – Line 2 [int main()]

Ø  The next part of a C program is to declare the main() function.

Ø  It is the entry point of a C program and the execution typically begins with the first line of the main().

Ø  The empty brackets indicate that the main doesn’t take any parameter.

Ø  The int that was written before the main indicates the return type of main().

Ø  The value returned by the main indicates the status of program termination.

            Body of Main Method – Line 3 to Line 6 [enclosed in {}]

Ø  The body of a function in the C program refers to statements that are a part of that function.

Ø  It can be anything like manipulations, searching, sorting, printing, etc.

Ø  A pair of curly brackets define the body of a function.

Ø  All functions must start and end with curly brackets.

            Statement – Line 4 [printf(“Hello World”);]

Ø  Statements are the instructions given to the compiler.

Ø  In C, a statement is always terminated by a semicolon (;). 

Ø  In this particular case, we use printf() function to instruct the compiler to display “Hello World” text on the screen.

            Return Statement – Line 5 [return 0;]

Ø  The last part of any C function is the return statement.

Ø  The return statement refers to the return values from a function.

Ø  This return statement and return value depend upon the return type of the function.

Ø  The return statement in our program returns the value from main().

Ø  The returned value may be used by an operating system to know the termination status of your program.

Ø  The value 0 typically means successful termination. 

Compiling Process



Ø  The compilation and execution process of C can be divided in to multiple steps:

Ø  Preprocessing Using a Preprocessor program to convert C source code in expanded source code. "#include" and "#define" statements will be processed and replaced actually source codes in this step.

Ø  Compilation Using a Compiler program to convert C expanded source to assembly source code.

Ø  Assembly Using a Assembler program to convert assembly source code to object code.

Ø  Linking Using a Linker program to convert object code to executable code. Multiple units of object codes are linked to together in this step.

Ø  Loading Using a Loader program to load the executable code into CPU for execution. Compilation

C Preprocessor

Ø  C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation.

Ø  All preprocessor commands begin with a hash symbol (#).

Ø  It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column.

Ø  We'll refer to the C Preprocessor as CPP.

Ø  Preprocessor directives are lines included in a program that begin with the character #, which make them different from a typical source code text.

Ø  They are invoked by the compiler to process some programs before compilation.

Ø  Preprocessor directives change the text of the source code and the result is a new source code without these directives.

 C  Preprocessors Examples

Ø  #define SIZE 20 : This directive tells the CPP to replace instances of SIZE with 20. Use #define for constants to increase readability.

Ø  #include<stdio.h>: These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file.

Ø  #include “myheder.h”: The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.

Ø  #ifndef MESSAGE

#define MESSAGE “Hello”

#endif

Ø  It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

Header Files

Ø  A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.

Ø  There are two types of header files:

Ø  the files that the programmer writes and

Ø  the files that comes with your compiler.

Ø  You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler.

Library Function

Ø  Inbuilt functions in C language.

Ø  These inbuilt functions are located in some common location, and it is known as the library.

Ø  All the functions are used to execute a particular operation.

Ø  These library functions are generally preferred to obtain the predefined output.

Ø  Also, the actions of these functions are present in their header files.

             

Library Functions in Different Header Files

Advantages of Using C library Functions

Ø  The Execution: One of the most significant reasons for utilising the library functions is that these functions are easy-to-use, and have gone through strict testing.

Ø  The Functions to Boost the Performance: The standard library functions are very popular. And, that is the reason developers are trying their best to polish them.

Ø  Can Save a Lot of Time: The best part is you don’t need to create basic functions, like calculating the square root and more, because we already have these. 

Character Set

Ø  the character set refers to a set of all the valid characters that we can use in the source program for forming words, expressions, and numbers.

Ø  The source character set contains all the characters that we want to use for the source program text.

Ø  On the other hand, the execution character set consists of the set of those characters that we might use during the execution of any program.

Ø  They include digits, alphabets, special symbols, etc. The C language provides support for about 256 characters.

Types of Characters in C

            Alphabets

Ø  The C programming language provides support for all the alphabets that we use in the English language.

Ø  Thus, in simpler words, a C program would easily support a total of 52 different characters- 26 uppercase and 26 lowercase.

            Digits

Ø  The C programming language provides the support for all the digits that help in constructing/ supporting the numeric values or expressions in a program.

Ø  These range from 0 to 9, and also help in defining an identifier.

Ø  Thus, the C language supports a total of 10 digits for constructing the numeric values or expressions in any program.

 

            Special Characters

Ø  We use some special characters in the C language for some special purposes, such as logical operations, mathematical operations, checking of conditions, backspaces, white spaces, etc.

Ø  We can also use these characters for defining the identifiers in a much better way.

Ø  For instance, we use underscores for constructing a longer name for a variable, etc.

Ø  The C programming language provides support for the following types of special characters:

 

            White Spaces

Ø  The white spaces in the C programming language contain the following:

Ø  Blank Spaces

Ø  Carriage Return

Ø  Tab

Ø  New Line

Comments

Ø  Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Ø  Comments can be singled-lined or multi-lined.

Ø  Single-line Comments

Ø  Single-line comments start with two forward slashes (//).

Ø  Any text between // and the end of the line is ignored by the compiler (will not be executed).

Ø  Example:

Ø  // This is a comment

Ø  printf("Hello World!");

Ø  C Multi-line Comments

Ø  Multi-line comments start with /* and ends with */.

Ø  Any text between /* and */ will be ignored by the compiler:

Ø  Example:

Ø  /* The code below will print the words Hello World!
to the screen, and it is amazing */

Ø  printf("Hello World!");

Token and its types

Ø  A token is the smallest unit used in a C program.

Ø  Each and every punctuation and word that you come across in a C program is token.

Ø  A compiler breaks a C program into tokens and then proceeds ahead to the next stages used in the compilation process.

Ø  In other words, tokens are the building blocks or the very basic components used in creating any program in the C language.

Ø  Different types of token in C:

Ø  Identifiers in C

Ø  Keywords in C

Ø  Operators in C

Ø  Strings in C

Ø  Special Characters in C

Ø  Constant in C

Identifier in C

Ø  These are used to name the arrays, functions, structures, variables, etc.

Ø  The identifiers are user-defined words in the C language.

Ø  These can consist of lowercase letters, uppercase letters, digits, or underscores, but the starting letter should always be either an alphabet or an underscore.

Ø  We cannot make use of identifiers in the form of keywords.

Ø  Here are the rules that we must follow when constructing the identifiers:

Ø  The identifiers must not begin with a numerical digit.

Ø  The first character used in an identifier should be either an underscore or an alphabet. After that, any of the characters, underscores, or digits can follow it.

Ø  Both- the lowercase and uppercase letters are distinct in an identifier. Thus, we can safely say that an identifier is case-sensitive.

Ø  We cannot use an identifier for representing the keywords.

Ø  An identifier does not specify blank spaces or commas.

Ø  The maximum length of an identifier is 31 characters.

Ø  We must write identifiers in such a way that it is not only meaningful- but also easy to read and short.

Keywords in C

Ø  We can define the keywords as the reserved or pre-defined words that hold their own importance.

Ø  It means that every keyword has a functionality of its own.

Ø  Since the keywords are basically predefined words that the compilers use, thus we cannot use them as the names of variables.

Ø  If we use the keywords in the form of variable names, it would mean that we assign a different meaning to it- something that isn’t allowed.

Ø  The C language provides support for 32 keywords, as mentioned below:

Operators in C

Ø  The operators in C are the special symbols that we use for performing various functions.

Ø  Operands are those data items on which we apply the operators.

Ø  We apply the operators in between various operands.

Ø  On the basis of the total number of operands, here is how we classify the operators:

Ø  Unary Operator a type of operator that gets applied to one single operand, for example: (--) decrement operator, (++) increment operator, (type)*, sizeof, etc.

Ø  Binary Operator types of operators that we apply between two of the operands. Here is a list of all the binary operators that we have in the C language: Relational Operators, Arithmetic Operators, Logical Operators, Shift Operators, Conditional Operators, Bitwise Operators, Misc Operator, Assignment Operator

Ø  Ternary Operator Using this operator would require a total of three operands. For instance, we can use the ?: in place of the if-else conditions.

Strings in C

Ø  The strings in C always get represented in the form of an array of characters.

Ø  We have a ‘\0′ null character at the end of any string- thus, this null character represents the end of that string.

Ø  In C language, double quotes enclose the strings, while the characters get enclosed typically within various single characters.

Ø  The number of characters in a string decides the size of that string.

Ø  Now, there are different ways in which we can describe a string:

Ø  char x[9] = “chocolate’’; // Here, the compiler allocates a total of 9 bytes to the ‘x’ array.

Ø  char x[] = ‘chocolate’; // Here, the compiler performs allocation of memory during the run time.

Ø  char x[9] = {‘c’,’h’,’o’,’c’,’o’,’l’,’a’,’t’,’e’,’\0′}; // Here, we are representing the string in the form of the individual characters that it has.

Special Characters in C

Ø  We also use some of the special characters in the C language, and all of them hold a special meaning that we cannot use for any other purpose.

Ø  () Simple brackets – We use these during function calling as well as during function declaration. For instance, the function printf() is pre-defined.

Ø  [ ] Square brackets – The closing and opening brackets represent the multidimensional and single subscripts.

Ø  (,) Comma – We use the comma for separating more than one statement, separating the function parameters used in a function call, and for separating various variables when we print the value of multiple variables using only one printf statement.

Ø  { } Curly braces – We use it during the closing as well as opening of any code. We also use the curly braces during the closing and opening of the loops.

Ø  (*) Asterisk – We use this symbol for representing the pointers and we also use this symbol as a type of operator for multiplication.

Ø  (#) Hash/preprocessor – We use it for the preprocessor directive. This processor basically denotes that the user is utilizing the header file.

Ø  (.) Period – We use the period symbol for accessing a member of a union or a structure.

Ø  (~) Tilde – We use this special character in the form of a destructor for free memory.

Constant in C

Ø  Constant is basically a value of a variable that does not change throughout a program.

Ø  The constants remain the same, and we cannot change their value whatsoever.

Ø  Here are two of the ways in which we can declare a constant:

Ø  By using a #define pre-processor

Ø  By using a const keyword

Ø  Here is a list of the types of constants that we use in the C language:


Data Types

Ø  data types are declarations for variables. This determines the type and size of data associated with variables. For example,

Ø  int myVar;

Ø  Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.

Ø  Basic types




 Data Type-int

Ø  Integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example, 0, -5, 10

Ø  We can use int for declaring an integer variable.

Ø  int id;

Ø  Here, id is a variable of type integer.

Ø  You can declare multiple variables at once in C programming. For example,

Ø  int id, age;          

Ø  The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -2147483648 to 2147483647.

Data Type-float and double

Ø  float and double are used to hold real numbers.

Ø  float salary;

Ø  double price;

Ø  In C, floating-point numbers can also be represented in exponential. For example,

Ø  float normalizationFactor = 22.442e2;

Ø  What's the difference between float and double?

Ø  The size of float (single precision float data type) is 4 bytes. And the size of double (double precision float data type) is 8 bytes.

Data Type-char & void

char

Ø  Keyword char is used for declaring character type variables. For example,

Ø  char test = 'h';

Ø  The size of the character variable is 1 byte.

Void

Ø  void is an incomplete type. It means "nothing" or "no type". You can think of void as absent.

Ø  For example, if a function is not returning anything, its return type should be void.

Ø  Note that, you cannot create variables of void type.

Data Type-short & long

Ø  If you need to use a large number, you can use a type specifier long. Here's how:

Ø  long a;

Ø  long long b;

Ø  long double c;

Ø  Here variables a and b can store integer values. And, c can store a floating-point number.

Ø  If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can use short.

Ø  short d;

Check the size of a variable-size of

            #include <stdio.h>     

            int main() {

              short a;

              long b;

              long long c;

              long double d;

              printf("size of short = %d bytes\n", sizeof(a));

              printf("size of long = %d bytes\n", sizeof(b));

              printf("size of long long = %d bytes\n", sizeof(c));

              printf("size of long double= %d bytes\n", sizeof(d));

              return 0;

            }

Data Type-signed & unsigned

Ø  In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using them:

Ø  signed - allows for storage of both positive and negative numbers

Ø  unsigned - allows for storage of only positive numbers

Ø  For example,

Ø  // valid codes

Ø  unsigned int x = 35;

Ø  int y = -35;  // signed int

Ø  int z = 36;  // signed int

Ø  // invalid code: unsigned int cannot hold negative integers

Ø  unsigned int num = -35;

Ø  Here, the variables x and num can hold only zero and positive values because we have used the unsigned modifier.

Ø  Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1, whereas variable x can hold values from 0 to 232-1.

Derived data types

Ø  Data types that are derived from fundamental data types are derived types.

Ø  For example: arrays, pointers, function types, structures, etc.

Ø  We will learn about these derived data types in later class.

Escape Sequences

Ø  An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

Ø  It is composed of two or more characters starting with backslash \.

Ø  For example: \n represents new line.

Ø  List of Escape Sequences in C.


Escape Sequence Example

Output:

 




 

 

 


 


 



 



No comments:

Post a Comment

Research in Social Science

   C  Concept of Research in Social Science -         Understanding the concept of Research Methods, Techniques and Tools: Interview, Fo...