0% found this document useful (0 votes)
52 views

BPL C Programming 2024

Uploaded by

Santhosh Sgrao
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

BPL C Programming 2024

Uploaded by

Santhosh Sgrao
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

dge Course:

ics of Programming and Computer Organization


C PROGRAMMING TUTORIAL
By : santhosh SG, Assoc.Prof., JNN College of Engg

[email protected]
i
Table of Contents
Module-1
C Programming: decision making, control structures and arrays
C Structure, Data Types, Input-Output Statements, Decision making with if statement, simple if statement,
the if..else statement, nesting of if..else statements, the else.if ladder, the switch statement, the ?: operator,
the goto statement, the break statement, programming examples. The while statement, the do...while
statement, the for statement, nested loops, jumps in loops, the continue statement, programming
examples. One dimensional and two dimensional arrays, declaration and initialization of arrays, reading,
writing and manipulation of above types of arrays.
Module-2
Structures
Defining a structure, declaring structure variables, accessing structure members, structure initialization,
copying and comparing structure variables, operations on individual members, array of structures,
structures within structures, structures and functions, Unions, size of structures.
iii
Module-3
Pointers
Pointers in C, Declaring and accessing pointers in C, Pointer arithmetic, Functions , Call by value, Call by
reference, Pointer as function arguments, recursion, Passing arrays to functions, passing strings to functions,
Functions returning pointers, Pointers to functions, Programming Examples.

Module-4
Binary Systems and Combinational Logic
Digital Computers and Digital Systems, Binary Numbers, Number Base Conversion, Octal and Hexadecimal
Numbers, subtraction using r’s and r-1 complements, Binary Code, Binary Storage and Registers, Binary Logic,
Integrated Circuits, Digital Logic Gates

Module-5
Basic Structure of Computer Hardware and Software
Computer Types, Functional Units, Basic Operational Concepts, Bus structure, Software, Performance,
Multiprocessing and Multi computers, Machine Instruction: Memory Locations and Addresses, Memory
Operations, Instructions and Instruction Sequencing, Addressing Modes, Interrupts
iii
Chapter 1

Fundamental of C Programming
Language
and
Basic Input/Output Function

5
Chapter 1: Fundamental of C and Input/Output

In this chapter you will learn about:

C Development Environment C Program


Structure
Basic Data Types Input/Output function Common
Programming Error

6
History of C language
The base or father of programming languages is 'ALGOL.' It was first
introduced in 1960. 'ALGOL' was used on a large basis in European countries.
'ALGOL' introduced the concept of structured programming to the developer
community. In 1967, a new computer programming language was announced called
as 'BCPL' which stands for Basic Combined Programming Language.

BCPL was designed and developed by Martin Richards, especially for writing
system software. This was the era of programming languages.

Just after three years, in 1970 a new programming language called 'B' was
introduced by Ken Thompson that contained multiple features of 'BCPL.' This
programming language was created using UNIX operating system at AT&T and Bell
Laboratories. Both the 'BCPL' and 'B' were system programming languages.
What is C programming?
C is a general-purpose programming language that is extremely popular, simple and
flexible. It is machine-independent, structured programming language which is used
extensively in various applications.
C was the basic language to write everything from operating systems (Windows and
many others) to complex programs like the Oracle database, Git, Python interpreter
and more.
It is said that 'C' is a god's programming language. One can say, C is a base for the programming. If
you know 'C,' you can easily grasp the knowledge of the other programming languages that uses
the concept of 'C'
It is essential to have a background in computer memory mechanisms because it is an important
aspect when dealing with the C programming language.
In 1972, a great computer scientist Dennis
Ritchie created a new programming language
called 'C' at the Bell Laboratories. It was created
from 'ALGOL', 'BCPL' and 'B' programming
languages. 'C' programming language contains all
the features of these languages and many more
additional concepts that make it unique from
other languages.
History of C
How 'C' Works?
C is a compiled language. A compiler is a special tool that compiles the program
and converts it into the object file which is machine readable. After the compilation
process, the linker will combine different object files and creates a single executable file
to run the program. The following diagram shows the execution of a 'C' program

Nowadays, various compilers are available online, and you can use any of
those compilers. The functionality will never differ and most of the compilers will
provide the features required to execute both 'C' and 'C++' programs.
Summary
• 'C' was developed by Dennis Ritchie in 1972.
• It is a robust language.
• It is a low programming level language close to machine language

• It is widely used in the software development field.


