Food Rec
Food Rec
Food Rec
C PROGRAMMING FUNDAMENTALS
History of c language
Features of c language
Structure of c program
Flow of c program
Types of errors
Keywords in c
Operators
Expressions
Assignment statement
Let's see the programming languages that were developed before C language.
C is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.
Unlike assembly language, c programs can be executed in many machines with little
bit or no change. But it is not platform-independent.
C is a structured programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify.
5) Rich Library
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion
In c, we can call the function within the function. It provides code reusability for
every function.
10) Extensible
In this type of language, large programs are divided into small programs
called functions
Prime focus is on functions and procedures that operate on the data
Data moves freely around the systems from one function to another
Program structure follows ―Top Down Approach‖
Examples: C, Pascal, ALGOL and Modula-2
High level languages provide almost everything that the programmer might
need to do as already built into the language. Example: Java, Python
Middle level languages don‘t provide all the built-in functions found in high level
languages, but provides all building blocks that we need to produce the result
we want. Examples: C, C++
Low level languages provide nothing other than access to the machines basic
instruction set. Example: Assembler
1. Operating Systems
With the help of the C programming language, you can write your own
operating system. Windows Kernel, Linux Kernel and Apple‘s OS X kernel are
mostly written in C.
2. GUI
3. Embedded Systems
4. Database
5. Ease of Computation
6. Gaming
Due to the fast execution and simplicity, many languages like Java, C++,
Python, PHP, PERL, JavaScript, etc were influenced by the development of C. In
Python, C is used for building standard libraries. The syntax and control
structures of PERL, PHP and C++ are based upon the C programming language.
8. Google
In the Google open source community, the projects are being handled by
C/C++. And C/C++ also helped in developing Google file system and chromium
browser.
9. Assemblers
C also helped in creating various text editors like Vim, Gedit etc.
11. Drivers
12. Interpreters
Definition In this section, variables are defined and values are set to these
Section variables.
Global
Global variables are defined in this section. When a variable is to
declaration
be used throughout the program, can be defined in this section.
section
Function
prototype Function prototype gives many information about a function like
declaration return type, parameter names used inside the function.
section
User
defined User can define their own functions in this section which perform
function particular task as per the user requirement.
section
To understand the flow of C program well, let us see a simple program first.
File: sample.c
#include <stdio.h>
main()
{
printf("Hello KK");
}
Execution Flow
2) Expanded source code is sent to compiler which compiles the code and
converts it into assembly code.
3) The assembly code is sent to assembler which assembles the code and
converts it into object code. Now a sample.obj file is generated.
4) The object code is sent to linker which links it to the library such as header
files. Then it is converted into executable code. A sample.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it
is executed. After execution, output is sent to console.
There are lot of IDE programs available for C and C++. IDE makes it easy
to create, compile and execute a C or C++ program. Most of the IDEs are open
source applications (ie.) they are available free of cost.
These are given by the compiler and prevent the program from not running.
Linking errors
This is given by the linker or at runtime and ends the program. The linker can
also detect and report errors, for example, if part of the program is missing or a
non-existent library component is referenced.
Syntax Errors
printf(“Hello World”)
Semantic Errors
A Program has not produced expected result even though the program is
grammatically correct. It may be happened by wrong use of variable / operator /
order of execution etc. This means, program is grammatically correct, but it
contains some logical error. So, Semantic error is also called as ―Logic Error‖.
Run-time errors
A run time error occurs during the execution of a program. It occurs because of
some illegal operation that takes place.
For example, if a program tries to open a file which does not exist, it results in a
run-time error.
Debugging
Removing errors from a program is called debugging. Any type of error in your
program is known as bug. During debugging an attempt is made to remove all
the known problems or bugs from the program.
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 12
Source Code is the file which contains programming code in high level
language. To create source code, we need a text editor to write the program.
In C programming language every source code file must be saved with “.c”
extension.
F2 or Alt + f + s
Step 3
What is linker?
Eventually, when the source code of all the modules has been converted into
object code, we need to put all the modules together. This is the job of the
linker.
Usually, the compiler automatically invokes the linker as the last step in
compiling a program.
What is loader?
A loader is a special type of program that copies programs from a storage device
to main memory, where they can be executed.
Object code is the output of a compiler after it processes source code. Source
code is the version of a computer program as it is originally written by a human
in a programming language. A compiler is a specialized program that converts
source code into object code.
Translates the entire source code Translates and executes the source
Errors are detected and must be Errors are detected and must be
Error corrected after the entire program corrected line-by-line during
Detection
is compiled. execution.
Programming Rules in C
Rule 3: Blank spaces may be inserted between the words. This improves the
readability of statements.
Rule 4: Blank spaces should not be allowed while declaring variables, constants,
keyword, and function.
Rule 5: Programmer can write the statement anywhere between the "2 braces".
Rule 6: Programmer can write one or more statement in one line, separating
that by semicolon (;).
Special Symbols
Blank space, newline, horizontal tab, carriage return and form feed.
A data type specifies the type of data that a variable can store such as integer,
floating, character etc.
#include <stdio.h>
void main()
// Create variables
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
}
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 17
C has five basic data types and they are as follows:
Ex.
Specifier
byte(s)
Format
word
Size
Name
character/letter/number, or ASCII
values
decimals
Double
8 Stores fractional numbers, 1.99
double
precision
containing one or more decimals.
floating %lf Sufficient for storing 15 decimal
digits
point
Integer datatype is a set of whole numbers. Every integer value does not
have the decimal value. We use the keyword "int" to represent integer datatype
in c. A 16-bit signed integer ranges from -32768 to 32767. The integer datatype
is used with different type modifiers like short, long, signed and unsigned.
Syntax:
Floating point data types are set of numbers with decimal value (like
3.141592). The floating point data type has two variants float and double.
The keyword "float" to represent floating point data type and "double" to
represent double data type in c.
Syntax:
float var2;
The character data type is represented by the char keyword and is used to
store a variable with only a single character. The size of the char data type is 1
byte (i.e., 8 bits). It has two subtypes- signed char and unsigned char. The
range for these is -127 to 128 and 0 to 255, respectively. Character data type
is an enclosed in single quotations.
Syntax
char var_name;
For example, if a function is not returning anything, its return type should be
void. Note that, you cannot create variables of void type.
1. signed
2. unsigned
3. long
4. short
-(263 – 1) to 263 – 1
long long int 8 %lld, %lli
(C99 standard)
264 – 1
unsigned long long int 8 %llu
(C99 standard)
In simple words, the unsigned modifier means all positive values, while
the signed modifier means both positive and negative values.
When the compiler gets a numeric value, it converts that value into a
binary number, which means a combination of 0 and 1. For example,
32767 in binary is 01111111 11111111
In the case of a signed integer, the highest order bit or the first digit
from left (in binary) is used as the sign flag. If the sign flag is 0, the
number is positive, and if it is 1, the number is negative.
For signed int, 11111111 11111111 means -32,767 and because the
first bit is a sign flag to mark it as a negative number, and rest represent
the number. Whereas in the case of unsigned int,
11111111 11111111 means 65,535.
To assign a value to any data type which is more than the allowed range
of value, then the C language compiler will give an error.
Example:
Derived datatypes are user-defined data types. The derived datatypes are also
called as user defined datatypes or secondary datatypes. In c programming
language, the derived datatypes are created using the following concepts...
Function, Arrays, Pointer.
Type Casting in C
#include <stdio.h>
main()
{
int a = 3;
int b = 2;
int c;
printf("The value of c = %f ",(float)a/b);
}
Output: The value of c = 1.500000
Variables a, b, c belongs to integer data type, where actual result will be in float.
Thus, we are in need to typecast the data type of variable 'c' from an int to float.
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 23
Type Casting Higher to Lower Datatype Conversion
#include <stdio.h>
main()
{
float a = 3.56;
printf("The value of a = %d ",(int)a);
}
Output: The value of a = 3
The size qualifiers alter the size of the basic data types. There are two such
qualifiers that can be used with the data type int; these are short and long.
1. Identifiers
2. Constants
3. Keywords
4. Strings
5. Operators
6. Special Symbols
1. Identifiers
Example
int amount;
double totalbalance;
mark_1
x2
Variables in C
syntax:
datatype variable_name;
int a;
float b;
char c;
Here, a, b, c are variables and int, float, char are data types.
A variable name can have letters (both uppercase and lowercase letters), digits
and underscore only.
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 26
The first letter of a variable should be either a letter or an underscore. However,
it is discouraged to start variable name with an underscore.
It is because variable name that starts with an underscore can conflict with
system name and may cause error.
There is no rule on how long a variable can be. However, only the first 31
characters of a variable are checked by the compiler.
int 2;
int a b;
int long;
Types of Variables in C
Example
#include<stdio.h>
main()
{
int m = 22, n = 44; /* Local variable declaration and initialization */
printf("\n main function values : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80; /* Local variable declaration and initialization */
printf("\n sub function values : a = %d and b = %d", a, b);
}
Output:
main function values : m = 22 and n = 44
sub function values : a = 50 and b = 80
The scope of global variables will be throughout the program. These variables
can be accessed from anywhere in the program.
This variable is defined outside the main function. So that, this variable is
visible to main function and all other sub functions.
Example
#include<stdio.h>
main()
{
printf("All variables are accessed from main function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
void test()
{
printf("\n\nAll variables are accessed from" \" test function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
Output:
All global variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All global variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80
Static variables are initialized only once. Compiler persist the variable till the
end of the program. Static variable can be defined inside or outside the function.
Example
#include <stdio.h>
/* Function declaration */
void display();
main()
{
display();
display();
display();
}
/* Function definition */
void display()
{
int n1 = 10;
static int n2 = 10;
Output:
Local n1 = 10, Static n2 = 10
Local n1 = 10, Static n2 = 11
Local n1 = 10, Static n2 = 12
External variables are also known as global variables. These variables are
defined outside the function. These variables are available globally throughout
the function execution. The value of global variables can be modified by the
functions.
First create a file named value.h where you put all your variables with extern
keyword which can be used by any program by simply including the file name in it.
//external variable (also global)
Note: The program illustrates that an external variables are declared in separate file with
an extension .h which is then including in demanded file.
Output:
• C Constants are also like normal variables. But, only difference is, their
values cannot be modified by the program once they are defined.
• Literals are data items whose values do not change during the execution
of a program. Therefore Literals are called as Constants. C has several
kinds of literals:
Note:
newline (\n), backspace (\b), Carriage return (\r), tab (\t), space () are
known as whitespace characters.
Example
#include<stdio.h>
main()
{
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
Output:
You
are
learning
'c' language
What is a C Operator?
1. Arithmetic Operators
2. Relational Operators
3. Shift Operators
4. Logical Operators
5. Bitwise Operators
7. Assignment Operator
8. Misc Operator
The following table shows all the arithmetic operators supported by the C
language.
Equality Operators
Assume variable A holds 10 and variable B holds 20 then
The relational operators in C are used for the comparison of the two operands.
All these operators are binary operators that return true or false values as the
result of comparison.
Checks if the value of left operand is greater than the value (A > B)
> of right operand. If yes, then the condition becomes true False
otherwise false.
Checks if the value of left operand is less than the value of (A < B)
right operand. If yes, then the condition becomes true True
< otherwise false.
A Left Shift of one position moves each bit to the left by one. The vacant
least significant bit (LSB) is filled with zero and the most significant bit
(MSB) is discarded.
A Right Shift of one position moves each bit to the right by one. The least
significant bit is discarded and the vacant MSB is filled with zero.
27 26 25 24 23 22 21 20 Decimal to Binary
128 64 32 16 8 4 2 1 conversion
technology
0 0 1 1 1 1 0 0 Binary value
0 1 1 1 1 0 0 0 Binary Left Shift by 1
1 1 1 1 0 0 0 0 Binary Left Shift by 2
27 26 25 24 23 22 21 20 Decimal to Binary
128 64 32 16 8 4 2 1 conversion technology
0 0 1 1 1 1 0 0 Binary value
0 0 0 1 1 1 1 0 Binary Right Shift by 1
0 0 0 0 1 1 1 1 Binary Right Shift by 2
If both left and right operands and (5 > 10) && (5 < 4)
&& expressions are true, it will return true. False
Otherwise, it will return false. Both expressions are false. so,
logical AND output will be 0
If one of the operands or expressions is (10 > 20) || (10 < 20)
true, it will return 1. True
|| If all of them are false, it will return 0. First expression is false and
second one is true. so,
logical OR output will be 1
Logical NOT operator is used to inverse !(100 < 10) 100 is greater
the current decision. Say, if current than 10. So, it will return
! state is true, Logical NOT (!) operator false.
will make it false. !(false) ==> true
Bitwise Operators
Bitwise AND (&) operator will take two equal length binary sequence and perform the
bitwise AND operation on each pair of bit sequence.
Example
Let’s take two integers,
A = 5 and B = 9.
What will be the result of A & B?
Solution
Let’s represent each number in binary format.
A = (0101) 2
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 40
B= (1001) 2
Bitwise OR (|) operator will take two equal length binary sequence and perform bitwise OR
operation on each pair of bit sequence.
Example
Let’s take two integers say A = 10 and B = 12,
Solution
Then A | B will be,
Bitwise XOR (^) operator will take two equal length binary sequence and perform bitwise
XOR operation on each pair of bit sequence.
Example
Let’s take two integers say A = 5 and B = 9.
A = (0101) 2
B= (1001) 2
A B A&B A|B A ^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Example
Let’s take a number 4.
4 = (00000100)2
5 = (00000101) 2
1’s complement of 5 = (11111010) 2
Add 1 to get the 2’s complement,
-5 = (11111011) 2
Result of ~4 is equal to the representation of -5 in binary, hence ~4 is -5.
Example
Let’s take number 2,
2 = (00000010) 2
1’s complement of 2 = (11111101) 2
Add 1 to get the 2’s complement,
~2 = (11111101) 2
Result of ~2 is equal to the representation of -3 in binary, hence ~2 is -3.
Eg. int a;
sizeof() Returns the size of a variable. sizeof(a),
where ‗a‟ is integer, will return 2.
& Returns the address of a &a; returns the actual address of the
variable. variable.
Syntax:
Example
Example:
Int a, b = 10;
a = -(b)
The result of this expression is a = -10, because variable b has a positive value.
After applying unary minus operator (-) on the operand b, the value becomes -10,
which indicates it as a negative value.
The increment and decrement operators are called as unary operators because,
both needs only one operand. The increment operator adds one to the existing
value of the operand and the decrement operator subtracts one from the existing
value of the operand.
Pre-Increment or Pre-Decrement
In case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In case of pre-decrement, the value of the variable is
decreased by one before the expression evaluation. That means, when we use pre
increment or pre decrement, first the value of the variable is incremented or
decremented by one, and then modified value is used in the expression
evaluation.
Pre-Increment Pre-Decrement
main(){ main(){
} }
Post-Increment Post-Decrement
main(){ main(){
CODING
() function call
[] array reference
1 Left to Right
-> structure member access
! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
* pointer
* multiplication
% remainder
== equal to
7 Left to Right
!= not equal to
= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign additon
|= assign bitwise OR
Operands are the values on which the operators perform the task. Here
operand can be a direct value or variable or address of memory location.
Expression Types in C
In C programming language, expressions are divided into THREE types. They are
as follows...
Expression Evaluation
Based on the operators and operators used in the expression, they are
divided into several types. Types of Expression Evaluation in C are:
Example 1
10 + 4 * 3 / 2
In the above expression there are three operators +, * and /. Among these
three operators, both multiplication and division have same higher precedence
and addition has lower precedence. So, according to the operator precedence
both multiplication and division are evaluated first and then addition is
evaluated. As multiplication and division have same precedence they are
evaluated based on the associativity. Here, the associativity of multiplication and
division is left to right. So, multiplication is performed first, then division and
finally addition. So, the above expression is evaluated in the order of * / and +.
It is evaluated as follows...
Step1 4 * 3 ====> 12
Step2 12 / 2 ===> 6
Step3 10 + 6 ===> 16
5. Unformatted IO Functions
Only work with character data type. Unformatted input and output functions
do not require any format specifiers. Because they only work with character
data type.
1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()
scanf() function
The scanf() function is used to read multiple data values of different data
types from the keyboard. The scanf() function is built-in function defined in a
header file called "stdio.h". When we want to use scanf() function in our
program, we need to include the respective header file (stdio.h) using #include
statement. The scanf() function has the following syntax...
Example Program1
#include <stdio.h>
void main()
int i;
scanf("%d",&i);
Output:
The scanf function also used to read multiple data values of different or same
data types. Consider the following example program...
#include <stdio.h>
main()
int i;
float x;
Output:
In the above example program, we used the scanf() function to read one
integer value and one float value from the keyboard. Here 'i' is an integer
variable so we have used format string %d, and 'x' is a float variable so we have
used format string %f.
The scanf() function returns an integer value equal to the total number of input
values read using scanf function.
#include <stdio.h>
main()
int i,a,b;
float x;
getchar() function
The getchar() function is used to read a character from the keyboard and
return it to the program. This function is used to read only single character. To
read multiple characters we need to write multiple times or use a looping
statement. Consider the following example program...
#include <stdio.h>
main()
char ch;
ch = getchar();
Output:
getch() function
#include <stdio.h>
main()
char ch;
Output:
gets() function
The gets() function is used to read a line of string and stores it into
character array. The gets() function reads a line of string or sequence of
characters till a newline symbol enters. Consider the following example
program...
#include <stdio.h>
main()
char name[30];
gets(name);
printf("%s",name);
Output:
www.annauniv.edu
fscanf() function
When you want to use fscanf() function the file must be opened in reading
mode.
1. printf()
2. putchar()
3. puts()
4. fprintf()
printf() function
#include <stdio.h>
main()
When we want to display data values we use format string of the data
value to be display.
main()
int i = 10;
float x = 5.5;
Output: 10 5.5
In the above example program, we used the printf() function to print data
values of variables i and x on to the output screen. Here i is a integer variable so
we have used format string %d and x is a float variable so we have used format
string %f.
The printf() function can also used to display string along with data
values.
#include <stdio.h>
main()
int i = 10;
float x = 5.5;
In the above program we are displaying string along with data values.
main()
int i;
i = printf("Tiruchirappalli");
Output:
In the above program, first printf() function printing " Tiruchirappalli " which is
of 15 characters. So it returns integer value 15 to variable "i". The value of "i" is
printed in the second printf() function.
#include <stdio.h>
main()
printf("Welcome to ");
printf("C ");
printf("Language");
Output:
Welcome to C Language
In the above program, there are 3 printf() statements written in different lines
but the output is displayed in single line only.
#include <stdio.h>
main()
printf("Welcome to\n");
printf("C\n");
printf("Language");
Output:
Welcome to
Language
putchar() function
#include <stdio.h>
main()
char ch = 'A';
putchar(ch);
Output: A
The puts() function is used to display string on the output screen. The puts()
functions prints a string or sequence of characters till the newline. Consiider the
following example program...
#include <stdio.h>
main()
char name[30];
gets(name);
puts(name);
Output:
www.annauniv.edu
fprintf() function
When you want to use fprintf() function the file must be opened in writting
mode.
Syntax:
Example:
int x = 5;
The value of a variable may be changed. For example, if x has the value 5, then the
assignment statement
Example:
int i = 0;
value1 = 2*3 ;
NEXT, put the result of the calculation into the variable value1.
Compound Operators
a=a+b is written as
a += b
or
Example:
char str[4]={‗H‘,‗a‘,‗i‘};
it will store
(or)
str[0] = ‗H‘;
str[1] = ‗a‘;
str[2] = ‗i;
Consider a situation,
Decision making statements are the statements that are used to verify a
given condition and decide whether a block of statements gets executed or not
based on the condition result.
1. Conditional
2. Unconditional
1. if statement
2. switch statement
if statement in c
Simple if statement
if - else statement
Nested if statement
if-else-if statement (if-else ladder)
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 68
Simple if statement
The ‗if‘ statement evaluates a condition, if the condition is true then a true-
block (a statement or set of statements) is executed, otherwise the true-block is
skipped.
Example:
Output
Output Enter your age: 23
m and n are equal You are eligible for voting
Syntax
if (test-expression)
{
True block of statements
}
else
{
False block of statements
}
Statements;
Syntax
if ( test condition1)
{
if ( test condition2)
{
Test condition2 True statements;
}
else
{
Test condition2 False statements;
}
}
else
{
Test condition1 False statements;
}
The working procedure of the above said if..else structures are given as
flowchart below:
#include <stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:
Output 2:
Enter any integer number: 999
Given number is not below 100
Syntax
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is
true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false
and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
When the respective expression becomes true, the statement associated with
block is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Output
Enter any three integer numbers: 55 60 20
60 is the largest number
Syntax
switch ( expression )
{
case label1:
statement(s);
break;
case label2:
statement(s);
break;
case label3:
statement(s);
break;
default:
statement(s);
In the above syntax, the expression is evaluated and if its value matches
against the constant value specified in one of the case statements, that
respective set of statements are executed. Otherwise, the statements under the
default option are executed. The workflow of switch statement and flow chart
are shown below.
Rules
3) The case value can be used only inside the switch statement.
int id = 3 ;
switch(id)
{
case 2:
printf("C++ Programming Language");
break;
case 2: //error
printf("Web Technology");
break;
case 1 :
printf("C Programming Language");
break;
Rule 4 : Case label must be of integral Type ( Integer, Character) whereas Case label
should not be ‘floating point number ‘
case 10:
case 20+20:
case 'A':
case 'a':
Illegal examples
switch(roll)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
default :
printf("Default Version 1");
break;
default : //error
printf("Default Version 2");
break;
}
It violets rule.
switch(roll)
{
case 1 :
printf("C Programming Language");
switch(roll)
{
case 1 :
printf("C Programming Language");
break;
default: //ANYWHERE
printf("No Student Found");
break;
case 2 :
printf("C++ Programming Language");
break;
switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
printf("Alphabet B");
break;
}
switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
switch(alpha)
{
}
break;
}
switch(num)
{
case >15: //error
printf("Number > 15");
break;
case =15: //error
printf("Number = 15");
break;
#define MAX 2
switch(num)
{
case MAX:
printf("Number = 2");
break;
}
as preprocessor will replace occurrence of MAX by constant value i.e 2 theref
or it is allowed.
Output:
1. break
2. continue
3. goto
Break Statement
Syntax: break;
Example
The continue statement works quite similar to the break statement. Instead
of terminating the loop (break statement), continue statement forces the loop to
continue or execute the next iteration. When the continue statement is executed
in the loop, the code inside the loop following the continue statement will be
skipped and next iteration of the loop will begin.
Syntax continue;
Break is used with loops as well as Continue is only used in loops, it is not
switch case. used in switch case.
Syntax
Example:
1. while statement
2. do-while statement
3. for statement
while Statement
A while loop is a control flow statement that allows the loop statements to be
executed as long as the condition is true. The while loop is an entry-controlled
loop because the test-expression is evaluated before entering into a loop.
If the condition is True then it will execute the statements inside the loop.
Next we have to use Increment and Decrement Operator inside the while
loop to increment and decrements the value. Please refer Increment and
Decrement Operator in C article to understand the functionality
Again it will check for the condition after the value incremented. As long
as the condition is True, the statements inside the while loop will be
executed.
If the condition is False then it will exit from the While loop
#include <stdio.h>
main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
Output :
Even numbers upto 10
0 2 4 6 8 10
#include <stdio.h>
main()
{
int count=1;
while (count <= 4)
{
printf("%d\t ", count);
count++;
}
return 0;
}
Ouput:
1 2 3 4
#include <stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
Output
Even numbers upto 10
0 2 4 6 8 10
Syntax
Test Condition: The value of the counter variable is tested against the test
condition. If the condition is True then it will execute the statements inside the
For loop. If the condition fails then For loop will be terminated.
main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
OUTPUT:
0123456789
Output
Even numbers upto 10
0 2 4 6 8 10
Nested while loop : A while loop inside another while loop is called nested while
loop.