C Programming

Imp C Programming link with Explanataion

http://cprogramming.language-tutorial.com/2012/01/program-to-find-given-number-is-perfect.html
http://free-c-programs.blogspot.in/
http://www.cquestions.com/2011/12/c-program-examples-with-output.html
http://cprogramming.language-tutorial.com/2012/01/program-to-find-given-number-is-perfect.html

History of C Programming Language

1.       C is a programming language which born at “AT & T’s Bell Laboratories” of USA in 1972.
2.      It was written by Dennis Ritchie.
3.      This language was created for a specific purpose : to design the UNIX operating system (which is used on many computers).
4.      From the beginning, C was intended to be useful to allow busy programmers to get things done because C is such a powerful, dominant and supple language, its use quickly spread beyond Bell Labs. in the late 70’s
5.      Many of its principles and ideas were taken from the earlier language B.
6.      Ken Thompson was the developer of B Language.
7.      BCPL and CPL are the earlier ancestors of B Language
8.      CPL is common Programming Language.In 1967, BCPL ( Basic CPL ) was created as a scaled down version of CPL
9.      As many of the features were derived from “B” Language thats why it was named as “C”.
10.   After 7-8 years C++ came into existence .

Summary of C Programming Language History

Summary of C Programming History
1
B Language Developed By
Ken Thompson
2
Operating System Developed in C
UNIX
3
Developed at
AT & T Bell Laboratory
4
Creator of Traditional C
Dennis Ritchie
5
Year
1972
History of C Programming Language



Father of C Programming : Dennis Ritchie

Dennis Ritchie : General

Born On
September 9, 1941
Born in
Bronxville,New York,
Full Name
Dennis MacAlistair Ritchie
Nickname
DMR
Nationality
American
Graduate From
Harvard University
Graduate In
Physics and Applied Mathematics
Webpage
Dead On
October 12, 2011

Dennis Ritchie : Known for

No
What ?
1
Creator of C Programming
2
Creator of UNIX operating System
3
Co-author of “The C Programming Language”

Awards :

1982
Ritchie and Ken Thompson jointly received the Turing Award for their development of generic operating systems theory
  1999
Thompson and Ritchie jointly received the 1998 National Medal of Technology from President Bill Clinton for co-inventing the UNIX operating system and the C programming language





Chapter 2 : C Programming Basics

Features of C Programming Language :

C Programming is widely used in Computer Technology, We can say that C Programming is inspiration for development of other languages. We can use C Programming for different purposes. Below are some of the Features of C Programming language -

1 . Low Level Features :

1.       C Programming provides low level features that are generally provided by the Lower level languages. C is Closely Related to Lower level Language such as “Assembly Language“.
2.      It is easier to write assembly language codes in C programming.

2 .Portability :

1.       C Programs are portable i.e they can be run on any Compiler with Little or no Modification
2.      Compiler and Preprocessor make it Possible for C Program to run it on Different PC
Features of C Programming Language

3 .Powerfull

1.       Provides Wide verity of ‘Data Types
2.      Provides Wide verity of ‘Functions’
3.      Provides useful Control & Loop Control Statements

4 . Bit Manipulation

1.       C Programs can be manipulated using bits. We can perform different operations at bit level. We can manage memry representation at bit level. [Eg. We can use Structure to manage Memory at Bit Level]
2.      It provides wide verity of bit manipulation Operators. We have bitwise operators to manage Data at bit level.

5 . High Level Features :

1.       It is more User friendly as compare to Previous languages. Previous languages such as BCPL,Pascal and other programming languages never provide such great features to manage data.
2.      Previous languages have there pros and cons but C Programming collected all useful features of previous languages thus C becomemore effective language.

6 . Modular Programming

1.       Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules
2.      C Program Consist of Different Modules that are integrated together to form complete program

7 . Efficient Use of Pointers

1.       Pointers has direct access to memory.
2.      C Supports efficient use of pointer .

8 . More Efficient


Application Of C Programming

C Programming is best known programming language. C Programming is near to machine as well as human so it is called as Middle level Programming Language. C Programming can be used to do verity of tasks such as networking related,OS related.

Application of C Programming are listed below -

