C - Unit 1,2,3
C - Unit 1,2,3
C - Unit 1,2,3
INTRODUCTION TO C PROGRAMMING
History of C Language
C programming is considered as the base for other programming languages, that is why it is known as
mother language.
It can be defined by the following ways: with lazy loaded modules [2020]
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the
programming languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being used in
many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be declared before being used.
In the C language, we break the program into parts using functions. It makes the program easier to
understand and modify.
C is considered as a middle-level language because it supports the feature of both low-level and
high-level languages. C language program is converted into assembly code, it supports pointer
arithmetic (low-level), but it is machine independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast
to run. But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.
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
Digits
0123456789
Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
White space Characters
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;
C Keywords
do if static while
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:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an identifier
because int is a keyword.
Rules for naming identifiers
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. You cannot use keywords like int, while etc. as identifiers.
4. 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.
You can choose any name as an identifier if you follow the above rule; however, give meaningful names
to identifiers that make sense.
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:
char ch = 'a';
// some code
ch = 'l';
C is a strongly typed language. This means that the variable type cannot be changed once it is declared.
For example:
Here, the type of number variable is int. You cannot assign a floating-point (decimal) value 5.5 to this
variable. Also, you cannot redefine the data type of the variable to double. By the way, to store the
decimal values in C, you need to declare its type to either double or float.
Literals
Literals are data used for representing fixed values. They can be used directly in the code. 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)
For example:
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.
Escape Sequences
Escape
Character
Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
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:
Constants
If you want to define a variable whose value cannot be changed, you can use the const keyword. This
will create a constant. For example,
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,
int myVar;
char 1 %c
float 4 %f
double 8 %lf
signed char 1 %c
unsigned char 1 %c
int id;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.
float and double
float and double are used to hold real numbers.
float salary;
double price;
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 be void.
Note that, you cannot create variables of void type.
short and long
If you need to use a large number, you can use a type specifier long. Here's how:
long a;
long long b;
long double c;
short d;
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int
// invalid code: unsigned int cannot hold negative integers
unsigned int num = -35;
Here, the variables x and num can hold only zero and positive values because we have used
the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1, whereas
variable x can hold values from 0 to 232-1.
Derived Data Types
Data types that are derived from fundamental data types are derived types. For example: arrays,
pointers, function types, structures, etc.
bool type
Enumerated type
Complex types
To write the first c program, open the C console and write the following code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful
execution and 1 for unsuccessful execution.
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
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Output
C Programming
All valid C programs must contain the main() function. The code execution begins from the start
of the main() 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 include stdio.h header file using the #include
<stdio.h> statement.
The return 0; statement inside the main() function is the "Exit status" of the program. It's
optional.
Example 2: Integer Output
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
We 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
#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;
number1 = 13.500000
number2 = 12.400000
#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c", chr);
return 0;
}
Output
character = a
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output
Enter an integer: 4
Number = 4
Here, 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.
#include <stdio.h>
int main()
{
float num1;
double num2;
return 0;
}
Output
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Output
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
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
Output
Enter a character: g
You entered g.
ASCII value is 103.
#include <stdio.h>
int main()
{
int a;
float b;
Output
%d for int
%f for float
%lf for double
%c for char
Here's a list of commonly used C data types and their format specifiers.
int %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
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 Operators
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication,
division etc on numerical values (constants and variables).
* multiplication
/ division
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
a/d = 2.5
c/b = 2.5
c/d = 2
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes
like a++ and a--.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is =
Operator Example Same as
= a=b a=b
Operator Example Same as
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Example 3: Assignment Operators
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
C Relational Operators
A 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.
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
return 0;
}
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 Operators
An 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.
Operato
Meaning Example
r
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
Output
(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 0
C Bitwise Operators
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc
are converted to bit-level which makes processing faster and saves power.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators:
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf(“Size of int=%lu bytes\n”,sizeof(a));
printf(“Size of float=%lu bytes\n”,sizeof(b));
printf(“Size of double=%lu bytes\n”,sizeof©);
printf(“Size of char=%lu byte\n”,sizeof(d));
return 0;
}
Output
Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Show Examples
sizeof() Returns the size of a variable. Sizeof(a), where a is integer, will return 4.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
C Expressions
An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a constant.
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation
of a particular expression produces a specific value.
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an expression.
Arithmetic Expressions
When an expression contains only integral operands, then it is known as pure integer expression when
it contains only real operands, it is known as pure real expression, and when it contains both integral
and real operands, it is known as mixed mode expression.
The expressions are evaluated by performing one operation at a time. The precedence and associativity
of operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
o When both the operands are of type integer, then arithmetic will be performed, and the result of
the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional
part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of
the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic
will be performed. In this case, the first operand is converted into a real operand, and then
arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first
value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.
Relational Expressions
Relational Description
Expression
x%2 = = 0 This condition is used to check whether the x is an even number or not. The
relational expression results in value 1 if x is an even number otherwise
results in value 0.
A+b = = x+y It is used to check whether the expression “a+b” is equal to the expression
“x+y”.
1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf(“The number x is even”);
9. }
10. else
11. printf(“The number x is not even”);
12. return 0;
13. }
Output
Logical Expressions
Logical Description
Expressions
( x > 4 ) && ( x < It is a test condition to check whether the x is greater than 4 and x is less than 6.
6) The result of the condition is true only when both the conditions are true.
X > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than
11. The result of the test condition is true if either of the conditions holds true
value.
! ( x > 10 ) && ( y = It is a test condition used to check whether x is not greater than 10 and y is
=2) equal to 2. The result of the condition is true if both the conditions are true.
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
6. if ( (x <10) && (y>5))
7. {
8. printf(“Condition is true”);
9. }
10. else
11. printf(“Condition is false”);
12. return 0;
13. }
Output
Let’s see a simple example of “| |” operator
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 9;
6. if ( (x <6) || (y>10))
7. {
8. printf(“Condition is true”);
9. }
10. else
11. printf(“Condition is false”);
12. return 0;
13. }
Output
Conditional Expressions
The above expression is a conditional expression which is evaluated on the basis of the value of the
exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.
1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? ‘M’: ‘U’;
8. if(status == ‘M’)
9. printf(“Married”);
10. else
11. printf(“Unmarried”);
12. return 0;
13. }
Output
1 if statement
2 if...else statement
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of values.
C if else Statement
The if-else statement in C is used to perform the operations based on some specific condition. The
operations specified in if block are executed if and only if the given condition is true.
o If statement
o If-else statement
o If else-if ladder
o Nested if
If Statement
The if statement is used to check some given condition and perform some operations depending upon
the correctness of that condition. It is mostly used in the scenario where we need to perform the
different operations for the different conditions. The syntax of the if statement is given below.
1. if(expression){
2. //code to be executed
3. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
Enter a number:4
4 is even number
enter a number:5
1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
22. }
23. }
Output
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is an
extension to the if statement using which, we can perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the incorrectness of the condition. Here, we must
notice that if and else block cannot be executed simultaneously. Using if-else statement is always
preferable since it always invokes an otherwise case with every if condition. The syntax of the if-else
statement is given below.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
Let's see the simple example to check whether a number is even or odd using if-else statement in C
language.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
1. #include <stdio.h>
2. int main()
3. {
4. int age;
5. printf("Enter your age?");
6. scanf("%d",&age);
7. if(age>=18)
8. {
9. printf("You are eligible to vote...");
10. }
11. else
12. {
13. printf("Sorry ... you can't vote");
14. }
15. }
Output
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where
there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a
condition is true then the statements defined in the if block will be executed, otherwise if some other
condition is true then the statements defined in the else-if block will be executed, at the last if none of
the condition is true then the statements defined in the else block will be executed. There are multiple
else-if blocks possible. It is similar to the switch case statement where the default is executed instead of
else block if none of the cases is matched.
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Program to calculate the grade of the student according to the specified marks.
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
21. printf("You scored grade C ...");
22. }
23. else
24. {
25. printf("Sorry you are fail ...");
26. }
27. }
Output
C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute
multiple operations for the different possible values of a single variable called switch variable. Here, We
can define various statements in the multiple cases for the different values of a single variable.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
4) The break statement in switch case is not must. It is optional. If there is no break statement found in
the case, all the cases will be executed present after the matched case. It is known as fall through the
state of C switch statement.
Let's try to understand it by the examples. We are assuming that there are following variables.
1. int x,y,z;
2. char a,b;
3. float f;
Valid Switch Invalid Switch Valid Case Invalid Case
First, the integer expression specified in the switch statement is evaluated. This value is then matched
one by one with the constant values given in the different cases. If a match is found, then all the
statements specified in that case are executed along with the all the cases present after that case
including the default statement. No two cases can have similar values. If the matched case contains a
break statement, then all the cases present after that will be skipped, and the control comes out of the
switch. Otherwise, all the cases following the matched case will be executed.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }
Output
hi
In C language, the switch statement is fall through; it means if you don't use a break statement in the
switch case, all the cases after the matching case will be executed.
Let's try to understand the fall through state of switch statement by the example given below.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
Output
enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
We can use as many switch statement as we want inside a switch statement. Such type of statements is
called nested switch case statements. Consider the following example.
1. #include <stdio.h>
2. int main () {
3. int i = 10;
4. int j = 20;
5. switch(i) {
6. case 10:
7. printf("the value of i evaluated in outer switch: %d\n",i);
8. case 20:
9. switch(j) {
10. case 20:
11. printf("The value of j evaluated in nested switch: %d\n",j);
12. }
13. }
14. printf("Exact value of i is : %d\n", i );
15. printf("Exact value of j is : %d\n", j );
16. return 0;
17. }
Output
The looping can be defined as repeating the same process multiple times until a specific condition
satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are going to
learn all the aspects of C loops.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the
program so that instead of writing the same code again and again, we can repeat the same code for a
finite number of times. For example, if we need to print the first 10 natural numbers then, instead of
using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantage of loops in C
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
1. do while
2. while
3. for
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several
parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop
at least once. The do-while loop is mostly used in menu-driven programs where the termination
condition depends upon the end user.
1. do{
2. //code to be executed
3. }while(condition);
Example2: Program to print table for the given number using do while loop
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be
executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if
statement. The while loop is mostly used in the case where the number of iterations is not known in
advance.
1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in C
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
o A conditional expression is used to check the condition. The statements defined inside the while
loop will repeatedly execute until the given condition fails.
o The condition will be true if it returns 0. The condition will be false if it returns any non-zero
number.
o In while loop, the condition expression is compulsory.
o Running a while loop without a body is possible.
o We can have more than one conditional expression in while loop.
o If the loop body contains only one statement, then the braces are optional.
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int j = 1;
5. while(j+=2,j<=10)
6. {
7. printf("%d ",j);
8. }
9. printf("%d",j);
10. }
Output
3 5 7 9 11
Example 2
1. #include<stdio.h>
2. void main ()
3. {
4. while()
5. {
6. printf("hello Javatpoint");
7. }
8. }
Output
compile time error: while loop can't be empty
Example 3
1. #include<stdio.h>
2. void main ()
3. {
4. int x = 10, y = 2;
5. while(x+y-1)
6. {
7. printf("%d %d",x--,y--);
8. }
9. }
Output
infinite loop
If the expression passed in while loop results in any non-zero value then the loop will run the infinite
number of times.
1. while(1){
2. //statement
3. }
for loop in C
The for loop in C language is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like the array and linked list.
1. for(Expression 1; Expression 2; Expression 3){
2. //code to be executed
3. }
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Properties of Expression 1
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }
Output
35 36
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
9. }
Output
1234
Properties of Expression 2
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;i<=4;i++)
6. {
7. printf("%d ",i);
8. }
9. }
output
01234
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i,j,k;
5. for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
6. {
7. printf("%d %d %d\n",i,j,k);
8. j+=2;
9. k+=3;
10. }
11. }
Output
000
123
246
369
4 8 12
Example 3
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;;i++)
6. {
7. printf("%d",i);
8. }
9. }
Output
infinite loop
Properties of Expression 3
o Expression 3 is used to update the loop variable.
o We can update more than one variable at the same time.
o Expression 3 is optional.
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int i=0,j=2;
5. for(i = 0;i<5;i++,j=j+2)
6. {
7. printf("%d %d\n",i,j);
8. }
9. }
Output
02
14
26
38
4 10
Loop body
The braces {} are used to define the scope of the loop. However, if the loop contains only one statement,
then we don't need to use braces. A loop without a body is possible. The braces work as a block
separator, i.e., the value variable declared inside for loop is valid only for that block and not outside.
Consider the following example.
1. #include<stdio.h>
2. void main ()
3. {
4. int i;
5. for(i=0;i<10;i++)
6. {
7. int i = 20;
8. printf("%d ",i);
9. }
10. }
Output
20 20 20 20 20 20 20 20 20 20
To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to
provide two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.
1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to javatpoint");
7. }
8. }
If you run this program, you will see above statement infinite times.
C – JUMP STATEMENTS
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 break
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.
How break statement works?
Output
Enter n1: 2.4
Enter n4: -3
Sum = 10.30
This 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.
In C, break is also used with the switch statement. This will be discussed in the next tutorial.
C continue
The continue statement skips the current iteration of the loop and continues with the next iteration. Its
syntax is:
continue;
#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
Output
In 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 goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the
program control to a predefined label. The goto statment can be used to repeat some part of the code for
a particular condition. It can also be used to break the multiple loops which can't be done by using a
single break statement. However, using goto is avoided these days since it makes the program less
readable and complecated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
goto example
1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }
The only condition in which using goto is preferable is when we need to break the multiple loops using a
single statement at the same time. Consider the following example.
1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }
000
001
002
010
011
012
020
021
022
030
came out of the loop
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the
elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
data_type array_name[array_size];
int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the following code.
int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
In the following program, we are using bubble sort method to sort the array in ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns. However, 2D arrays are created to
implement a relational database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at least
the second dimension of the array. The two-dimensional array can be declared and defined in the
following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
C Strings
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The
character array or the string is used to manipulate text such as word or sentences. Each character in the
array occupies one byte of memory, and the last character must always be 0. The termination character
('\0') is important in a string since it is the only way to identify where the string ends. When we define a
string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
1. By char array
2. By string literal
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.Stay
While declaring string, size is not mandatory. So we can write the above code as given below:
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
char ch[]="javatpoint";
In such case, '\0' will be appended at the end of the string by the compiler.
There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as a format
specifier for the string in c language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[11]="javatpoint";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output
Traversing String
Traversing the string is one of the most important aspects in any of the programming languages. We may
need to manipulate a very large text which can be done by traversing the text. Traversing string is
somewhat different from the traversing an integer array. We need to know the length of the array to
traverse an integer array, whereas we may use the null character in the case of string to identify the end
the string and terminate the loop.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
Let's see the same example of counting the number of vowels by using the null character.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
Till now, we have used scanf to accept the input from the user. However, it can also be used in the case of
strings but with a different scenario. Consider the below code which stores the string while space is
encountered.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%s",s);
7. printf("You entered %s",s);
8. }
Output
It is clear from the output that, the above code will not work for space separated strings. To make this
code working for the space separated strings, the minor changed required in the scanf function, i.e.,
instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the compiler to store
the string s while the new line (\n) is encountered. Let's consider the following example to store the
space-separated strings.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%[^\n]s",s);
7. printf("You entered %s",s);
8. }
Output
Here we must also notice that we do not need to use address of (&) operator in scanf to store a string
since string s is an array of characters and the name of the array, i.e., s indicates the base address of the
string (character array) therefore we need not use & with it.
However, there are the following points which must be noticed while entering the strings by using scanf.
o The compiler doesn't perform bounds checking on the character array. Hence, there can be a case
where the length of the string can exceed the dimension of the character array which may always
overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a header file
string.h. The gets() is capable of receiving only one string at a time.
C String Functions
No Function Description
.
3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
Output:
The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are
equal.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
Output:
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
Output:
The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr()
function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
Output:
The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr()
function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
Output:
The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is
used to return substring from first match till the last character.
Syntax:
char *strstr(const char *string, const char *match)
string: It represents the full string from where substring will be searched.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[100]="this is javatpoint with c and java";
5. char *sub;
6. sub=strstr(str,"java");
7. printf("\nSubstring is: %s",sub);
8. return 0;
9. }
Output: