0% found this document useful (0 votes)
36 views26 pages

Introduction to C Programming Basics

Uploaded by

Mohamed Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views26 pages

Introduction to C Programming Basics

Uploaded by

Mohamed Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT - I:

Basic of C: History of C and its importance – Structure of a C program – Data Types –


Constants and Variables – Operators and Expressions – Order of Precedence,
Evaluating of Arithmetic Expressions – Type Conversion- Decision Statements: if, if-
else, and nested if statements.

OVERVIEW OF C LANGUAGE
 C is a structured programming language developed by Dennis Ritchie in 1973 at
Bell Laboratories.
 It is one of the most popular computer languages today because of its structure,
high-level abstraction, machine independent feature etc.
 C language was developed to write the UNIX operating system, hence it is
strongly associated with UNIX, which is one of the most popular network
operating system in use today and heart of internet data superhighway.

HISTORY OF C LANGUAGE

 C language has evolved from three different structured language ALGOL, BCPL
and B Language.

 It uses many concepts from these languages while introduced many new
concepts such as datatypes, struct, pointer etc.

 In 1988, the language was formalised by American National Standard


Institute(ANSI). In 1990, a version of C language was approved by
the International Standard Organisation(ISO) and that version of C is also
referred to as C89.

Page | 1
Why C Language is so popular?
 C language is a very good language to introduce yourself to the programming
world, as it is a simple procedural language which is capable of doing wonders.

 Programs written in C language takes very less time to execute and almost
executes at the speed of assembly language instructions.

 Initially C language was mainly used for writing system level programs, like
designing operating systems, but there are other applications as well which can
be very well designed and developed using C language, like Text Editors,
Compilers, Network Drivers etc.

Page | 2
Features of C language

 It is a robust language with rich set of built-in functions and operators that can be
used to write any complex program.
 The C compiler combines the capabilities of an assembly language with features of
a high-level language.
 Programs Written in C are efficient and fast. This is due to its variety of data type
and powerful operators.
 It is many time faster than BASIC.
 C is highly portable this means that programs once written can be run on another
machines with little or no modification.
 Another important feature of C program, is its ability to extend itself.
 A C program is basically a collection of functions that are supported by C library. We
can also create our own function and add it to C library.
 C language is the most widely used language in operating systems and embedded
system development today.

Key points to remember in C language:


1. The C language is a structure oriented programming language developed by
Dennis Ritchie.
2. The C language is belonging to middle level programming language.
3. Operating system programs such as Windows, Unix, Linux are written in C
language.
4. C89/C90 and C99 are two standardized editions of C language.
5. C has been written in assembly language.
6. C language is a structured language:

Structure oriented language:


 In this type of language, large programs are divided into small programs called
functions
 Prime focus is on functions and procedures that operate on the data
 Data moves freely around the systems from one function to another
 Program structure follows “Top Down Approach”
 Examples: C, Pascal, ALGOL and Modula-2

Page | 3
Object oriented language:
 In this type of language, programs are divided into objects
 Prime focus is in the data that is being operated and not on the functions or
procedures
 Data is hidden and cannot be accessed by external functions
 Program structure follows “Bottom UP Approach”
 Examples: C++, JAVA and C# (C sharp)

Non structure oriented language:


 There is no specific structure for programming this language. Examples: BASIC,
COBOL, FORTRAN

STRUCTURE OF A C PROGRAM

C Basic commands Explanation

This is a preprocessor command that includes


standard input output header file(stdio.h) from
#include <stdio.h> the C library before compiling a C program

This is the main function from where execution


int main() of any C program begins.

This indicates the beginning of the main


{ function.

whatever is given inside the command “/* */”


in any C program, won‟t be considered for
/*_some_comments_*/ compilation and execution.

printf command prints the output onto the


printf(“Hello_World! “); screen.

This command waits for any character input


getch(); from keyboard.

Page | 4
This command terminates C program (main
return 0; function) and returns 0.

} This indicates the end of the main function.

DATATYPES

A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.

There are the following data types in C language.

Page | 5
Basic Data Types

The basic data types are integer-based and floating-point based. C language
supports both signed and unsigned literals.

Page | 6
TOKENS

A token in C can be defined as the smallest individual element of the C


programming language that is meaningful to the compiler. It is the basic component of
a C program.

Types of Tokens in C

The tokens of C language can be classified into six types based on the
functions they are used to perform. The types of C tokens are as follows:

1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since keywords
are referred names for a compiler, they can‟t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not allowed.
You cannot redefine keywords. However, you can specify the text to be substituted for
keywords before compilation by using C preprocessor directives. C language
supports 32 keywords which are given below:

auto double int struct


break else long switch
case enum register typedef
Page | 7
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables,
functions, and arrays. These are user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the underscore(_) as a first
character. Identifier names must differ in spelling and case from any keywords. You
cannot use keywords as identifiers; they are reserved for special use. Once declared,
you can use the identifier in later program statements to refer to the associated value.
A special identifier called a statement label can be used in goto statements.

Rules for Naming Identifiers


Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special
character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are
significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be
treated as different.
For example,

 main: method name.


 a: variable name.
3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal
variables but with the difference that their values can not be modified in the program
once they are defined. Constants may belong to any of the data types.

Examples of Constants in C

Page | 8
const int c_var = 20;
const int* const ptr = &c_var;

4. C Token – Strings
Strings are nothing but an array of characters ended with a null character
(„\0‟). This null character indicates the end of the string. Strings are always enclosed
in double quotes. Whereas, a character is enclosed in single quotes in C and C++.

Examples of String

char string[20] = {„g‟, ‟e‟, „e‟, „k‟, „s‟, „f‟, „o‟, „r‟, „g‟, ‟e‟, „e‟, „k‟, „s‟, „ \0‟};
char string[20] = “geeksforgeeks”;

char string [] = “geeksforgeeks”;

5. C Token – Special Symbols


The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose. Some of these are listed below:

 Brackets[]: Opening and closing brackets are used as array element


references. These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and
function parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating
parameters in function calls.
 Colon(:): It is an operator that essentially invokes something called an
initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one
logical entity. That‟s why each individual statement must be ended with a
semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables.
 Assignment operator(=): It is used to assign values and for logical operation
validation.
Page | 9
 Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Used as a destructor to free some space from memory.

6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act are called operands.

CONSTANTS

A constant in C is a variable that cannot be modified once it is declared in the


program. We cannot make any change in the value of the constant variables after
they are defined.

How to define a constant in C?


We define a constant in C language using the const keyword. Also known as a
const type qualifier, the const keyword is placed at the start of the variable
declaration to declare that variable as a constant.

Syntax to Define Constant

const data_type var_name = value;

Page | 10
VARIABLES

A variable in C language is the name associated with some memory location


to store data of different types. There are many types of variables in C depending on
the scope, storage class, lifetime, type of data they store, etc. A variable is the basic
building block of a C program that can be used in expressions as a substitute in place
of the value it stores.

The syntax to declare a variable in C specifies the name and the type of the variable.

data_type variable_name = value; // defining single variable


or
data_type variable_name1, variable_name2; // defining multiple variable
Here,

 data_type: Type of data that a variable can store.


 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.

Example
int var; // integer variable

char a; // character variable

float fff; // float variables

OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following types
of operators

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators

Page | 11
Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language.

Relational Operators

The following table shows all the relational operators supported by C.

Logical Operators

Following table shows all the logical operators supported by C language.

Page | 12
Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation.

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C.

Page | 13
Assignment Operators

The following table lists the assignment operators supported by the C language

Page | 14
EXPRESSIONS
An expression is a combination of operators, constants and variables. An
expression may consist of one or more operands, and zero or more operators to
produce a value.

Example:
a+b

s-1/7*f

etc

Types of Expressions:
Expressions may be of the following types:

Page | 15
 Constant expressions: Constant Expressions consists of only constant values. A
constant value is one that doesn‟t change.
Examples:
5, 10 + 5 / 6.0, 'x‟

 Integral expressions: Integral Expressions are those which produce integer


results after implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)

where x and y are integer variables.

 Floating expressions: Float Expressions are which produce floating point results
after implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75

where x and y are floating point variables.

 Relational expressions: Relational Expressions yield results of type bool which


takes a value true or false. When arithmetic expressions are used on either side of
a relational operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:
Page | 16
x <= y, x + y > 2

 Logical expressions: Logical Expressions combine two or more relational


expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5

 Pointer expressions: Pointer Expressions produce address values.


Examples:
&x, ptr, ptr++

where x is a variable and ptr is a pointer.

 Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level.
They are basically used for testing or shifting bits.
Examples:
x << 3

shifts three bit position to left

y >> 1

shifts one bit position to right.

Shift operators are often used for multiplication and division by powers of two.

ORDER OF PRECEDENCE
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.