1.       C language is used for creating computer applications 
2.      Used in writing Embedded softwares
3.      Firmware for various electronics, industrial and communications products which use micro-controllers.
4.      It is also used in developing verification software, test code, simulators etc. for various applications and hardware products.
5.      For Creating Compiles of different Languages which can take input from other language and convert it into lower level machine dependent language.
6.      C is used to implement different Operating System Operations.
7.      UNIX kernel is completely developed in C Language.
Unix Operating System - Application of C Programming Language

List of Applications of C Programming

List of Application
Operating Systems
Network Drivers
Print Spoolers
Assemblers
Text Editors
Modern Programs
Data Bases
Language Interpreters
Simulators
Utilities
Embedded System

Definition of Compiler :

1.       A computer program which reads source code and outputs assembly code or executable code is called compiler.
2.      A program that translates software written in source code into instructions that a computer can understand Software used to translate the text that a programmer writes into a format the CPU can use.
3.      A piece of software that takes third-generation language codeand translates it into a specific assembly code. Compilers can be quite complicated pieces of software.

Compiler Overview :

Consider process of Executing Simple C Language Code –

We have opened C Code editor and wrote simple C Program , Whenever we try to compile code and try to execute code our code is given to the compiler.
intmain()
{
printf("Hello");
return(0);
}
Now our main intention is to convert program into lower level language which can be read by Machine. Compiler have different phases , and program undergoes through these 6 phases. After Passing through all the compilation Phases our code is converted into the machine level language code which can be read by machine.
Compiler Converts C Program into Binary Language

Different Phases of Compiler

1.       Lexical Analysis Phase
2.      Syntax Analysis
3.      Semantic Analysis
4.      Intermediate Code Generation
5.      Code Optimizer
6.      Code Generation

What is Interpreter ?

1.       Interpreter Takes Single instruction as input .
2.      No Intermediate Object Code is Generated
3.      Conditional Control Statements are Executes slower
4.      Memory Requirement is Less
5.      Every time higher level program is converted into lower level program
6.      Errors are displayed for every instruction interpreted (if any)
7.      The interpreter can immediately execute high-level programs, thus interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly.
8.      In addition, interpreters are often used in education because they allow students to program interactively.

Examples of Programming Languages Using Interpreter :

Lisp

