C Language
(The heart of ECE)
Introduction to programming
Software :- Software is a set of programs that perform some set of tasks.
Program :- A program is a set of instructions given to the computer to perform some specific
tasks.
Algorithm :- Algorithm is a sequence of steps that are used to write a program. It creates logic.
Problems involved in solving a problem:-
User Requirement
⬇️
Problem Analysis
⬇️
Input and Output
⬇️
Detailed Algorithm
⬇️
Coding
Types of Approach:-
1. Top down Approach:- In this type of approach, first the complex problem is simplified into
small and easy problem such that it become easier to solve the problems.
2. Bottom-Up Approach:- In this type of approach, first the small problems are converted into
large problems as they mentioned in the name.
3. Modular Approach:- In this type of approach, the big problem is converted into very small
modules such that the module will be solved and by mixing all the small modules, we obtain
the solution for the large problem.
Programming Languages:-
Computer can’t understand human language directly, I only understand the digital signals (0 and 1).
Then here comes the concept programming languages. The user write the set of instructions
interms of programming languages. Then the translator converts the programming language into
binary language.
Types of Programming languages:-
o Low level language:- Low level language is very close to the computer language. But
these are very fast to execute and efficiency is also high.
1. Machine Level Language:- It is in the form of 0s and 1s. These are fast and
efficient. These are prone and difficult. They are not portable.
2. Assembly language :- These are in the form of shortcuts of human language, but
also difficult to remember large number of keywords. These are not portable.
o High level language:- High level language are very close to human language and
these are also portable and slower execution time compared to the low level
language.
Types of translators:-
Assembler :-
This translator converts the assembly language into the machine level language.
Compiler :-
This translator translates the high level language into the Machine level language.
Interpreter :-
This translator translates the high level language into the low level language
History of C :-
Origin:-
Developed by Dennis Ritchie at Bell laboratories in USA in 1972 to develop UNIX OS.
Based on:-
Derived from B (Developed by Ken Thompson) which is derived form BCPL.
Standardization:-
In 1979, it came into force by the book written by the developers.
In 1989, it was standardized by ANSI C.
Impact:-
It becomes the base for many languages.
Characteristics of C:-
1) Portable
2) Smallest (32 keywords)
3) Mid level
4) Case sensitive
Structure of C programming:-
Comments
Header files
Global declaration
Main function
{
………….
………….
}
Sub functions
{
………….
………….
}
Comments :- These are used to mention the dates, purpose and etc.., and these are not used by the
translator Header files :- These are preprocessor directives that are already defined in preprocessor and
these starts with #.
Global Declaration :- Anything that need to be defined for the whole program can be defined here.
Elements of C
Character set:-
1) Alphabets:-
A,B,C,D,……….
2) Numbers:-
1,2,3,4,………..
3) Special Characters:-
*,”,’,:,;,,,!,?,@,#,$,_,&,-,+,(,),/,~,`,|,÷,×,^,=,{,},\,%,[,].
Execution Operation/Escape Sequence:-
All the characters are not entered directly. Some are entered by using escape sequence/ execution
operations. They start with backward slash(\).
Execution ASCII Purpose
Operator code
\a (Bell) 007 Rings sound, when the compiler detects this.
Deletes the character. Recent compilers deletes character, if
\b (Backspace) 008
there is something to replace that character.
\f (Form feed) 012 Moves the cursor to the initial position of the next logic page.
\n (New line) 010 Moves the cursor to the next new line.
\0 (Null) 000 Null. Used in strings.
\r (Carriage
013 Moves the cursor to the initial position of the same line.
return)
\t (Horiz. Tab) 009 Gives a horizontal tab space.
\v (Vert. Tab) 011 Gives a vertical tab space.
\\ (Backslash) 092 To print backslash
Trigraph Character:-
Imagine if the keyboard doesn’t contain some characters or in some keyboards some characters
doesn’t work. Then comes the concept trigraph character. It starts with ?? followed by some
character.
??= - #
??< -{
??> -}
??( -[
??) -]
??! -|
??/ -\
??- -~
??’ -^
Delimiters:-
These are used to separate different parts of the code.
These define the structure of the code.
: used for label
; end of the statement
, separate variables
() Used for expression
[] Array
{ } Differ functions.
# preprocessor directives
Keywords:-
These are reserved words. These are already predefined in the preprocessor. These have fixed
meanings which can’t be able to change. C language consists of 32 keywords. These are always
lower case letters.
Identifiers:-
These are used defined names of the variable, constant, functions and etc.., These are used defined
but these are not predefined.
Rules:-
1) Case sensitive.
2) No keywords are allowed as identifiers.
3) No special Characters are allowed except underscore(_).
4) Consists of alphanumerical and underscore.
5) Starts with alphabet or either underscore but not with numerical.
6) Some implementations of C recognizes only first 8 characters. While according to ANSI C only
first 31 characters are allowed.
Datatypes:-
In C, data types define the type of data a variable can hold.
Data Types
Primary (Basic) Derived Enumeration
Int (Integer Value)
Float (Single precision Arrays
decimals)
Pointers
Double (Double
Structures Enum
precision decimals)
Unions
Char (Single character)
Strings
Void (Empty)
There are 4 types of qualifiers in C language related to datatypes.
Size qualifiers:- Long, short
Sign qualifiers:- Signed, unsigned
When unsigned qualifier is used, the number must be positive.
If sign qualifiers is not mentioned, then by default it considered it as signed qualifier.
For calculating range, the formula can be used is
For signed, range = -2n-1 to 2n-1-1
For unsigned, range = 0 to 2n-1
Constant:-
The value that can’t be changed and it is fixed is called constant.
Types of constants:-
1) Numeric
a. Integer
i. Decimal
ii. Octal
iii. Hexadecimal
b. Real
2) Character
3) String
1) Numeric constant:-
Contains at least one digit.
No comma or space between numeric.
Either positive or negative.
a. Integer:-
Decimal: 0,1,2,3,4,5,6,7,8,9
Octal: 0,1,2,3,4,5,6,7
Hexadecimal: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
In octal integer, the number must start with 0
In hexadecimal, the decimal must start with 0x
If the value of decimal exceeds the range, then it need to be considered as unsigned. We can
mention by sufficing it with L or UL.
b. Floating point:-
Single precision decimals.
Precision: 6 digits
c. Double:-
Double precision digits.
Precision: 15-16 digits
Float: Saves memory, faster on small systems (e.g., embedded systems).
Double: Gives better precision for scientific and financial calculations.
Some times they use mantissa to represent them
Ex:-
18000000= 18e6
e- mantissa
6- exponent
2) Character constant:-
Character constant is a single character that is enclosed within the single quote.
Ex: ‘A’
Every character has its own integer value known as ASCII (American Standard Code for Information
Interchange).
A-Z :- 65-90
a-z :- 97-122
0-9 :- 48-57
; :- 59
3) String Constant:-
String Constant is basically used for zero, one or more characters.
These are placed under double quote.
“A”≠’A’
4) Symbolic constant:-
To define a constant that is to be used in the entire cone then it should be declared in a way that
#define name value
Variable:-
A value that cant be constant is called a variable.
The value can be changed at any instant.
Declaration:- datatype variable_name;
Initialization:- variable_name= value;
Expression:-
A combination of operators, constants, variables of function calls.
The set of library functions that consists of input and output functions is called standard input
output functions.
If a program consists of input and output functions, then he should must include header file
(stdio.h)
For the use of integers characters we need to use the control string.
%d-integer
%f-float
%lf-double
%Lf-long double
%c-character
%s-string
%o-octal
%x-hexadecimal
Reading input data:-
We use scanf for reading input data.
Syntax:- scanf(“controlstring”,&variablename);
Showing output data:-
We use printf for showing output data.
Syntax:- printf(“controlstring”,variablename);
Format for integer input:-
%wd
W- data length
Program:-
Output:-
Here in the first case (w<data length) , it only recognizes first w elements and the remaining elements are
shifted to the next statement.
Format integer output:-
If the given number is less than w, then the blank will be left.
Program:-
Output:-
Format integer input and output:-
Same as integer, but it counts point also as a digit, if any blank left in input it would consider as 0.
Sometime it also mentioned as %w.af
Here, w is the total length
a is the length after point
Format for string input:-
Input is same as integer but at last null character is added automatically
Format for string output:-
There leave blanks for the extra ones of w>datalength
If it uses %w.as
Then w is the size of the string and a is the no of characters form the start.
Suppression character in C:-
%*d,%*f,etc..,
Here * is the suppression character, it means it holds the next character.
Character I/O:-
These macros getchar() and putchar() can be used for character I/O.
Getchar() reads a single character from the standard input.
Putchar() outputs one character at a time to the standard output.
Program
#include <stdio.h>
Main()
{
Char ch;
Printf(“Enter a character : “);
Ch = getchar();
Printf(“The entered character is : “);
Putchar(ch);
}
Output:
Enter a character : B
The entered character is : B
Operators and Expressions
Operator:-
An operator specifies the operation need to be takes place.
Operand:-
A data item in which operator acts is called operand.
Arithmetic Operator:-
Used for numeric calculations and these are of two types, they are
1. Unary Operator:-
+ Nothing happens.
-Changes the sign of the operand.
Unary Operator requires only one operand.
2. Binary Operator:-
It needs two operands to act.
Operator Operation
+ It adds two operands.
- It subtracts the second operand from the first operand
*(Asterisk) It products two operands
/(Forward slash) It divides and results in quotient
% It divides and results in remainder
Modulus and it doesn’t applicable on floating point.
Assignment Operator:-
The operator that is used to assign a value to a variable is called assignment operator.
= Assignment operator.
If we end the statement with semicolon in which assignment takes place is called assignment
statement.
There are several compound assignment operator. They are
+=,-=,*=,/=,%=.
Here a+=b means that a=a+b and same for the remaining cases.
Increment/Decrement Operator:-
There is a concept called increment or Decrement Operator, in which it behaves a unary Operator as
they operates in single operand.
These works only on variables but not on constants and expressions.
++5,++(x+y+z) are invalid.
Prefix increment/decrement:-
In this type of operation first the value will be increased or decreased based on condition
taken and then the value will be used in the operation.
Y=++x is equal to x=x+1 and then y=x.
Y=--x is equal to x=x-1 and then y=x.
Postfix increment/decrement:-
In this type of operation first the value will be assigned and the value will be increased or
decreased based on the condition taken.
Y=x—is equal to y=x and x=x-1
Y=x++ is equal to y=x and x=x+1
Relational Operator:-
It gives the relation between two operands. It compares two operands.
Operato If true it returns If false it returns
r
<= 1 0
>= 1 0
== 1 0
!= 1 0
< 1 0
> 1 0
Logical or Boolean operator:-
An expression that contains two or more expressions is called logical expression.
Operator Purpose
&&(and) It is inserted between two expressions. If the both expressions are correct, then it returns 1
or if any expression between them is wrong then it returns 0
||(or) It is inserted between two expressions, if either both the expressions or any one of them are
correct, it returns 1 otherwise it returns 0.
!(Not) It states that if the result in the statement is true then it results false(0). And vice-versa.
Conditional Operator:-
It is in the form of (Test expression? Expression 1: Expression 2)
It says that if the test expression is true, then expression 1 is the final expression need to be
evaluated, if it fails then expression 2 will be the test expression.
Comma Operator:-
It is used to differ the expressions.
Ex:-
Sum=(a=8,b=2,a+b);
Size of Operator:-
It is used to find the size .
Sizeof(var/datatype).
Bitwise operators:-
It will discuss in the upcoming sessions.
Control Statements
Control Statements enables us to execute specific statement based on the conditions in the
controlled way.
Compound statement or block:-
Compound statement or a block is a set of statements that is enclosed within a braces is called
compound statement or a block.
Control Statements are many types they are,
1) If
2) If else
3) Else if
4) Nested if else
5) Loops
5.1) for
5.2)while
5.3)do while
Loops:-
Loops are used to execute a set of statements for several time, so we need to write the same
statement for several times, instead we use loops.
While loop:-
Syntax:-
Initial value
While(condition)
{
…….
…….
…….
Update expression
}
Do while loop:-
Do{
….
…..
……
}While(condition);
For loop:-
For(initialization; condition; update expression);
{
……
…….
……..
}
The loops that go on terminating after infinite iterations are called infinite loops.
For for loop:-
For ( ; ; )
{
…
…
}
For while loop:-
While(1)
{
…
…
}
For do while loop:-
Do
{
..
..
}while(1);
Break Statement:-
It is used to break a loop after it gets noticed by the compiler and are used inside the loops. This
statement causes a immediate exit from the loop.
Continue Statement:-
It is also used in loops after it gets noticed that iteration gets terminated and next iteration
continues.
Goto:-
If this encountered by a compiler then the compiler moves to the statement mentioned in the label.
Syntax:-
Goto label;
……..
……..
Label:
Statement;
…………….
Switch:-
In C, a switch statement is used to execute one block of code out of many options, based on the
value of a variable or expression. It’s an alternative to writing many if-else statements when you’re
checking the same variable for multiple values.
Syntax:
Switch (expression) {
Case value1:
// Code to execute if expression == value1
Break;
Case value2:
// Code to execute if expression == value2
Break;
…
Default:
// Code to execute if expression doesn’t match any case
}
Example:
#include <stdio.h>
Int main() {
Int day = 3;
Switch (day) {
Case 1:
Printf(“Monday\n”);
Break;
Case 2:
Printf(“Tuesday\n”);
Break;
Case 3:
Printf(“Wednesday\n”);
Break;
Case 4:
Printf(“Thursday\n”);
Break;
Case 5:
Printf(“Friday\n”);
Break;
Case 6:
Printf(“Saturday\n”);
Break;
Case 7:
Printf(“Sunday\n”);
Break;
Default:
Printf(“Invalid day\n”);
}
Return 0;
}
Notes:
The break statement prevents the code from “falling through” to the next case.
If break is omitted, execution continues into the next case.
Default is optional and is executed if no case matches.
Functions
Function:-
A function is a block of code that performs some specific tasks.
C program has two different types of functions, they are,
1) Library functions
2) User defined functions.
Library functions:-
C has the ability to access some library functions, these are already defined in preprocessor. We just
need to include some header files to access the library functions.
User defined functions:-
Users can create their own functions that perform separate set of tasks.
There are three things we need to focus on,
1) Function definition.
2) Function declaration.
3) Function call.
Function definition:-
The function definition consists of the whole code that the function need to be executed.
In this function can be defined.
Syntax:-
return type func_name(type1 arg1, type2 arg2,…………., typen argn) //function header
{
local variable;
…………..
return (expression);
}
After function name, the arguments need to be declared in their respective types. These are known
as formal arguments and these are used to accept values.
The variables declared inside the function is called local variables.
Function call:-
It is used to call the function which is defined in the code.
Syntax:-
func_name(arg1,arg2,……);
Arg1, arg2 , arg3 are called the actual arguments.
The function call is written on the right hand side of the operator.
The value returned is assigned to the left operand.
A function call can’t be placed on the left hand side and it is invalid.
If a function is defined and not called, then the code will not be executed.
Function Declaration:-
The function need to be declared before the use. If the function is defined before the function call,
then there is no need to declare a function.
Example program:-
Code:-
#include<stdio.h>
Int sum( int, int); //Function declaration
Int main()
{
Int a,b,c;
Printf(“Enter the numbers to be add:”);
Scanf(“%d %d”,&a,&b);
C=sum(a,b);//Function Call
Printf(“The sum of two numbers is %d.”,c);
Return 0;
}
Int sum(int a, int b)// Function Definition
{
Return a+b;
}
Output:-
Enter the numbers to be add:2 3
The sum of two numbers is 5.
[Program finished]
Function Arguments:-
These are of two types they are,
1) Actual Arguments/Actual parameters
2) Formal Arguments/ Formal parameters
1) Actual Arguments:-
The arguments which are mentioned in function call is called actual arguments. (Or)
The values which are sent to the called function is called Actual Arguments.
2) Formal Arguments:-
The arguments which are mentioned in the function definition is called formal
arguments. (Or) The arguments which are received by the function is called formal
arguments.
Types of Functions:-
1) Function with arguments and with return values.
2) Function with arguments and without return values.
3) Function without arguments and with return values.
4) Function without arguments and without return values.
If actual arguments > formal arguments, then the extra arguments will be ignored.
If actual arguments < formal arguments, then the garbage value will be taken in the vacant places.