Basics of ‘C’
By : Oumellahni Nabil
Allali Ayoub
History of C Language
H istory of C language is interesting
to know. Here we are going to discuss a brief
history of the c language.
C programming language was developed in
1972 by Dennis Ritchie at bell laboratories of
AT&T (American Telephone & Telegraph), located
in the U.S.A.
Dennis Ritchie is known as the founder of the
c language.
It was developed to overcome the problems of
previous languages such as B, BCPL, etc.
Initially, C language was developed to be used
in UNIX operating system. It inherits many
features of previous languages such as B and
BCPL.
Features of C Language
C is the widely used language. It provides a lot of features that are
given below.
1) Simple :
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.
2) Portable
Unlike assembly language, c programs can be executed in many
machines with little bit or no change. But it is not platform-
independent.
3)Structured programming language
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.
4) Rich Library
C provides a lot of inbuilt functions that makes the development fast.
5) 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.
6) Speed
The compilation and execution time of C language is fast.
7) Pointer
We can directly interact with the memory by using the pointers.
We can use pointers for memory, structures, functions, array etc.
8) Extensible
C language is extensible because it can easily adopt new features.
First C Program
• Before starting the abcd of C language, you need to learn how to
write, compile and run the first c program.
• To write the first c program, open the C console and write the
following code:
#include <stdio.h>
void main() {
printf("Hello World !");
}
#include <stdio.h> includes the standard input output library
functions. The printf() function is defined in stdio.h .
printf scanf in C
• The printf() and scanf() functions are used for input and output in
C language. Both functions are inbuilt library functions, defined in
stdio.h (header file).
printf() function :
• The printf() function is used for output. It prints the given
statement to the console.
• The syntax of printf() function is given below:
printf("format string",argument_list);
• The format string can be %d (integer), %c (character), %s
(string), %f (float) etc.
scanf() function :
• The scanf() function is used for input. It reads the input data
from the console.
• scanf("format string",argument_list);
Variables in C
• The variable is a memory location name it used to store data, its
value can be changed, and it can be reused multiple times.
• Let's see the syntax to declare a variable:
type variableName;
• The example of declaring variable is given below:
int a;
float b;
char c;
• Here, a, b, c are variables and int,float,char are data types.
• We can also provide values while declaring the variables as given
below:
int a=10,b=20;
float f=20.8;
char c='A';
Rules for defining variables
o A variable can have alphabets, digits and underscore.
o A variable name can start with alphabet and underscore only. It
can't start with digit.
o No white space is allowed within variable name.
o A variable name must not be any reserved word or keyword e.g.
int, float etc.
• Valid variable names:
int a;
int _ab;
int a30;
• Invalid variable names:
int 2;
int a b;
int long;
Examples :
char ch = 'a’;
ch = 'l’;
Note: You should always try to give meaningful names to variables.
For example: firstName is a better variable name than fn.
int number = 5; // integer
variable number = 5.5; // error
double number; // error
Literals
Literals are data used for representing fixed values. They can be used
directly in the code. For example: 1, 2.5, 'c' etc.
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)
2. Floating-point Literals
•A floating-point literal is a numeric literal that has either a fractional
form or an exponent form. For example:
3. Characters
•A character literal is created by enclosing a single character inside
single quotation marks. For example: 'a', 'm', 'F', '2', '}' etc.
4. String Literals
•A string literal is a sequence of characters enclosed in double-quote
marks.
5.Constants
•If you want to define a variable whose value cannot be changed ,
you can use the const keyword .This will create a constant .
•You can also define a constant using the #define preprocessor
directive .
•By convention, constants are named in uppercase, example : PI, not
pi or Pi.
Data Types in C
Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
Data Types Memory Size Range
char 1 byte −128 to 127
short 2 byte −32,768 to 32,767
int 2 byte −32,768 to 32,767
signed int 2 byte −32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte −32,768 to 32,767
long int 4 byte
float 4 byte
double 8 byte
long double 10 byte
The commonly used format
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means
that the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned
integer means that the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value
always starts with a 0 value.
%x It is used to print the hexadecimal unsigned integer where the
hexadecimal integer value always starts with a 0x value. In this,
alphabetical characters are printed in small letters such as a, b, c, etc.
%f It is used for printing the decimal floating-point values. By default, it
prints the 6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or
Exponent.
%g It is used to print the decimal floating-point values, and it uses the
fixed precision, i.e., the value after the decimal in input would be
exactly the same as the value in the output.
%c It is used to print the unsigned character.
%s It is used to print the strings.
Specifying Precision
• We can specify the precision by using '.' (Dot) operator which is
followed by integer and format specifier.
• Example :
#include<stdio.h>
int main()
{
float x=12.2;
printf("%.2f", x);
return 0;
}
• Output
12.20
C Boolean
• In C, Boolean is a data type that contains two types of values, i.e., 0
and 1. Basically, the bool type value represents two types of
behavior, either true or false. Here, '0' represents false value, while
'1' represents true value.
• Syntax
bool variable_name;
• Let's understand through an example.
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x=false; // variable initialization.
if(x==true) // conditional statements
{
printf("The value of x is true");
}
else
printf("The value of x is FALSE");
return 0;
}
Reserved Keywords in C
• A keyword is a reserved word. You cannot use it as a variable
name, constant name etc. There are only 32 reserved words
(keywords) in C language.
• A list of 32 keywords in c language is given below:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigne void volatile while
d
Comments in C
• Comments in C language are used to provide information about
lines of code. It is widely used for documenting code. There are 2
types of comments in C language.
Single Line Comments
Single line comments are represented by double slash \\. Let's see an
example of single line comment in C.
#include <stdio.h>
void main() {
//printing information
printf("Hello C");
}
Multiple Line Comments
•Multi line comments are represented by slash asterisk \* ... *\. It can
occupy many lines of code but it can't be nested. Syntax:
/*
code
to be commented
*/
•Let's see an example of multi line comment in C.
#include <stdio.h>
void main(){
/*printing
information*/
printf("Hello C");
}
Escape Sequence in C
• An escape sequence in C language is a sequence of characters
that doesn't represent itself when used inside string literal or
character.
• It is composed of two or more characters starting with backslash \.
For example: \n represents new line.
Escape Sequence Meaning
\n New Line
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\0 Null
C Arithmetic Operators
Operator Meaning of Operator
+ addition or unary plus
subtraction or unary
-
minus
* multiplication
/ division
remainder after division
%
(modulo division)
C Increment and Decrement Operators
C 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.
Increment Operator
•Increment Operators are the unary operators used to increment or
add 1 to the operand value. The Increment operand is denoted by the
double plus symbol (++). It has two types, Pre Increment and Post
Increment Operators.
– Pre-increment Operator
•The pre-increment operator is used to increase the original value of
the operand by 1 before assigning it to the expression.
•Syntax
X = ++A;
-Post increment Operator
•The post-increment operator is used to increment the original value
of the operand by 1 after assigning it to the expression.
•Syntax
X = A++;
Decrement Operator
•Decrement Operator is the unary operator, which is used to
decrease the original value of the operand by 1. The decrement
operator is represented as the double minus symbol (--). It has two
types, Pre Decrement and Post Decrement operators.
Pre Decrement Operator
•The Pre Decrement Operator decreases the operand value by 1
before assigning it to the mathematical expression. In other words,
the original value of the operand is first decreases, and then a new
value is assigned to the other variable.
•Syntax
B = --A;
Post decrement Operator:
•Post decrement operator is used to decrease the original value of
the operand by 1 after assigning to the expression.
•Syntax
B = A--;
C Assignment Operators
Operator Example Same as
= a=b a=b
+= 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
C Relational Operators
Meaning of
Operator Example
Operator
5 == 3 is
== Equal to
evaluated to 0
5 > 3 is
> Greater than
evaluated to 1
5 < 3 is
< Less than
evaluated to 0
5 != 3 is
!= Not equal to
evaluated to 1
Greater than or 5 >= 3 is
>=
equal to evaluated to 1
Less than or 5 <= 3 is
<=
equal to evaluated to 0
C Logical Operators
Operator Meaning Example
If c = 5 and d = 2
Logical AND. True
then, expression
&& only if all operands
((c==5) && (d>5))
are true
equals to 0.
If c = 5 and d = 2
Logical OR. True
then, expression
|| only if either one
((c==5) || (d>5))
operand is true
equals to 1.
Logical NOT. True If c = 5 then,
! only if the operand expression !(c==5)
is 0 equals to 0.
Exercise :
• Evaluate the following expressions assuming
A = 20 , B = 5 , C = -10 , D = 2 , X = 12 .
Note each time the value returned as the result of the expression and
the values of the variables whose contents have changed
(1) (5 * X) +2 * ((3 * B) +4)
(2) (5 * (X + 2) * 3) * (B + 4)
(3) A == (B = 5)
(4) A + = (X + 5)
(5) A! = (C * = (-D))
(6) A * = C + (X-D)
(7) A% = D ++
(8) A% = ++ D
(9) (X ++) * (A + C)
Selections and Loops
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.
•There are the following variants of if statement in C language.
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.
if(expression){
//code to be executed
}
Flowchart of if statement in C
Let's see a simple example of C language if statement.
#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
}
•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 simiulteneously. 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.
if(expression) {
//code to be executed if condition is true
}
else {
//code to be executed if condition is false
}
Flowchart of the if-else statement in C
Let's see the simple example to check whether a number is
even or odd using if-else statement in C language.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}
• If else-if ladder Statement
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.
if(condition1){
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Flowchart of else-if ladder statement in C
• The example of an if-else-if statement in C language is
given below.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Exercise :
• Body Mass Index (BMI) is a measure of health based on height and weight.
You can calculate your BMI by taking your weight in kilograms and dividing
it by the square of your height in meters. The interpretation of BMI for
people 20 years or older is as follows:
• Write a program that prompts the user to enter a weight in pounds and
height in inches and displays the BMI. Note that one pound is 0.45359237
kilograms and one inch is 0.0254 meters
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 possibles 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.
The syntax of switch statement in c language is given below:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
Rules for switch statement in C language
•1) The switch expression must be of an integer or character type.
•2) The case value must be an integer or character constant.
•3) The case value can be used only inside the switch statement.
•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.
Flowchart of switch statement in C
• Let's see a simple example of c language switch statement.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
C Loops
Why use loops in C language?
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 runup to 10 iterations
Advantage of loops in C
•1) It provides code reusability.
•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
•There are three types of loops in C language that is given below:
1.do while
2.while
3.for
do-while loop in C
•The do-while loop continues until a given condition satisfies. It is
also called post tested loop. It is used when it is necessary to execute
the loop at least once (mostly menu driven programs).
•The syntax of do-while loop in c language is given below:
do{
//code to be executed
} while(condition);
Flowchart of do while loop
Do - while example
•There is given the simple program of c language do while loop
where we are printing the table of 1.
#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
} while(i<=10);
return 0;
}
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.
•The syntax of while loop in c language is given below:
while(condition){
//code to be executed
}
Flowchart of while loop in C
• Let's see the simple program of while loop that prints table
of 1.
#include<stdio.h>
int main(){
int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
return 0;
}
Exercise :
• Write a program that reads and calculates the sum of an
unspecified number of integers. The input 0 signifies the
end of the input
• 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.
• The syntax of for loop in c language is given below:
for(Expression 1; Expression 2; Expression 3){
//code to be executed
}
Flowchart of for loop in C
Let's see the simple program of for loop that prints table of 1.
#include<stdio.h>
int main(){
int i;
for(i=1;i<=10;i++){
printf("%d \n",i);
return 0;
}
Exercise :
• write a program allowing to take a number H of
lines, then to realize a triangle of stars
C break statement
• he break is a keyword in C which is used to bring the program
control out of the loop. The break statement is used inside loops
or switch statement. The break statement breaks the loop one by
one, i.e., in the case of nested loops, it breaks the inner loop first
and then proceeds to outer loops. The break statement in C can
be used in the following two scenarios:
- With switch case
-With loop
Syntax:
//loop or switch case
break;
Flowchart of break in c
Example
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
}
C continue statement
• The continue statement in C language is used to bring the
program control to the beginning of the loop. The continue
statement skips some lines of code inside the loop and continues
with the next iteration. It is mainly used for a condition so that we
can skip some code for a particular condition.
• Syntax:
//loop statements
continue;
//some lines of the code which is to be skipped
• Example
#include<stdio.h>
void main ()
{
int i = 0;
while(i<5)
{
i++;
if(i==2)
continue;
printf("%d\n", i);
}
}
Type Casting in C
• Typecasting allows us to convert one data type into other. In C
language, we use cast operator for typecasting which is denoted
by (type).
Syntax:
(type)value;
• Note: It is always recommended to convert the lower value to
higher for avoiding data loss.
• Without Type Casting:
int f= 9/4;
printf("f : %d\n", f );//Output: 2
• With Type Casting:
float f=(float) 9/4;
printf("f : %f\n", f );//Output: 2.250000
• Let's see a simple example to cast int value into the float.
#include<stdio.h>
int main(){
float f= (float)9/4;
printf("f : %f\n", f );
return 0;
}
Conditional Expressions
• A conditional expression evaluates an expression based on a
condition.
• Conditional expressions have a completely different structure and
do not include an explicit if. The syntax is shown here:
Boolean-expression ? expression1 : expression2;
• You might want to assign a variable a value that is restricted by
certain conditions. For example, the following statement assigns 1
to y if x is greater than 0, and -1 to y if x is less than or equal to 0.
if (x > 0)
y = 1;
else
y = -1;
Alternatively, as in the next example, you can use a conditional
expression to achieve the same result:
y = x > 0 ? 1 : -1;