100% found this document useful (1 vote)
17 views41 pages

C Basics

Uploaded by

Sarthak Gupta
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
100% found this document useful (1 vote)
17 views41 pages

C Basics

Uploaded by

Sarthak Gupta
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
You are on page 1/ 41

Introduction to

C Programming Language
Language?
 Source of Communication between two persons.
 Example: Human –To- Human
OR
 Source of Communication between User and
Computer is called programming language.
 Example: Human –To- Machine

2
Program

Set of instructions which perform any specific


task is called program.

3
What is programming?
 Series of instructions to a computer to achieve a task

 Instructions must be written in a way the computer can


understand

 Programming languages are used to write programs

 Once the code (language) of a program has been written, it


must be executed (run, started).

 Some programming languages (like C, C++ or Java) require the


code to be compiled (translated to binary) before it can be
started.
4
History of C language

Year Language Developer


ALGOL
1960 Internal Committee
(Algorithmic Language)
BCPL
1967 Martin Richards
(Basic Combined Programming Language)

1970 B Ken Thompson

1972 C Dennis Ritchie

5
What is C?
C
A language written by Dennis
Ritchie in 1972 at AT&T Bell Labs
USA. This was to be the language
that UNIX was written in to become
the first "portable" language.

In recent years C has been used as a general-purpose


language because of its popularity with
programmers.

AT&T-American Telephone and Telegraph

UNIX-Uniplexed Information and Computing System or Service 6


Why C Still Useful?
 C provides:
Efficiency, high performance and high quality
Provide functionality through rich set of function libraries
Gateway for other professional languages like C → C++ → Java

 C is used:
System software, Compilers, Editors
Graphics and Geometry
Databases, operating systems, device drivers
Also used in application programs

7
Software Development Method
 Requirement Specification
 Problem Definition
 Analysis
 Refine, Generalize the problem definition
 Design
 Develop Algorithm: (A formula or set of steps for solving a
particular problem)
 Implementation
 Write Code
 Verification and Testing
 Test and Debug the code

8
How do you write a program?
 Decide what steps are needed to complete the task

 Write the steps (Algorithm) in pseudo code (written in English) or as a flowchart


(graphic symbols)

 Translate into the programming language

 Try out the program and “debug”.

9
Getting started with C
 Steps in learning English language

Alphabets Words Sentences Paragraph

 Steps in learning C
Constants
Alphabets Instruction Program
Variables
Digits
Keywords
Special-symbols

10
Sample Pseudo code
 Task: add two numbers
 Pseudo code (Algorithm) :

1. Start
2. Get two numbers
3. Add them (a + b)
4. Print the answer
5. End

11
What does a flowchart look like?
 Pseudo code Start
(Algorithm) :
Get 2 numbers
1. Start
2. Get two numbers
A+B
3. Add them (A + B)
4. Print the answer
5. End
Print answer

End

12
Integrated Development Environments
 An integrated development environment (IDE) is a software package
that makes it possible to edit, compile, link, execute, and debug a program
without leaving the environment.

13
13
Program Development in C
Header Files
The files that are specified in the include section is called
as header file
These are precompiled files that has some functions
defined in them
We can call those functions in our program by supplying
parameters
Header file is given an extension .h
C Source file is given an extension .c

15
Main Function
This is the entry point of a program
When a file is executed, the start point is the main function
From main function the flow goes as per the programmers choice.
There may or may not be other functions written by user in a program
Main function is compulsory for any c program

16
Simple C Program
/* A first C Program*/

#include <stdio.h>

void main(void)

{
printf("Hello World");

17
Simple C Program
/* A first C Program*/

#include <stdio.h> Header File

Preprocessor directive
void main() Main Function

{ Opening bracket

printf("Hello World"); Statement Part

} Closing Bracket

18
Simple C Program
 Line 1: #include <stdio.h>

 As part of compilation, the C compiler runs a program called the


C preprocessor. The preprocessor is able to add and remove
code from your source file.
 In this case, the directive #include tells the preprocessor to
include code from the file stdio.h.
 This file contains declarations for functions that the program
needs to use. A declaration for the printf function is in this file.

19
Simple C Program
 Line 2: void main(void)

 This statement declares the main function.


 A C program can contain many functions but must always have
one main function.
 A function is a self-contained module of code that can finish
some task.
 The "void" specifies the return type of main. In this case, nothing
is returned to the operating system.

20
Simple C Program
 Line 3: {

 This opening bracket denotes the start of the program.

21
Simple C Program
 Line 4: printf("Hello World ");

 Printf is a function from a standard C library that is used to


print strings to the standard output, normally your screen.
 The compiler links code from these standard libraries to the code
you have written to produce the final executable.
 If there were another printf in this program, its string would
print on the next line.

22
Simple C Program
 Line 5: }
 This closing bracket denotes the end of the program.

23
Running C Program
Type a program
Save it
Compile the program – This will generate an exe file
(executable)
Run the program (Actually the exe created out of
compilation will run and not the .c file)
In different compiler we have different option for compiling
and running. We give only the concepts.

24
Comment
Single line comment
// (double slash)
– Termination of comment is by pressing enter key
Multi line comment
/*….
…….*/
It is used to increase the readability of the program.
Any number of comments can be given at any place in the program.
Comment cannot be nested
example:
/* A first C Program*/

25
Data Types
Data types specify how we enter data into our programs and what type of data we enter.
C language has some predefined set of data types to handle various kinds of data that we
use in our program. These datatypes have different storage capacities.
Basic data types are listed below:
Type Size(bytes) Range Control String/
format specifier
char or signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
int or signed int 2 -32,768 to 32767 %i or %d
unsigned int 2 0 to 65535 %u
short int or signed short int 1 -128 to 127 %d
long int or signed long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
float 4 3.4E-38 to 3.4E+38 %f or %g
double 8 1.7E-308 to 1.7E+308 %lf
long double 10 3.4E-4932 to 1.1E+4932 %lf
void
void type means no value. This is usually used to specify the type of functions. We will learn it later
Note: C program takes 64 Kb memory in RAM on 16 - bit Compiler

26
The C character Set

A character denotes any alphabet, digit or special symbol


used to represent information.

Alphabets A,B, …. ,Y, Z


a,b, ….. ,y, z

Digits 0,1,2,3,4,5,6,7,8,9

Special Symbols ~‘!@#%^&*( )_-+=


|\{}[] :;“‘< > , .? /

27
Constants, Variable and keywords
 The alphabets, numbers and special symbol when properly

combined form constants, variables and keywords

 A constant is a quantity that doesn’t change

 A variable is a name given to the location in memory where

the constant is stored


 Example: 3x + y = 20

3 & 20 are constants, which cannot change

x & y can vary or change hence are called variables

28
Constants
Any information is Constant
Data = Constant = Information
 Primary
 Integer (2, -34 , 0)
 Real (3.4 , 0.06 )
 Character ( Single quote, length one)
 Secondary (Secondary constant made with the help of
primary constant)
 Array
 String ( e.g “Rahul” )
 Pointer
 Union
 Structure
 Enumerator
 Class
Variable
A variable is a name that may be used to store a data value. Unlike constant, variables
are changeable, we can change value of a variable during execution of a program. A
programmer can choose a meaningful variable name. Example : average, height, age,
total etc.

Rules to define variable name

➢Variable name must not start with a digit.


➢Variable name can consist of alphabets, digits and special symbols like
underscore _.
➢Blank or spaces are not allowed in variable name.
➢Keywords are not allowed as variable name.
➢The Variable names may be a combination of uppercase and lowercase
characters . Ex: suM and sum are not the same
Declaration Different Types of Variable
The declaration of variables should be done in the declaration part of the program. The variables
must be declared before they are used in the program.

Declaration provides two things


1. Compiler obtains the variable name
2. It tells to the compiler data types of the variable being declared and helps in allocating the
memory.

The syntax of declaring a variable is as follows.

Syntax : Data_type variable_name


Example :
int age;
char m;
float s;
double k;
int a,b,c;

The int, char, float and double are the keywords to represent data types. Commas separate the
variables, in case variables are more than one.
Keywords
Keywords are the words whose meaning has already been explained
to the C compiler
Sometimes called reserved words.
They cannot be used as variable names.
There are only 32 keywords available in c

auto double if static do


break else int struct goto
case enum long switch signed
char extern near typedef while
const float register union default
continue far return unsigned for
short void
32
IDENTIFIER
 Identifiers are the names you can give to entities such as
variables, functions, array ,structures etc.
 Also remember, identifier names must be different from
keywords.You cannot use int as an identifier because int is a
keyword.
 Ex:
 int money;
 double accountBalance;
 Identifier is like a word
 Instruction is like a sentence
Escape Sequence
Many programming languages support a concept called Escape Sequence.
When a character is preceded by a backslash (\), it is called an escape
sequence and it has a special meaning to the compiler. For example, \n
in the following statement is a valid character and it is called a new line
character −

 \n new line
 \t tab
 \a alert
 \\ backslash
 \” double quote
 \0 Null
 \b Backspace

34
Escape Sequence
Escape Description
Sequence
\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
use \r to move to the start of the line and overwrite the existing text.
\f Inserts a form feed in the text at this point.
\f is used for page break. You cannot see any effect in the console. But
when you use this character constant in your file then you can see the
difference. (in cmd abc > xyz.doc)
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.
Delimiters
Language pattern of C uses special kind of symbols, which
are called as delimiters. They are given as under.
Delimiters Symbols Use
Colon : Useful for label
Semicolon ; Terminates statements
Parenthesis () Used in Expression and function
Square brackets [] Used for array declaration
Curly braces {} Scope of statement
Hash # Preprocessor directive
Comma , Variable seperator
Null Character \0 In end of string
Operator and Expressions

Operators, functions, value and variables are combined together to


form expressions.

Consider the expression A + B * 5. where, +, * are operators, A, B are


variables, 5 is value and A + B * 5 is an EXPRESSION.

The symbols which are used to perform logical and mathematical


operations in a C program are called C OPERATORS.
Operators in C

Types of Operator Symbolic Representation

Arithmetic operators + , - , * , /, %
Relational operators > , < , = = , >= , <= , !=
Logical operators && , ||
Increment and Decrement operator ++ , --
Assignment Operator =, +=, -=, *=, /=, %=
Bitwise operators & , | , ^ , >> , << and ~
Comma operator ,
Condition operator ?:
Sizeof operator
Operators in C
 Unary operators
Increment and decrement operator
Assignment operator
Sizeof operator
 Binary operators
Arithmetic operators
Relational operators
Logical operators
 Ternary operators
Condition operator
Operator precedence
Precedence Operator Description Associativity
++ -- Suffix/postfix increment and decrement Left-to-right
() Function call
[] Array subscripting
1
. Structure and union member access
Structure and union member access through
->
pointer
++ -- Prefix increment and decrement Right-to-left
+- Unary plus and minus
!~ Logical NOT and bitwise NOT
2 (type) Cast
* Indirection (dereference)
& Address-of
sizeof Size-of
Operator precedence
Precedence Operator Description Associativity
3 */% Multiplication, division, and remainder Left-to-right
4 +- Addition and subtraction
5 << >> Bitwise left shift and right shift
< <= For relational operators < and ≤ respectively
6
> >= For relational operators > and ≥ respectively
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)
11 && Logical AND
12 || Logical OR
13 ?: Ternary conditional Right-to-left
= Simple assignment
+= -= Assignment by sum and difference
14 *= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
15 , Comma Left-to-right

You might also like