• It is a procedure and structure oriented language.

• It has the full support of various operating systems and hardware platforms.
• Many compilers are available for executing programs written in 'C'.

• A compiler compiles the source file and generates an object file.


• A linker links all the object files together and creates one executable file.
• It is highly portable.
C Development Environment
Program is created
Phase 1 : Editor Disk using the Editor and
stored on Disk.

Preprocessor
Preprocessor program
Phase 2 : Disk
processes the
code.

Compiler creates
Phase 3 : Compiler Disk object code and
stores it on Disk.

Linker Linker links object


Phase 4 : Disk code with libraries,
creates a.out and
stores it on Disk

13
C Development Environment cont
Primary
Memory
Phase 5 : Loader
Loader puts
Program in
: Memory
.

Primary
Memory
Phase 6 : C P U (execute) CPU takes each instruction
and executes it, storing
new data values as the
: program executes.
.

Entering, translating, and running a High-Level Language Program

14
C Program Structure
An example of simple program in C

#include <stdio.h>

main(void)
{
printf(“I love programming\n”);
printf(“You will love it too once ”);
printf(“you know the trick\n”);
}

15
Preprocessor directives
a C program line begins with # provides an instruction to
the C preprocessor, It is executed before the actual
compilation is done.
Two most common directives :
• #include
• #define