(defun convert ()
(format t "Enter Fahrenheit ")
(LET (fahr)
(SETQ fahr(read fahr))
(APPEND '(celsisus is)(*(-fahr32)(/59)))
)
)

BASIC

CLS
INPUT "Enter your name: ", Name$
IF Name$="Mike" THEN 
PRINT "Go Away!"
ELSE
    PRINT "Hello, "; Name$;".  How are you today?"
END IF
Interpreter in Programming Language

Difference between Compiler and Interpreter

No
Compiler
Interpreter
1
Compiler Takes Entireprogram as input
Interpreter Takes Singleinstruction as input .
2
Intermediate Object Code isGenerated
No Intermediate Object Code is Generated
3
Conditional Control Statements are Executesfaster
Conditional Control Statements are Executes slower
4
Memory Requirement :More (Since Object Code is Generated)
Memory Requirement isLess
5
Program need not becompiled every time
Every time higher level program is converted into lower level program
6
Errors are displayed afterentire program is checked
Errors are displayed foreveryinstructioninterpreted (if any)
7
Example : C Compiler
Example : BASIC

Explanation : Compiler Vs Interpreter

Just understand the concept of the compiler and interpreter -
1.       We give complete program as input to the compiler. Our program is in the human readable format.
2.      Human readable format undergoes many passes and phases of compiler and finally it is converted into the machine readable format.
3.      However interpreter takes single line of code as input at a time and execute that line. It will terminate the execution of the code as soon as it finds the error.
4.      Memory requirement is less in Case of interpreter because no object code is created in case of interpreter.
Following video will say much more about compiler -

Step By Step Execution Of C Program

Step 1 : Edit

1.       This is First Step i.e Creating and Editing Program.
2.      First Write C Program using Text Editor , such as [ Borland C/C++ 3.0 , Notpad++,Notpad ]
3.      Save Program by using [.C] Extension.
4.      File Saved with [.C] extension is called “Source Program“.

Step 2 : Compiling

1.       Compiling C Program : C Source code with [.C] Extension is given as input to compiler and compiler convert it into Equivalent Machine Instruction.
2.      In Borland C/C++ 3.0 program can be compiled using key [Alt + F9 ].
3.      Compiler Checks for errors . If source code is error-free then Code is converted into Object File [.Obj ].
http://img.c4learn.com/2011/12/Execution_of_C_programming_Code1.jpg

Step 3 : Checking Errors

1.       During Compilation Compiler will check for error, If compiler finds any error then it will report it.
2.      User have to re-edit the program.
3.      After re-editing program , Compiler again check for any error.
4.      If program is error-free then program is linked with appropriate libraries.

Step 4 : Linking Libraries

1.       Program is linked with included header files.
2.      Program is linked with other libraries.
3.      This process is executed by Linker.

Step 5 : Error Checking

1.       If run time error occurs then “Run-time” errors are reported to user.
2.      Again programmer have to review code and check for the solution.

What is Low level Language in Computer Science ?

·         Machine understandable Language.
·         Assembly is Common High Level Language
·         Internal Machine Code dependent
·         Fast to Run But slow to write & Understand
What is Low Level Language ?

What is machine Level Language ?

1.       Machine code is the only language a microprocessor can process directly without a previous transformation.
2.      Currently, Programmers never write programs directly in machine code, because it requires attention to numerous details which a high-level language would handle automatically.
3.      Low Level Language Requires memorizing or looking up numerical codes for every instruction that is used.
4.      For this reason, second generation programming languages provideone abstraction level on top of the machine code.

Example: A function in 32-bit x86 machine code to calculate the nth Fibonacci number :

8B542408 83FA0077 06B80000 0000C383
FA027706 B8010000 00C353BB 01000000
B9010000 008D0419 83FA0376 078BD98B
C84AEBF1 5BC3
Higher Level Languages and Middle Level languages are different than Low Level Language in many aspects.

Summary of Lower Level Languages :

Low level languages are Machine Understandable, difficult to write, requires more efforts to code and debug.

Middle Level Language ?

C Programming bridges gap between traditional Machine Understandable Machine Level language and more conventional High level languages. User can Use C Language to do system programming for writing operating system as well as application programming.
Middle Level Programming languages are closely related to  Machine as well as Human Being.

Why C is Middle Level Language ?

1.       C Programming Supports Inline Assembly Language Programs .
2.      Using inline assembly language feature in C  we can directly access system registers.
3.      C Programming is used to access memory directly using pointer.
4.      C Programming also Supports high Level Language Features.
5.      It is more User friendly as compare to Previous languages so C programming is Middle Level Language.
C Language is Middle Level Language
C Language is Middle Level Language

Tips : Middle Level Language

1.       Language is more Close to Machine
2.      Language is far from Human i,e human need to take more efforts to code
3.      We have to Write More Code to meet user requirement and It is Easy to create Machine Level Code using C Programming.



What is high Level Language and its Execution Model ?

High level Language :

1.       First high-level programming languages were designed in the 1950s.
2.      High level Language is Human understandable Language.
3.      English is Common example of High Level Language.
4.      High level Language is Internal Machine Code Independent.
5.      High level Language is Program Oriented Language.
6.      High level Language is Developed for providing GUI Interface.
Middle Level Language Programming Concept

Explanation :

As you can see the above diagram, it clearly shows that HLL are more close to human and can be easily programmed as compare to lower level language.In HLL Language and Machine gap is more.

C Programming can be considered as High Level / Low Level -

·         In early 70′s , C Programming was considered as High Level language because it was capable of evaluating expressions,parenthesis recursive functions etc.
·         Nowadays C may be considered as “Low Level Language” by some programmer because it lacks a large runtime-system (no garbage collection, etc.)

Execution Models of HLL :

1. Interpreted :

1.       Interpreted languages are read and then executed directly, with no compilation stage.
2.      Program is read line by line and convert it into machine code, and executes it. [More Info : Interpreter]

2. Compiled :

Languages are transformed into an executable form before running There are two types of compilation:

2.1 Machine code generation

Some compilers compile source code directly into machine code. Machine code is generated by using compiler it is called as “truly compiled” languages.

2.2 Intermediate representations

Language is converted into middle level language and further optimized and reused.

3. Translated :

1.       A language may be translated into a lower-level programming language for which native code compilers are already widely available.
2.      The C programming language is a common target for such translators.

Some High Level Languages :

1.       Ada
2.      Algol
3.      LISP
4.      Pascal
5.      Prolog.
6.      Java
7.      C#

Single Line Comment

Comments are non-executable code used to provide documentation to programmer. Single Line Comment is used to  comment out just Single Line in the Code. It is used to provide One Liner Description of line.

Some ImportatntPoints :

1.       Single Line Comment Can be Placed Anywhere
2.      Single Line Comment Starts with ‘//’
3.      Any Symbols written after ‘//’ are ignored by Compiler
4.      Comment cannot hide statements written before ‘//’ and On the Successive new line

Live Example :

#include<stdio.h>
void main()
{
printf("Hello"); //Single Line Comment
printf("By");
}

Which Part is Ignored by Compiler ? [Shown by Asterisk]

#include<stdio.h>
voidmain()
{
printf("Hello");// ********** Until Line Ends *****
printf("By");
}

Explanation :

1.       In the above code we have included Single Line Comment. Single Line Comment can be used anywhere in the code.
2.      Single Line Comment ignores the complete line from the position where it has been written.Therefor Single line comment is written usually after termination of statement.
3.      For Multiple Line Comment we have another approach.Learn More on Difference between Single Line and Multiple Line Comment.

Different Ways of Writing Singular Line Comment :

For Specifying Operation

#include<stdio.h>
intmain()
{
intcvar=1,dvar=2;// Declare Variables
int sum =0;// Declare Sum
sum=cvar+dvar;// Compute Sum
printf("Sum : %d",sum);
return(0);
}
We can use this type of comment to specify the operation that we are performing or to specify the formula used.
Multi Line Comment
·         Multi Line Comment Can be Placed Anywhere.
·         Multi Line Comment Starts with ‘/*’ .
·         Multi Line Comment Ends with ‘*/’ .
·         Any Symbols written between ‘/*’  and ‘*/’ are ignored by Compiler.
·         It can be split over multiple Lines


Chapter 3 : Variables and Constants

C Tokens Chart

·         In C Programming punctuation,individualwords,charactersetc are called tokens.
·         Tokens are basic building blocks of C Programming
Tokens in C Programming - Basic Building Blocks

Example :

No
Token Type
Example 1
Example 2
1
Keyword
do
while
2
Constants
number
sum
3
Identifier
-76
89
4
String
HTF”
PRIT”
5
Special Symbol
*
@
6
Operators
++
/

Basic Building Blocks and Definition :

Token
Meaning
Keyword
A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer
Constant
Constants are expressions with a fixed value
Identifier
The term identifier is usually used for variable names
String
Sequence of characters
Special Symbol
Symbols other than the Alphabets and Digits and white-spaces
Operators
A symbol that represent a specific mathematical or non mathematical action

What is Variable in C Programming

Variable in C Programming is also called as container to store the data. Variable name may have different data types to identify the type of value stored. Suppose we declare variable of type integer then it can store only integer values.Variable is considered as one of the building block of C Programming which is also called as identifier.
A Variable is a name given to the memory location where the actual data is stored.
Consider real time example , suppose we need to store water then we can store water in glass if quantity of water is small and Bucket is the quantity of water is large. And big can to store water having quantity larger than bucket similarly Variable (i.e Value container) may have different size for storing different verities of values.

Fundamental Attributes of C Variable :

1.       Name of a Variable
2.      Value Inside Variable
3.      Address of Variable
4.      Size of a Variable
5.      Type of a Variable

1.Name of Variable

·         We can Give proper name to any Variable which is human readable.
·         Compiler won’t understand this name , This is only for human understanding.
·         Variable name is only the name given to the “Memory address”.
·         Variable name maps into “Address inside” and then by considering mapped address compiler processes data.
·         We have declared variable means “We have created one empty container which will hold data“.

2.Value inside Variable

·         Depending on the type of Variable we can store any value of appropriate data type inside Variable.
·         Suppose we have “Integer Variable” then Value inside variable will be of type “Integer“.
·         Simple Variable can only hold one value at a time.

3.Address of Variable

·         Variable can hold data ,it means there should be a container.
·         So container must have Starting Address.
·         Address of variable = Starting Address of Memory where Memory is allocated to Variable.

4.Type of Variable

·         While declaring a variable we have to specify type of variable.
·         Type of variable tells compiler that – “Allocate memory for data of Specified type“.
·         If we declare variable of type Integer then compiler will allocate memory container of size 2 bytes and container will be able to store integer data only.

5.Size of Variable

·         We can use sizeof operator to calculate size of any data type.


Variable attributes
Variable attributes
Variable Name
ivar
Variable Type
Integer
Variable Address
2000
Variable Size
2 Bytes
Variable Value
34

What is Local Variable ?

1.       Local Variable is Variable having Local Scope.
2.      Local Variable is accessible only from function or block in which it is declared .
3.      Local variable is given Higher Priority than the Global Variable.
Above Fig.  Tells us that – Above Program has 2 blocks i.e Inner Block and Outer Block
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIXu5_oyfW9RnjPG3oPp7SCodkWamXPhsgDIZXo9_ZZGMmhZCWhsd-ughKZ6BT6EFuPBZfDfmpHSpqrVom6rZVR_nvYwxkvrmRaB0LNX4ZRS34h0K2CttO6W1n27mjBoTIdL7gr4e8DypM/s400/local_variable_in_c.bmp

Facts about Local Variable :

1.       Variables declared inside outer block are visible or meaningful only inside outer block.
o    Example : var1 is Local to Outer Block.
o    var1 cannot be accessed from its outer block.
o    var1 cannot be accessed from Other Function or other block
o    var1 can be accessed from inner block
2.      Similarly Variables declared inside inner block are visible or meaningful only inside Inner block.
3.      Variables declared inside inner block are not accessed by outer block .i.e
#include<stdio.h>
voidmain()
{
int var1=10;
{
int var2 =20;
printf("%d%d",var1,var2);// Legal : var1 can be accessed
}
printf("%d%d",var1,var2);// Error : var2 is not declared
}

Short Summary :

Inner Block can access variables declared inside Outer Block
Outer block can’t access variables declared inside Inner Block
Global Variable : 
1.       Global Variable is Variable that is Globally available.
2.      Scope of Global variable is throughout the program [ i.e in all functions including main() ]
3.      Global variable is also visible inside function , provided that it should not be re-declared with same name inside function because … “High Priority is given to Local Variable than Global
4.      Global variable can be accessed from any function.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2zDuUNJrPq3qV5LNeeVYl0_mjz9DfZ9i1Ewn_Re2_r_JVjhNPaPc120ZTv47w6oIn1pMhpjPQ4HJfabt5nfGVnlwyBVfZLpSwKnHezyJNbEuru_Fm4MgoI7EgpsE3-SEa23CJpTPcFbaw/s400/global+and+Local+variable.bmp
#include<stdio.h>
intvar=10;
void message();
voidmain()
{
intvar=20;
{
intvar=30;
printf("%d",var);
}
printf("%d",var);
message();
}

void message()
{
printf("%d",var);
}
Output :
30 20 10
·         Inside message() ‘var’ is not declared so global version of ‘var’ is used , so 10 will be printed.
{  intvar = 30;  printf("%d ",var);   }
·         Here variable is re-declared inside block , so Local version is used and 30 will be printed.


In Short -
1.       For Inner Block variables declared in Outer Block acts as “Global Variable“.
2.      If block contain undefined variable then -
o    It checks occurrence of that variable in outer block .
o    If it is also undefined in outer block then global version is used .
o    If it also undeclared globally then its extern definition is checkedif not found then it throws error.

Rules For Constructing Variable Name

1.       Characters Allowed :
o    Underscore(_)
o    Capital Letters ( A – Z )
o    Small Letters ( a – z )
o    Digits ( 0 – 9 )
2.      Blanks & Commas are not allowed
3.      No Special Symbols other than underscore(_) are allowed
4.      First Character should be alphabet or Underscore
5.      Variable name Should not be Reserved Word

Explanation with Example

Tip 1 : Use allowed Characters

Valid Names
num
Num
Num1
_NUM
NUM_temp2

Tip 2 : blanks are not allowed

Invalid Names
number1
num1
addition of program

Tip 3 : No special symbols other that underscore

Valid Identifier
num_1
number_of_values
status_flag

Tip 4 : First Character must be underscore or Alphabet

Valid Identifier
_num1
Num
Num_
_
__
Invalid Identifier
1num
1_num
365_days

Tip 5 : Reserve words are not allowed

·         C is case sensitive.
·         Variable name should not be Reserve word.
·         However if we capitalize any Letter from Reserve word then it will become legal variable name.
Valid Identifier
iNt
Char
Continue
CONTINUE
Invalid Identifier
int
char
continue

Tip 6 : Name of Identifier cannot be global identifier

Basic Note :
·         Global predefined macro starts with underscore. (_) .
·         We cannot use Global predefined macro as our function name.
Example : Some of the predefined macros in C
·         __TIME__
·         __DATE__
·         __FILE__
·         __LINE__
Valid Identifier
__NAME__
__SUM__
Invalid Identifier
__TIME__
__DATE__
__FILE__

Tip 7 : Name of identifier cannot be register Pseudo variables

Invalid Example :
#include<stdio.h>
intmain(){
longint _AH =15;
printf("%ld",_AH);
return0;
}

Tip 8 : Name of identifier cannot be exactly same as of name of another identifier within the scope of the function

Valid Example :
#include<stdio.h>
intmain(){
intivar=15;
{
intivar=20;
printf("%d",ivar);
}
return0;
}
Invalid Example : We cannot declare same variable twice within same scope
#include<stdio.h>
intmain(){
intivar=15;
intivar=20;
printf("%d",ivar);
return0;
}

Tip 9 : Constants

1.       We know that M_PI constant is declared inside math.h header file.
2.      Suppose in our program we have declared variable M_PI and we have not included math.h header file then it is legal variable.
Legal Example :
#include<stdio.h>
intmain(){
int M_PI=25;
printf("%d",M_PI);
return0;
}
Output :
 25
Illegal Example :
#include<stdio.h>
#include<math.h>
 
intmain(){
int M_PI=25;
printf("%d",M_PI);
return0;
}
Output :
 Compile error

Remember following Tricks

1.       Do not Create unnecessarily long variable name
2.      Do not use underscore as first character to avoid confusion between System Variable & user defined variables because many system variables starts with undescore
3.      Variable names are case-Sensitive .i.e sum,Sum,SUM these all three are different variable names.
4.      Reserve words with one/more Capital letters allowed eg. Int,Float,chAr are allowed but try to skip them.

What is Constant ?

Constant in C means the content whose value does not change at the time of execution of a program.

Definition :

Constant means “Whose value cannot be changed
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfGf8uugM198mqBteo-T-L12wqfIrsKC4RGDuZPJYkLY_8YTJpgY4hrbsDfE1Cy88pdd4gzQUC3Y207eW6ms4-nPqsIJdMx7Y95bH2ZnC_S4NMWa_47Trg9ShqLK4r3j-hBUeR36EifgVq/s320/Constant+Variable.jpg

Explanation :

·         Initially 5 is Stored in memory location and name x is given to it
·         After We are assigning the new value (3) to the same memory location
·         This would Overwrite the earlier value 5 since memory location can hold only one value at a time
·         The value of ’3′,’5′ do not change ,so they are constants
·         In Short the ‘Values of Constant Does not Change‘.

Different Types of C Constants :

Constant
Type of Value Stored
Integer Constant
Constant which stores integer value
Floating Constant
Constant which stores float value
Character Constant
Constant which stores character value
String Constant
Constant which stores string value

How to Declare Constant in C :

We can declare constant using const variable. Suppose we need to declare constant of type integer then we can have following two ways to declare it -
constint a =1;
intconst a =1;
above declaration is bit confusing but no need to worry, We can start reading these variables from right to left. i.e
Declaration
Explanation
constint a =1;
read as “a is an integer which is constant”
intconst a =1;
read as “a is a constant integer”

Keywords in C Programming Language :

1.       Keywords are those words whose meaning is already defined by Compiler
2.      Cannot be used as Variable Name
3.      There are 32 Keywords in C
4.      C Keywords are also called as Reserved words .

32 Keywords in C Programming Language

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

Simple Tip :

We cannot Use Keywords for – For Declaring Variable Name,For Function Name and for declaring Constant Variable










C - Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the programming languages:
Decision making statements in C
Statement
Description
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
You can use one if or else if statement inside another if or else if statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
You can use one swicth statement inside another switchstatement(s).

The ? : Operator:

We have covered conditional operator ? : in previous chapter which can be used to replace if...elsestatements. It has the following general form:
Exp1?Exp2:Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ?expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ?expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

If Statement :

This is a conditional statement used in C to check condition or to control the flow of execution of statements. This is also called as 'decision making statement or control statement.' The execution of a whole program is done in one direction only.
Syntax:
 
if(condition)
{
       statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces. If there are more than 1 (one) statements in if statement then use { } braces else it is not necessary to use.

Program :


/*  Program to demonstrate if statement.*/



#include <stdio.h>
#include <conio.h>
void main()
{
       int a;
       a=5;
       clrscr();
       if(a>4)
              printf("\nValue of A is greater than 4 !");
       if(a==4)
              printf("\n\n Value of A is 4 !");
       getch();
}


Output :



 
Value of A is greater than 4 !_

 

 

 

 

 

 

 

 

 

 

 

 

If-Else Statement :

This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
 
if(condition)
{
       true statements;
}
else
{
       false statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then it executes the else part of a program.

Program :


/*  Program to demonstrate if-else statement.*/



#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n Enter Number :");
       scanf("%d",&no);
       if(no%2==0)
              printf("\n\n Number is even !");
       else
              printf("\n\n Number is odd !");
       getch();
}


Output :



Enter Number : 11
 
Number is odd !_







Nested If-Else Statement :

It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute.
Syntax:
 
if(condition)
{
       if(condition)
       {
              statements;
       }
       else
       {
              statements;
       }
}
else
{
       statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and again checks the next condition. If it is true then it executes the block of statements associated with it else executes else part.

Program :


/*  Program to demonstrate nested if-else statement.*/



#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n Enter Number :");
       scanf("%d",&no);
       if(no>0)
       {
              printf("\n\n Number is greater than 0 !");
       }
       else
       {
              if(no==0)
              {
                    printf("\n\n It is 0 !");
              }
              else
              {
                    printf("Number is less than 0 !");
              }
       }
       getch();
}


Output :



Enter Number : 0
 
It is 0 !_




Switch case Statement :

This is a multiple or multiwaybrancing decision making statement.
When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax:

The syntax for a switch statement in C programming language is as follows:
switch(expression){
case constant-expression  :
statement(s);
break;/* optional */
case constant-expression  :
statement(s);
break;/* optional */
 
/* you can have any number of case statements */
default:/* Optional */
statement(s);
}
The following rules apply to a switch statement:
·         The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
·         You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
·         The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
·         When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
·         When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
·         Not every case needs to contain a break. If no break appears, the flow of control will fall throughto subsequent cases until a break is reached.
·         A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. Nobreak is needed in the default case.

Flow Diagram:

switch statement in C

Example:

#include<stdio.h>
 
int main ()
{
/* local variable definition */
char grade ='B';
 
switch(grade)
{
case'A':
printf("Excellent!\n");
break;
case'B':
case'C':
printf("Well done\n");
break;
case'D':
printf("You passed\n");
break;
case'F':
printf("Better try again\n");
break;
default:
printf("Invalid grade\n");
}
printf("Your grade is  %c\n", grade );
 
return0;
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is B

Program :


/*  Program to demonstrate switch case statement.*/



#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n Enter any number from 1 to 3 :");
       scanf("%d",&no);
       switch(no)
       {
              case 1:
                    printf("\n\n It is 1 !");
                     break;
              case 2:
                    printf("\n\n It is 2 !");
                    break;
              case 3:
                    printf("\n\n It is 3 !");
                    break;
              default:
                    printf("\n\n Invalid number !");
       }
       getch();
}


Output 1 :



Enter any number from 1 to 3 : 3
 
It is 3 !_





Output 2 :



Enter any number from 1 to 3 : 5
 
Invalid number !_





* RULES FOR DECLARING SWITCH CASE :

·         The case label should be integer or character constant.
·         Each compound statement of a switch case should contain break statement to exit from case.
·         Case labels must end with (:) colon.

* ADVANTAGES OF SWITCH CASE :

·         Easy to use.
·         Easy to find out errors.
·         Debugging is made easy in switch case.
·         Complexity of a program is minimized.

No comments:

Post a Comment