Learn C Programming
developerinsider.in/turbocpp
The Definitive Guide
C is a powerful general-purpose programming language. It is fast, portable and available in all platforms.
If you are new to programming, C is a good choice to start your programming journey.
This is a comprehensive guide on how to get started in C programming language, why you should learn it and how you can learn it.
To print
And when we display that value using
If you are new to programming, C is a good choice to start your programming journey.
This is a comprehensive guide on how to get started in C programming language, why you should learn it and how you can learn it.
c programming |
Introduction
- Keywords & Identifier
- Variables & Constants
- C Data Types
- C Input/Output
- C Operators
- Basic Examples
C Keywords and Identifiers
In this tutorial, you will learn about keywords; reserved words in C programming that are part of the syntax. Also, you will learn about identifiers and how to name them.Character set
A character set is a set of alphabets, letters and some special characters that are valid in C language.
Alphabets
Uppercase: A B C ................................... X Y Z Lowercase: a b c ...................................... x y z
C accepts both lowercase and uppercase alphabets as variables and functions.
Digits
0 1 2 3 4 5 6 7 8 9
Special Characters
Special Characters in C Programming , < > . _ ( ) ; $ : % [ ] # ? ' & { } " ^ ! * / | - \ ~ +
Blank space, newline, horizontal tab, carriage, return and form feed.
C Keywords
Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
int
is a keyword that indicates money is a variable of typeint
(integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords allowed in ANSI C.
C Keywords auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
continue
for
signed
void
do
if
static
while
default
goto
sizeof
volatile
const
float
short
unsigned
C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of the program. For example:
Here, money and accountBalance are identifiers.int money;
double accountBalance;
Also remember, identifier names must be different from keywords. You cannot useint
as an identifier becauseint
is a keyword.
Rules for naming identifiers
- A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
- The first letter of an identifier should be either a letter or an underscore.
- You cannot use keywords as identifiers.
- There is no rule on how long an identifier can be. However, you may run into problems in some compilers if the identifier is longer than 31 characters.
C Variables, Constants and Literals
In this tutorial, you will learn about variables and rules for naming a variable. You will also learn about different literals in C programming and how to create constants.Variables
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. For example:
Here, playerScore is a variable ofint playerScore = 95;
int
type. Here, the variable is assigned an integer value95
.
The value of a variable can be changed, hence the name variable.
char ch = 'a';
// some code
ch = 'l';
Rules for naming a variable
- A variable name can have only letters (both uppercase and lowercase letters), digits and underscore.
- The first letter of a variable should be either a letter or an underscore.
- There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters.
Note: You should always try to give meaningful names to variables. For example:C is a strongly typed language. This means that the variable type cannot be changed once it is declared. For example:firstName
is a better variable name thanfn
.
Here, the type of number variable isint number = 5; // integer variable
number = 5.5; // error
double number; // error
int
. You cannot assign a floating-point (decimal) value 5.5 to this variable. Also, you cannot redefine the data type of the variable todouble
. By the way, to store the decimal values in C, you need to declare its type to eitherdouble
orfloat
.
Visit this page to learn more about different types of data a variable can store.
Literals
A literal is a value (or an identifier) whose value cannot be altered in a program. For example: 1, 2.5, 'c' etc.
Here, 1,2.5 and 'c' are literals. Why? You cannot assign different values to these terms.
1. Integers
An integer is a numeric literal(associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming:
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
Decimal: 0, -9, 22 etc Octal: 021, 077, 033 etc Hexadecimal: 0x7f, 0x2a, 0x521 etc
In C programming, octal starts with a 0, and hexadecimal starts with a 0x.
2. Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For example:
-2.0 0.0000234 -0.22E-5
Note:E-5 = 10
-5
3. Characters
A character literal is created by enclosing a single character inside single quotation marks. For example: 'a', 'm', 'F', '2', '}' etc;
4. Escape Sequences
Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc.
In order to use these characters, escape sequences are used.
Escape Sequences Escape Sequences Character \b
Backspace \f
Form feed \n
Newline \r
Return \t
Horizontal tab \v
Vertical tab \\
Backslash \'
Single quotation mark \"
Double quotation mark \?
Question mark \0
Null character
For example:\n
is used for a newline. The backslash\
causes escape from the normal way the characters are handled by the compiler.
5. String Literals
A string literal is a sequence of characters enclosed in double-quote marks. For example:
"good" //string constant "" //null string constant " " //string constant of six white space "x" //string constant having a single character. "Earth is round\n" //prints string with a newline
Constants
If you want to define a variable whose value cannot be changed, you can use theconst
keyword. This will create a constant. For example,
Notice, we have added keywordconst double PI = 3.14;
const
.
Here, PI is a symbolic constant; its value cannot be changed.
const double PI = 3.14;
PI = 2.9; //Error
You can also define a constant using the#define
preprocessor directive. We will learn about it in C Macros tutorial.
C Data Types
In this tutorial, you will learn about basic data types such as int, float, char etc. in C programming.In C programming, data types are declarations for variables. This determines the type and size of data associated with variables. For example,
Here, myVar is a variable ofint myVar;
int
(integer) type. The size ofint
is 4 bytes.
Basic types
Here's a table containing commonly used types in C programming for quick access.
Type Size (bytes) Format Specifier int
at least 2, usually 4 %d
char
1 %c
float
4 %f
double
8 %lf
short int
2 usually %hd
unsigned int
at least 2, usually 4 %u
long int
at least 4, usually 8 %li
long long int
at least 8 %lli
unsigned long int
at least 4 %lu
unsigned long long int
at least 8 %llu
signed char
1 %c
unsigned char
1 %c
long double
at least 10, usually 12 or 16 %Lf
int
Integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example,0
,-5
,10
We can useint
for declaring an integer variable.
Here, id is a variable of type integer.int id;
You can declare multiple variables at once in C programming. For example,
The size ofint id, age;
int
is usually 4 bytes (32 bits). And, it can take232
distinct states from-2147483648
to2147483647
.
float and double
float
anddouble
are used to hold real numbers.
In C, floating-point numbers can also be represented in exponential. For example,float salary;
double price;
float normalizationFactor = 22.442e2;
float
anddouble
?
The size offloat
(single precision float data type) is 4 bytes. And the size ofdouble
(double precision float data type) is 8 bytes.
char
Keywordchar
is used for declaring character type variables. For example,
The size of the character variable is 1 byte.char test = 'h';
void
void
is an incomplete type. It means "nothing" or "no type". You can think of void as absent.
For example, if a function is not returning anything, its return type should bevoid
.
Note that, you cannot create variables ofvoid
type.
short and long
If you need to use a large number, you can use a type specifierlong
. Here's how:
Here variables a and b can store integer values. And, c can store a floating-point number.long a;
long long b;
long double c;
If you are sure, only a small integer ([−32,767, +32,767]
range) will be used, you can useshort
.
short d;
You can always check the size of a variable using thesizeof()
operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
printf("size of short = %d bytes\n", sizeof(a));
printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}
signed and unsigned
In C,signed
andunsigned
are type modifiers. You can alter the data storage of a data type by using them. For example,
Here, the variable x can hold only zero and positive values because we have used theunsigned int x;
int y;
unsigned
modifier.
Considering the size ofint
is 4 bytes, variable y can hold values from-231
to231-1
, whereas variable x can hold values from0
to232-1
.
Other data types defined in C programming are:
- bool Type
- Enumerated type
- Complex types
Derived Data Types
Data types that are derived from fundamental data types are derived types. For example: arrays, pointers, function types, structures, etc.
We will learn about these derived data types in later tutorials.C Input Output (I/O)
In this tutorial, you will learn to use scanf() function to take input from the user, and printf() function to display output to the user.C Output
In C programming,printf()
is one of the main output function. The function sends formatted output to the screen. For example,
Example 1: C Output
Output#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
C Programming
How does this program work?
- All valid C programs must contain the
main()
function. The code execution begins from the start of themain()
function. - The
printf()
is a library function to send formatted output to the screen. The function prints the string inside quotations. - To use
printf()
in our program, we need to includestdio.h
header file using#inclue <stdio.h>
statement. - The
return 0;
statement inside themain()
function is the "Exit status" of the program. It's optional.
Example 2: Integer Output
Output
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Number = 5We use
%d
format specifier to print int
types. Here, the %d
inside the quotations will be replaced by the value of testInteger.Example 3: float and double Output
Output
#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;
printf("number1 = %f\n", number1);
printf("number2 = %lf", number2);
return 0;
}
number1 = 13.500000 number2 = 12.400000To print
float
, we use %f
format specifier. Similarly, we use %lf
to print double
values.Example 4: Print Characters
Output
#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c.", chr);
return 0;
}
character = a
char
, we use %c
format specifier.C Input
In C programming,scanf()
is one of the commonly used function to take input from the user. The scanf()
function reads formatted input from the standard input such as keyboards.Example 5: Integer Input/Output
Output
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Enter an integer: 4 Number = 4Here, we have used
%d
format specifier inside the scanf()
function to take int
input from the user. When the user enters an integer, it is stored in the testInteger variable.
Notice, that we have used
&testInteger
inside scanf()
. It is because &testInteger gets the address of testInteger, and the value entered by the user is stored in that address.Example 6: Float and Double Input/Output
Output
#include <stdio.h>
int main()
{
float num1;
double num2;
printf("Enter a number: ");
scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", num1);
printf("num2 = %lf", num2);
return 0;
}
Enter a number: 12.523 Enter another number: 10.2 num1 = 12.523000 num2 = 10.200000We use
%f
and %lf
format specifier for float
and double
respectively.Example 7: C Character I/O
Output
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Enter a character: g You entered g.When a character is entered by the user in the above program, the character itself is not stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using
%c
text format, the entered character is displayed. If we use %d
to display the character, it's ASCII value is printed.Example 8: ASCII Value
Output
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
// When %c is used, a character is displayed
printf("You entered %c.\n",chr);
// When %d is used, ASCII value is displayed
printf("ASCII value is % d.", chr);
return 0;
}
Enter a character: g You entered g. ASCII value is 103.
I/O Multiple Values
Here's how you can take multiple inputs from the user and display them.Output
#include <stdio.h>
int main()
{
int a;
float b;
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
Enter integer and then a float: -3 3.4 You entered -3 and 3.400000
Format Specifiers for I/O
As you can see from the above examples, we use%d
forint
%f
forfloat
%lf
fordouble
%c
forchar
Data Type | Format Specifier | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
int |
%d |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
char |
%c |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
float |
%f |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
double |
%lf |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
short int |
%hd |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
unsigned int |
%u |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
long int |
%li |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
long long int |
%lli |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
unsigned long int |
%lu |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
unsigned long long int |
%llu |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
signed char |
%c |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
unsigned char |
%c |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
long double C Introduction Examples
In this tutorial, you will find links to simple C
programs such as: displaying a line, adding two numbers, find ASCII
value of a character, etc.
To understand these topics better, we have created some examples. Before you go through these examples, we suggest you to try creating these programs on our own. We understand that programming can by start If you are just a programming newbie. In that case, go through each example below and see if you can understand them. Once you do that, try writing these programs on your own. Examples |
%Lf C Programming Operators
In this tutorial, you will learn about different
operators in C programming with the help of examples.
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.C Arithmetic OperatorsAn arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).
Example 1: Arithmetic Operators
a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1The operators + , - and * computes addition, subtraction, and multiplication respectively as you might have expected.In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25 .The modulo operator % computes the remainder. When a=9 is divided by b=4 , the remainder is 1 . The % operator can only be used with integers.Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2 . Then in C programming,// Either one of the operands is a floating-point number a/b = 2.5 a/d = 2.5 c/b = 2.5 // Both operands are integers c/d = 2 C Increment and Decrement OperatorsC programming has two operators increment++ and decrement -- to change the value of an operand (constant or variable) by 1.Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.Example 2: Increment and Decrement OperatorsOutput ++a = 11 --b = 99 ++c = 11.500000 ++d = 99.500000Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a-- . Visit this page to learn more about how increment and decrement operators work when used as postfix.C Assignment OperatorsAn assignment operator is used for assigning a value to a variable. The most common assignment operator is=
Example 3: Assignment OperatorsOutput c = 5 c = 10 c = 5 c = 25 c = 5 c = 0 C Relational OperatorsA relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.Relational operators are used in decision making and loops.
Example 4: Relational Operators
Output 5 == 5 is 1 5 == 10 is 0 5 > 5 is 0 5 > 10 is 0 5 < 5 is 0 5 < 10 is 1 5 != 5 is 0 5 != 10 is 1 5 >= 5 is 1 5 >= 10 is 0 5 <= 5 is 1 5 <= 10 is 1 C Logical OperatorsAn expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.
Example 5: Logical OperatorsOutput (a == b) && (c > b) is 1 (a == b) && (c < b) is 0 (a == b) || (c < b) is 1 (a != b) || (c < b) is 0 !(a != b) is 1 !(a == b) is 0Explanation of logical operator program
C Bitwise OperatorsDuring computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.Bitwise operators are used in C programming to perform bit-level operations.
Other OperatorsComma OperatorComma operators are used to link related expressions together. For example:
The sizeof operatorThesizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).Example 6: sizeof OperatorOutput Size of int = 4 bytes Size of float = 4 bytes Size of double = 8 bytes Size of char = 1 byte Other operators such as ternary operator ?: , reference operator & , dereference operator * and member selection operator -> will be discussed in later tutorials.Flow Control
C if...else Statement
In this tutorial, you will learn about if
statement (including if...else and nested if..else) in C programming.
This allows you to perform different action based on different test
condition.
C if StatementThe syntax of theif statement in C programming is:
How if statement works?Theif statement evaluates the test expression inside the parenthesis () .
To learn more about when test expression is evaluated to true (non-zero value) and false (0), check relational and logical operators. Example 1: if statementOutput 1 Enter an integer: -2 You entered -2. The if statement is easy.When the user enters -2, the test expression number<0 is evaluated to true. Hence, You entered -2 is displayed on the screen.Output 2 Enter an integer: 5 The if statement is easy.When the user enters 5, the test expression number<0 is evaluated to false and the statement inside the body of if is not executedC if...else StatementTheif statement may have an optional else block. The syntax of the if..else statement is:
How if...else statement works?If the test expression is evaluated to true,
Example 2: if...else statement
Enter an integer: 7 7 is an odd integer.When the user enters 7, the test expression number%2==0 is evaluated to false. Hence, the statement inside the body of else is executed.C if...else LadderTheif...else statement executes two different codes
depending upon whether the test expression is true or false. Sometimes, a
choice has to be made from more than 2 possibilities.The if...else ladder allows you to check between multiple test expressions and execute different statements. Syntax of nested if...else statement.
Example 3: C if...else LadderOutput Enter two integers: 12 23 Result: 12 < 23 Nested if...elseIt is possible to include anif...else statement inside the body of another if...else statement.Example 4: Nested if...elseThis program given below relates two integers using either< , > and = similar to the if...else ladder's example. However, we will use a nested if...else statement to solve this problem.
If the body of an
For example, this codeif...else statement has only one statement, you do not need to use brackets {} .is equivalent to
C for Loop
Loops are used in programming to execute a block
of code repeatedly until a specified condition is met. In this
tutorial, you will learn to create for loop in C programming.
C programming has three types of loops:
for loop in this tutorial. In the next tutorial, we will learn about while and do...while loop.for LoopThe syntax of thefor loop is:
How for loop works?
To learn more about test expression (when the test expression is evaluated to true and false), check out relational and logical operators. for loop Flowchart
Example 1: for loopOutput 1 2 3 4 5 6 7 8 9 10
Example 2: for loopOutput Enter a positive integer: 10 Sum = 55 The count is initialized to 1 and the test expression is evaluated. Since the test expression count<=num (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will equal to 1.Then, the update statement ++count is executed and the
count will equal to 2. Again, the test expression is evaluated. Since 2
is also less than 10, the test expression is evaluated to true and the
body of for loop is executed. Now, the sum will equal 3.This process goes on and the sum is calculated until the count reaches 11. When the count is 11, the test expression is evaluated to 0 (false), and the loop terminates. Then, the value of sum is printed on the screen.We will learn about while loop and do...while loop in the next tutorial.C while and do...while Loop
Loops are used in programming to execute a block
of code repeatedly until a specified condition is met. In this
tutorial, you will learn to create while and do...while loop in C
programming.
C programming has three types of loops.
for loop. In this tutorial, we will learn about while and do..while loop.while loopThe syntax of thewhile loop is:
How while loop works?
Flowchart of while loop
Example 1: while loop
1 2 3 4 5Here, we have initialized i to 1.
do...while loopThedo..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.The syntax of the do...while loop is:
How do...while loop works?
Flowchart of do...while LoopExample 2: do...while loopOutput Enter a number: 1.5 Enter a number: 2.4 Enter a number: -3.4 Enter a number: 4.2 Enter a number: 0 Sum = 4.70 C break and continue
We learned about loops in previous tutorials. In
this tutorial, we will learn to use break and continue statements with
the help of examples.
C breakThe break statement ends the loop immediately when it is encountered. Its syntax is:The break statement is almost always used with if...else statement inside the loop.How break statement works?Example 1: break statementOutput Enter a n1: 2.4 Enter a n2: 4.5 Enter a n3: 3.4 Enter a n4: -3 Sum = 10.30This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10 numbers? It's because if the user enters a negative number, the break statement is executed. This will end the for loop, and the sum is displayed.break is also used with the switch statement. This will be discussed in the next tutorial.C continueThecontinue statement skips the current iteration of the loop and continues with the next iteration. Its syntax is:The continue statement is almost always used with the if...else statement.How continue statement works?Example 2: continue statementOutput Enter a n1: 1.1 Enter a n2: 2.2 Enter a n3: 5.5 Enter a n4: 4.4 Enter a n5: -3.4 Enter a n6: -45.5 Enter a n7: 34.5 Enter a n8: -4.2 Enter a n9: -1000 Enter a n10: 12 Sum = 59.70In this program, when the user enters a positive number, the sum is calculated using sum += number; statement.When the user enters a negative number, the continue statement is executed and it skips the negative number from the calculation.C switch Statement
In this tutorial, you will learn to create switch statement in C programming.
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.Syntax of switch...caseHow does the switch statement work? The expression is evaluated once and compared with the values of each case label.
If we do not use
break , all statements after the matching label are executed.
The
default clause inside the switch statement is optional.switch Statement FlowchartExample: Simple CalculatorOutput Enter an operator (+, -, *,): - Enter two operands: 32.5 12.4 32.5 - 12.4 = 20.1 Since the operator is - , the control of the program jumps toprintf("%.1lf / %.1lf = %.1lf", n1, n2, n1/n2);Finally, the break statement terminates the switch statement.C go to Statement
In this tutorial, you will learn to create goto
statement in C programming. Also, you will learn when to use a goto
statement and when not to use it.
The
goto statement allows us to transfer control of the program to the specified label.Syntax of goto StatementThe label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.Example: goto StatementOutput 1. Enter a number: 3 2. Enter a number: 4.3 3. Enter a number: 9.3 4. Enter a number: -2.9 Sum = 16.60 Reasons to avoid gotogoto statement may lead to code that is buggy and hard to follow. For example,Also, the goto statement allows you to do bad stuff such as jump out of the scope.That being said, goto can be useful sometimes. For example: to break from nested loops.Should you use goto?If you think the use ofgoto statement simplifies your program, you can use it. That being said, goto is rarely useful and you can create any C program without using goto altogether.Here's a quote from Bjarne Stroustrup, creator of C++, "The fact that 'goto' can do anything is exactly why we don't use it". C Control Flow Examples
In this article, you will find a list of C
programs to sharpen your knowledge of decision-making statements and
loops.
|
|
| |
Comments