In our example (#include<stdio.h>) identifies the header file


for standard input and output needed by the printf().
16
Function main
Identify the start of the program Every C
program has a main ( )
'main' is a C keyword. We must not use it for any
other variable.
4 common ways of main declaration
int main(void) void main(void) main(void) main( )
{ { { {

return 0;
} } } }

17
The curly braces { }
Identify a segment / body of a program
The start and end of a function

The start and end of the selection or repetition block.

Since the opening brace indicates the start of a segment with


the closing brace indicating the end of a segment, there
must be just as many opening braces as closing braces
(this is a common mistake of beginners)
18
Statement
A specification of an action to be taken by the computer as the
program executes.
Each statement in C needs to be terminated with semicolon (;)
Example:
#include <stdio.h>
void main(void)
{

printf(“I love programming\n”); statement

printf(“You will love it too once ”); statement

printf(“you know the trick\n”); statement

}
19
Statement cont…

Statement has two parts :


Declaration
The part of the program that tells the compiler the names of
memory cells in a program

Executable statements
Program lines that are converted to machine language
instructions and executed by the computer

20
C program skeleton
In short, the basic skeleton of a C program looks like
this:

#include <stdio.h> Preprocessor directives

void main(void) Function main


{ Start of segment

statement(s);

} End of segment

21
Identifiers
Words used to represent certain program entities
(variables, function names, etc).
Example:
int my_name;
my_name is an identifier used as a program variable

void CalculateTotal(int value)


Calculate Total is an identifier used as a function name

22
Variables
Variable  a name associated with a memory
cell whose value can change

Variable Declaration: specifies the type of a variable


Example: int num;

Variable Definition: assigning a value to the declared


variable
Example: num = 5;

23
Basic Data Types
There are 4 basic data types :
• int
• float
• double
• char
int
used to declare numeric program variables of integer type
whole numbers, positive and negative
keyword: int
int number;
number = 12;

24
Basic Data Types cont…
float
fractional parts, positive and negative keyword:
float
float height;
height = 1.72;
double
used to declare floating point variable of higher precision or
higher range of numbers exponential numbers, positive and
negative
keyword: double double valuebig;
valuebig = 12E-3;

25
Basic Data Types cont…
char
equivalent to ‘letters’ in English language Example of
characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
single character keyword:
char

char my_letter;
The declared character must be
my_letter = 'U'; enclosed within a single quote!

In addition, there are void, short, long, etc.


26
Constants
Entities that appear in the program code as fixed values.
Any attempt to modify a CONSTANT will result in error.
4 types of constants:
Integer constants
Positive or negative whole numbers with no fractional part Example:
– const int MAX_NUM = 10;
– const int MIN_NUM = -90;
Floating-point constants (float or double)
Positive or negative decimal numbers with an integer part, a decimal point
and a fractional part
Example:
– const double VAL = 0.5877e2; (stands for 0.5877 x 102)

27
Constants cont…
Character constants
A character enclosed in a single quotation mark Example:
– const char letter = ‘n’;
– const char number = ‘1’;
– printf(“%c”, ‘S’);
» Output would be: S

Enumeration
Enumeration is a user defined datatype in C language. It is used to assign
names to the integral constants which makes a program easy to read and
maintain. The keyword “enum” is used to declare an enumeration.
syntax
enum enum_name{const1, const2, ....... };
enum week{sunday, monday, tuesday, wednesday, thursday, friday,
saturday};
enum week day; 28
Constant example – volume of a cone
#include <stdio.h>

void main(void)
{
const double pi = 3.412;
double height, radius, base, volume;

printf(“Enter the height and radius of the cone:”);


scanf(“%lf %lf”,&height, &radius);

base = pi * radius * radius; volume = (1.0/3.0) *


base * height;

printf(“\nThe volume of a cone is %f ”, volume);


}

29
#define
You may also associate constant using #define preprocessor directive
#include <stdio.h>
#define pi 3.412

void main(void)
{
double height, radius, base, volume;

printf(“Enter the height and radius of the cone:”); scanf(“%lf


%lf”,&height,&radius);

base = pi * radius * radius; volume = (1.0/3.0) *


base * height;

printf(“\nThe volume of a cone is %f ”, volume);


}

30
Input/Output Operations

When we say Input, it means to feed some data into a program. An input can
be given in the form of a file or from the command line.
C programming provides a set of built-in functions to read the given input
and feed it to the program as per requirement.

When we say Output, it means to display some data on screen, printer, or in


any file.
C programming provides a set of built-in functions to output the data on
the computer screen as well as to save it in text or binary files.

31
The Standard Files
C programming treats all the devices as files.
Standard File File Pointer Device
Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your screen

Input/Output Functions
A C function that performs an input or output operation
A few functions that are pre-defined in the header file stdio.h
such as :
printf()
scanf()
getchar() & putchar()
32
You must be wondering what is the purpose of %d inside
the scanf() or printf() functions. It is known as format string and this informs
the scanf() function, what type of input to expect and in printf() it is used to give a
heads up to the compiler, what type of output to expect.

Format String Meaning


%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning
ends at whitespace.
We can also limit the number of digits or characters that can be input or
output, by adding a number with the format string specifier, like "%1d" or "%3s", the
first one means a single numeric digit and the second one means 3 characters, hence
if you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the
case for output.
The printf function
Used to send data to the standard output (usually
the monitor) to be printed according to specific
format.
General format:
printf(“string literal”);
A sequence of any number of characters
surrounded by double quotation marks.
printf(“format string”, variables);
Format string is a combination of text, conversion
specifier and escape sequence.

34
The printf function cont…
Example:
printf(“Thank you”);
printf (“Total sum is: %d\n”, sum);
%d is a placeholder (conversion specifier)
– marks the display position for a type integer variable
\n is an escape sequence
– moves the cursor to the new line

35
Escape Sequence
Escape Sequence Effect
\a Beep sound
\b Backspace
\f Formfeed (for printing)
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash
\” “ sign
\o Octal decimal
\x Hexadecimal
\O NULL

36
Placeholder / Conversion Specifier
No Conversion Output Type Output Example
Specifier
1 %d Signed decimal integer 76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e notation) 7.6000e+01
9 %E Signed floating point (using E notation) 7.6000E+01
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String ‘76'

37
The scanf function
Read data from the standard input device (usually
keyboard) and store it in a variable.
General format:
scanf(“Format string”, &variable);
Notice ampersand (&) operator :
C address of operator
it passes the address of the variable instead of the
variable itself
tells the scanf() where to find the variable to store the
new value

38
The scanf function cont…
Example : int age;
printf(“Enter your age: “);
scanf(“%d”,&age);
Common Conversion Identifier used in
printf and scanf functions.

printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s
39
The scanf function cont…
If you want the user to enter more than one value, you
serialise the inputs.
Example:
float height, weight;
printf(“Please enter your height and weight:”); scanf(“%f
%f”, &height, &weight);

40
getchar() & putchar() functions
The getchar() function reads a character from the terminal
and returns it as an integer. This function reads only single
character at a time. You can use this method in a loop in case
you want to read more than one character.
The putchar() function displays the character passed to it
on the screen and returns the same character. This function too
displays only a single character at a time. In case you want to
display more than one characters, use putchar() method in a
getchar() and putchar()
getchar() - read a character from standard input
putchar() - write a character to standard output
Example: #include <stdio.h> void
main(void)
{
char my_char;
printf(“Please type a character: ”);
my_char = getchar();
printf(“\nYou have typed this character: ”);
putchar(my_char);
}

42
getchar() and putchar() cont
Alternatively, you can write the previous code using
normal scanf and %c placeholder.
Example
#include <stdio.h>
void main(void)
{
char my_char;
printf(“Please type a character: ”);
scanf(“%c”,&my_char);
printf(“\nYou have typed this character: %c ”, my_char);
}

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

The puts() function writes the string str and a trailing


newline to stdout.
str → This is the pointer to an array of chars where the C string

is stored.
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops
reading characters when it encounters a space, but gets() reads space as
character too.
If you enter name as Study Tonight using scanf() it will only read and
store Study and will leave the part after space. But gets() function will
read it completely.
Few notes on C program…
C is case-sensitive
Word, word, WorD, WORD, WOrD, worD, etc are all different
variables / expressions
Eg. sum = 23 + 7
What is the value of Sum after this addition ?

Comments (remember 'Documentation'; Chapter 2) are inserted into


the code using /* to start and */ to end a comment
Some compiler support comments starting with ‘//’
Provides supplementary information but is ignored by the preprocessor and
compiler
/* This is a comment */
// This program was written by Hanly Koffman

46
Few notes on C program cont…
Reserved Words
Keywords that identify language entities such as
statements, data types, language attributes, etc.
Have special meaning to the compiler, cannot be used as
identifiers (variable, function name) in our program.
Should be typed in lowercase.
Example: const, double, int, main, void,printf, while, for,
else (etc..)

47
Few notes on C program cont…
Punctuators (separators)
Symbols used to separate different parts of the C
program.
These punctuators include:
[ ] ( ) { } , ; “: * #
Usage example:
void main (void)
{
int num = 10;
printf (“%d”,num);
}
48
Few notes on C program cont…
Operators
Tokens that result in some kind of computation or action
when applied to variables or other elements in an
expression.
Example of operators:
* + = - / Usage example:
result = total1 + total2;

49
Common Programming Errors
Debugging  Process removing errors from a
program
Three (3) kinds of errors :
Syntax Error
a violation of the C grammar rules, detected during
program translation (compilation).
statement cannot be translated and program
cannot be executed

50
Common Programming Errors cont…
Run-time errors
• An attempt to perform an invalid operation, detected
during program execution.
• Occurs when the program directs the computer to
perform an illegal operation, such as dividing a number
by zero.
• The computer will stop executing the program, and
displays a diagnostic message indicates the line where
the error was detected
51
Common Programming Errors cont…
Logic Error/Design Error
• An error caused by following an incorrect algorithm

• Very difficult to detect - it does not cause run- time error


and does not display message errors.
• The only sign of logic error – incorrect program output

• Can be detected by testing the program thoroughly,


comparing its output to calculated results
• To prevent – carefully desk checking the algorithm
and written program before you actually type it 52
Summary
In this chapter, you have learned the following items:
environment of C language and C programming
C language elements
Preprocessor directives, curly braces, main (), semicolon, comments,
double quotes
4 basics data type and brief explanation on variable 6 tokens :
reserved word, identifier, constant, string literal, punctuators /
separators and operators.
printf, scanf, getchar and putchar
Usage of modifiers : placeholder & escape sequence Common
programming errors : syntax error, run-time error and logic error

53
C - Operator Types
What is Operator? Simple answer can be given using expression 4 + 5 is equal
to 9. Here 4 and 5 are called operands and + is called operator. C language
supports following type of operators.
Arithmetic Operators
Logical (or Relational) Operators
Bitwise Operators
Assignment Operators
Misc Operators
Lets have a look on all operators one by one.
Arithmetic Operators:
There are following arithmetic operators supported by C language:
Assume variable A holds 10 and variable B holds 20 then:
Show Examples

Operator Description Example


+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denumerator B / A will give 2

% Modulus Operator and remainder of after an integer division B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9


Logical (or Relational) Operators:
There are following logical operators supported by C language
Assume variable A holds 10 and variable B holds 20 then:
Show Examples

Operator Description Example


Checks if the value of two operands is equal or not, if yes
== then condition becomes true. (A == B) is not true.

Checks if the value of two operands is equal or not, if values


!= are not equal then condition becomes true. (A != B) is true.

Checks if the value of left operand is greater than the value


> of right operand, if yes then condition becomes true. (A > B) is not true.

Checks if the value of left operand is less than the value of