Page | 17
TYPE CONVERSION
Type conversion in C is the process of converting one data type to another. The type
conversion is only performed to those data types where conversion is possible. Type
conversion is performed by a compiler. In type conversion, the destination data type
can‟t be smaller than the source data type.

For example, if you try to divide two integers, 5 by 2, you would expect the result to
be 2.5. But since we are working with integers (and not floating-point values), the
following example will just output 2:

Example

int x = 5;
int y = 2;
int sum = 5 / 2;

Page | 18
printf("%d", sum); // Outputs 2

To get the right result, you need to know how type conversion works.

There are two types of conversion in C:

 Implicit Conversion (automatically)


 Explicit Conversion (manually)

Implicit Conversion

Implicit conversion is done automatically by the compiler when you assign a value of
one type to another.

For example, if you assign an int value to a float type:

Example

// Automatic conversion: int to float


float myFloat = 9;

printf("%f", myFloat); // 9.000000

As you can see, the compiler automatically converts the int value 9 to a float value
of 9.000000.

This can be risky, as you might lose control over specific values in certain situations.

Especially if it was the other way around - the following example automatically converts
the float value 9.99 to an int value of 9:

Example

// Automatic conversion: float to int


int myInt = 9.99;

printf("%d", myInt); // 9

Page | 19
What happened to .99? We might want that data in our program! So be careful. It is
important that you know how the compiler work in these situations, to avoid unexpected
results.

As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. And
as you know from the beginning of this page, if you store the sum as an integer, the
result will only display the number 2. Therefore, it would be better to store the sum as
a float or a double, right?

Example

float sum = 5 / 2;

printf("%f", sum); // 2.000000

Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in
the division. In this case, you need to manually convert the integer values to floating-
point values. (see below).

Explicit Conversion

Explicit conversion is done manually by placing the type in parentheses () in front of the
value.

Considering our problem from the example above, we can now get the right result:

Example

// Manual conversion: int to float


float sum = (float) 5 / 2;

printf("%f", sum); // 2.500000

DECISION STATEMENTS
The conditional statements (also known as decision control structures) such as
if, if else, switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate
one or more conditions and make the decision whether to execute a set of statements

Page | 20
or not. These decision-making statements in programming languages decide the
direction of the flow of program execution.

Types of Conditional Statements in C

1. if
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not i.e if
a certain condition is true then a block of statements is executed otherwise not.

Syntax of if Statement

if(condition)
{
// Statements to execute if
// condition is true
}

Here, the condition after evaluation will be either true or false. C if statement
accepts boolean values – if the value is true then it will execute the block of
Page | 21
statements below it otherwise not. If we do not provide the curly braces „{„ and „}‟ after
if(condition) then by default if statement will consider the first immediately below
statement to be inside its block.

Example

#include <stdio.h>

int main()
{
int i = 10;

if (i > 15) {
printf("10 is greater than 15");
}

printf("I am Not in if");


}

Output
I am Not in if

2. if-else
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won‟t. But what if we want to do something
else when the condition is false? Here comes the C else statement. We can use
the else statement with the if statement to execute a block of code when the condition
is false. The if-else statement consists of two blocks, one for false expression and
one for true expression.

Syntax of if else in C/C++

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
Page | 22
}

Example

#include <stdio.h>

int main()
{
int i = 20;

if (i < 15) {

printf("i is smaller than 15");


}
else {

printf("i is greater than 15");


}
return 0;
}

Output
i is greater than 15

3. Nested if-else
A nested if in C is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes, both C
and C++ allow us to nested if statements within if statements, i.e, we can place an if
statement inside another if statement.

Syntax of Nested if-else

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
Page | 23
// Executes when condition2 is false
}
}

Example

int main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}

return 0;
}

Output
i is smaller than 15

i is smaller than 12 too

4. if-else-if Ladder

The if else if statements are used when the user has to decide among multiple
options. The C if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed. if-else-if ladder is similar to the switch
statement.

Page | 24
Syntax of if-else-if Ladder

if (condition)
statement;
else if (condition)
statement;
.
.

else
statement;

Example

#include <stdio.h>

int main()
{
int i = 20;

if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}

Output
i is 20

5. switch Statement

The switch case statement is an alternative to the if else if ladder that can be used to
execute the conditional code based on the value of the variable specified in the
switch statement. The switch block consists of cases to be executed based on the
value of the switch variable.

Page | 25
Syntax of switch

switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}

Example

#include <stdio.h>

int main()
{
// variable to be used in switch statement
int var = 2;

// declaring switch cases


switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}

return 0;
}

Output
Case 2 is executed

Page | 26

You might also like