< right operand, if yes then condition becomes true. (A < B) is true.
Checks if the value of left operand is greater than or equal
>= to the value of right operand, if yes then condition becomes (A >= B) is not true.
true.

Checks if the value of left operand is less than or equal to


<= the value of right operand, if yes then condition becomes (A <= B) is true.
true.

&& Called Logical AND operator. If both the operands are non (A && B) is true.
zero then then condition becomes true.

Called Logical OR Operator. If any of the two operands is


|| (A || B) is true.
non zero then then condition becomes true.

Called Logical NOT Operator. Use to reverses the logical


! state of its operand. If a condition is true then Logical NOT !(A && B) is false.
operator will make false.
Bitwise Operators:
BITWISE OPERATORS are used for manipulating data at the bit level, also called bit
level programming. Bitwise operates on one or more bit patterns or binary numerals
at the level of their individual bits. They are used in numerical computations to make
the calculation process faster

Binary Ones Complement


Binary OR Binary AND Binary XOR Operator
Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
------------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

Binary 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
Hex 0 1 2 3 4 5 6 7 8 9 A B C D E F
There are following Bitwise operators supported by C language
Operator Description Example
Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is 0000
&
exists in both operands. 1100
Binary OR Operator copies a bit if it exists in eather (A | B) will give 61 which is 0011
| operand. 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011
^
operand but not both. 0001
Binary Ones Complement Operator is unary and has (~A ) will give -60 which is 1100
~ the efect of 'flipping' bits. 0011
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the A << 2 will give 240 which is 1111
0000
right operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the A >> 2 will give 15 which is 0000
1111
right operand.
Assignment Operators:
There are following assignment operators supported by C language:
Show Examples
Operator Description Example
Simple assignment operator, Assigns values from right side operands to C = A + B will assigne
=
left side operand value of A + B into C

Add AND assignment operator, It adds right operand to the left operand C += A is equivalent to C
+=
and assign the result to left operand =C+A

Subtract AND assignment operator, It subtracts right operand from the C -= A is equivalent to C
-=
left operand and assign the result to left operand =C-A

Multiply AND assignment operator, It multiplies right operand with the C *= A is equivalent to C
*=
left operand and assign the result to left operand =C*A

Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to C
/=
operand and assign the result to left operand =C/A
Modulus AND assignment operator, It
= takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2


>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
bitwise exclusive OR and assignment
^= operator C ^= 2 is same as C = C ^ 2
bitwise inclusive OR and assignment
|= operator C |= 2 is same as C = C | 2
Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using
conditional operator, we turn the if condition statement into a short and simple
operator.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3
Explanation:
•The question mark "?" in the syntax represents the if part.
•The first expression (expression 1) generally returns either true or false,
based on which it is decided whether (expression 2) will be executed or
(expression 3)
•If (expression 1) returns true then the expression on the left side of " : "
i.e (expression 2) is executed.
•If (expression 1) returns false then the expression on the right side of " :
" i.e (expression 3) is executed.
Special operator

Operator Description Example

sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of an variable &x ; return address of the variable x

* Pointer to a variable *x ; will be pointer to a variable x


Decision Making (if, if-else, if-else-if ladder, nested if, switch,
nested switch

Decision Making in programming is similar to decision making in


real life. In programming too, a certain block of code needs to be
executed when some condition is fulfilled.
A programming language uses control statements to control the
flow of execution of program based on certain conditions. These are
used to cause the flow of execution to advance and branch based on
changes to the state of a program.
C language handles decision-making by supporting the following statements,

The conditional statements of C:


• if
• if-else
• if-else-if
• Nested if
• Switch
• Nested switch
IF Statement
#include<stdio.h>
The if statement
#include<conio.h> checks the given condition. If the condition evaluates to be true
then the block of code/statements will execute otherwise not.
void main()
{ Syntax:
int a,b;
if(condition)
printf("Enter two numbers :");
{
scanf("%d %d",&a,&b);
//code to be executed
if (a>b) }
Note: If the curly brackets { } are not used with if statements than the statement
printf("%d is greater",a);
just next to it is only considered associated with the if statement.
printf("%d is greater",b);
Example:
getch();if (condition)
}
statement 1;
statement 2;
In this example, only statement 1 is considered to be associated with the if statement.
IF – else Statement
The if statement evaluates the code if the condition is true but what if the condition is not true, here
#include<stdio.h>
comes the#include<conio.h>
else statement. It tells the code what to do when the if condition is false.
Syntax:
void main()
{
if(condition)
int{ a;
printf("Enter a number :");
// code if condition is true
scanf("%d",&a);
}
if (a%2==0)
{else
{
printf("%d is even",a);
} // code if condition is false
Else}
printf("%d is odd",a);
getch();
}
If – else – if ladder Statement
The if-else-if ladder statement executes one condition from multiple
statements. The execution starts from top and checked for each if condition. The
statement of if block will be executed which evaluates to be true. If none of the if
condition evaluates to be true then the last else block is evaluated.
Syntax: if(condition1)
{
// code to be executed if condition1 is true
}
else if(condition2)
{
// code to be executed if condition2 is true
}
else if(condition3)
{
// code to be executed if condition3 is true
}
...
else
{
// code to be executed if all the conditions are false
}
Nested – If Statement
if statement inside an if statement is known as nested if. if statement in this case is the
target of another if or else statement. When more then one condition needs to be true
and one of the condition is the sub-condition of parent condition, nested if can be
used. Syntax:
if (condition1)
{
// code to be executed
// if condition2 is true
if (condition2)
{
// code to be executed
// if condition2 is true
}
}
Switch Statement
Switch statement is an alternative to long if-else-if ladders. The expression is
checked for different cases and the one match is executed. break statement is used
to move out of the switch. If the break is not used, the control will flow to all cases
below it until break is found or switch comes to an end. There is default case
(optional) at the end of switch, if none of the case matches then default case is
executed.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
.
.
.
case valueN: // statement sequence
break;
default: // default statement sequence
}
Nested switch
Nested Switch case are allowed in C . In this case, switch is present inside other switch case. Inner switch is
present in one of the cases in parent switch.

Difference between switch and if


•if statements can evaluate float conditions. switch statements cannot
evaluate float conditions.
•if statement can evaluate relational operators. switch statement cannot evaluate

relational operators i.e they are not allowed in switch statement.

Rules for using switch statement


1.The expression (after switch keyword) must yield an integer value i.e the expression should be an integer or
a variable or an expression that evaluates to an integer.
2.The case label values must be unique.
3.The case label must end with a colon(:)
4.The next line, after the case statement, can be any valid C statement.
Loops in C
In any programming language including C, loops are used to execute a set of
statements repeatedly until a particular condition is satisfied.
How it Works
The below diagram depicts a loop execution,
As per the above diagram, if the Test Condition is true, then
the loop is executed, and if it is false then the execution breaks out
of the loop. After the loop is successfully executed the execution
again starts from the Loop entry and again checks for the Test
condition, and this keeps on repeating.

The sequence of statements to be executed is kept inside


the curly braces { } known as the Loop body. After every execution
of the loop body, condition is verified, and if it is found to
be true the loop body is executed again. When the condition check
returns false, the loop body is not executed, and execution breaks
out of the loop.
Types of Loop
There are 3 types of Loop in C language, namely:

• while loop
• for loop
• do while loop

1. while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.
• Variable initialization.(e.g int x = 0;)
• condition(e.g while(x <= 10))
• Variable increment or decrement ( x++ or x-- or x = x + 2 )
Goto statement in C
C supports a unique form of a statement that is the goto Statement which is used to branch
unconditionally within a program from one point to another. Although it is not a good habit to use the
goto statement in C, there may be some situations where the use of the goto statement might be
desirable.

The goto statement is used by programmers to change the sequence of execution of a C


program by shifting the control to a different part of the same program.
Syntax:

goto label;
A label is an identifier required for goto statement to a place where the branch is to be made. A label is a
valid variable name which is followed by a colon and is put immediately before the statement where the

control needs to be jumped/transferred unconditionally .


Syntax: #include<stdio.h>

goto label; void main()


{
- - -- - - int age;
--------
g: //label name
printf("you are Eligible\n");
label: s: //label name
printf("you are not Eligible");
statement - X;
printf("Enter you age:");
/* This the forward jump of goto statement */
scanf("%d", &age);

if(age>=18)
goto g; //goto label g
else
goto s; //goto label s
getch();
}
C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element
in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Runtime initialization of a two dimensional Array
String and Character Array

String is a sequence of characters that is treated as a single data item and


terminated by null character '\0'. Remember that C language does not support
strings as a data type. A string is actually one-dimensional array of characters in C
language. These are often used to create meaningful and readable programs.
For example: The string "hello world" contains 12 characters including '\0'
character which is automatically added by the compiler at the end of the string.

You might also like