You are on page 1of 54

CSI 124

Structured Programming Language

Lecture 01
Introduction to C Language
What is Programming?
• Programming is writing instruction for a machine specially a
computer. It means translation of an algorithm into a programming
language
• The machine which works differently according to the instructions
given to it is called a programmable machine.
• The job of this machine is not fixed.
• We can change the working plan of the machine by changing the
instructions or programs according to our requirements.
• Programming.
What is Language?
• Instructions given to computer have a particular format.
• Computers are unable to understand human language.
• There are several levels of format or language which a computer can
understand.
▪ Low Level Language
▪ Mid Level Language
▪ High Level Language
Where does C stand?
• Problem oriented languages or High Level Language: these are
designed to give a better programming efficiency, i.e. Faster program
development eg. Fortran, Basic, Pascal
• Machine oriented languages or Low Level Language: these are
designed to give a better machine efficiency, i.e. Faster program
execution. Eg. assembly and microcontroller language
• C stands in between these two categories. That’s why it is called
Middle level language since it was designed to have both : a relatively
good programming efficiency and good machine efficiency
What is C?
• C is a programming language developed at AT &T‟s Bell Laboratories
of USA in 1972. It was designed and written by a man named Dennis
Ritchie.
• Why C is so popular?
-Readability: Programs are easy to read.
-Maintainability: Programs are easy to maintain.
-Portability: Programs are easy to port across different computer
platforms.
Simplest Program
// Prints Hello World

/* This is our
first program*/

#include <stdio.h>
void main()
{
printf("Hello World");
}
Header file
// Prints Hello World

/* This is our Includes other source code into


your program. One use is to tell
first program*/ your program about libraries you
are using. We are using the
#include statement Standard Input/Output library
#include <stdio.h> right now: stdio. The file stdio.h is
the header that defines the
void main() Standard I/O Library.
{
printf("Hello World\n");
}
Comment
A Comment is a note to yourself.
Single line comment. Programs can be cryptic and hard
// Prints Hello World to read. You need to remind
yourself what you were thinking
when you wrote something.
/* This is our That’s what comments are for.
first program*/

#include <stdio.h>
void main()
{
printf("Hello World\n");
}
Comment
// Prints Hello World A Comment is a note to yourself.
Programs can be cryptic and hard
to read. You need to remind
/* This is our Multiple line comment. yourself what you were thinking
first program*/ when you wrote something.
That’s what comments are for.

#include <stdio.h>
void main()
{
printf("Hello World\n");
}
Main Function
// Prints Hello World

/* This is our
first program*/
main() is the starting point for a C
program. It’s where the computer
#include <stdio.h> begins execution. Note the syntax:
The main function the code is contained in curly
void main() braces. ‘void’ means this function
does not return anything.
{
printf("Hello World\n");
}
printf() Function
// Prints Hello World
printf() is a library function that
/* This is our prints. It’s the main way we will
first program*/ get output from our C programs.

A printf function call


#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
printf() Function

{
printf("Hello World\n");
}
Basic structure of a C program
• Including header files
• Global declaration
• Main declaration
•{
• local declaration
• statement sequence
• other function call
•}
• User defined function
Points to Note
• Statements are terminated with semicolons
• Indentation is nice to be used for increased readability.
• Free format: white spaces and indentation is ignored by compiler
• C is case sensitive – pay attention to lower and upper case letters
when typing !
• All C keywords and standard functions are lower case
• Typing INT, Int, etc. instead of int is a compiler error
• Strings are placed in double quotes, ex: “Hello World”
• New line is represented by \n (Escape sequence)
• Tab is represented by \t
C Program Compilation Process
C character Set
• A character denotes any alphabet, digit or special symbol used to
represent information. The valid alphabets, numbers and special
symbols allowed in C.
• Alphabets A, B, ….., Y, Z a, b, ……, y, z
• Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
• Special symbols ~ „ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? /
Constants and Variables
• A constant is an entity that does not change. This can be stored at a
location in the memory of the computer.
• A variable can be considered as a name given to the location in
memory where this constant is stored. Naturally the contents of
variable can change.
e.g. 3x + 2y
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 a variable
name / identifier.
•Example:
printf, int, float, double, void, if, else, break, continue, do, while, for, const,
etc.
Keywords
Types of C Variables
• an entity that may vary during program execution is called a variable.
• Variable names/Identifiers are names given to locations in memory.

a num

• These locations can contain integer, real or character constants.


• A location in memory is very specialized. It can only hold one type of value -
integers, floating point values, or characters.
• An integer variable can hold only an integer value, a float/double variable
can hold only a fractional value and a character variable can hold only a
character.
Rules for Naming Identifiers
• Identifiers are programmer-chosen names to represent parts of the
program: variables, functions, etc.
• It is combination of alphabets, digits or underscores.
•  Identifier names can range from 1 to 31 characters.
• The first character in the identifier must be an alphabet or
underscore.
• After the first initial letter, an identifier can also contain letters and
numbers.
Rules for Constructing Variable Names
(Cont.)
• They are case sensitive. (For example- a_s and A_S are not the same)
• No commas or blanks are allowed within an identifier name.
• No special symbol other than an underscore (as in gross_sal) can be
used in an identifier name.
• Correct examples: si_int, area, pop_e_89
• Cannot match with a C keyword
Variable Declaration

• When you declare a variable, you are telling the compiler the kind of
value the variable may hold (its type)
• You cannot change the type of value a variable can hold once
declared (well, pretty much anyway)
• In fact, everything needs a type in C and it must be declared before
use!
Variable Declaration
• We must declare before use
• Every variable must be declared before it can be used (its type must be
indicated)
• Syntax:
<variable_type> <variable_name>;
Ex: int length;
length = 5;
(optional)
• Syntax:
<variable_type> <variable_name> [ =<initial_value> ];
Ex: double width = 2.5576939876984567945867587695876958;
Variable Types in Regular C
• int: an integer ex: 426, +78, -8000, -7605
▪ It must not have a decimal point.
▪ It can be either positive or negative.
▪ If no sign precedes an integer constant it is assumed to be positive.
▪ No commas or blanks are allowed within an integer value.

• float/double: fractional values


• Must have at least one digit and a decimal point.
• It can be either positive or negative.
• No commas or blanks are allowed within a float/double value.
• double has more precision than float

• char: a character, value assigned should be in single quotes


C Variable Data Types
Data Type Description Example

char Typically a single octet(one byte). char c, ch;

int The most natural size of integer for the int i, j, k;


machine.
float A single-precision floating point value. float f, salary;

double A double-precision floating point value. double d;

void Represents the absence of type. Useful for pointers in C.


Data Types in C
There are three classes of data types here:
• Primitive data types – int, float, double, char
• Aggregate OR derived data types – Arrays come under this category –
Arrays can contain collection of int or float or char or double data
• User defined data types – Structures and enum fall under this
category.
Variable Declaration and Assignment
int a;
a = 6; int a = 6;

float b;
b = 2.5; float b = 2.5;

char c;
c = ‘s’; char c = ‘s’;
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: const double PI = 3.14;
•Here, PI is a symbolic constant; its value cannot be changed.
•PI = 2.9; //Error
INPUT OUTPUT (I/O)

In C programming, printf() is one of the main output function. The


function sends formatted output to the screen. For example,
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
INPUT OUTPUT (I/O)

Integer Output: Here, we use %d format specifier to print int


types. The %d inside the quotations will be replaced by the value
of testInteger.
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
INPUT OUTPUT (I/O)

float and double Output


#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;

printf("number1 = %f\n", number1);


printf("number2 = %lf", number2);
return 0;
}
INPUT OUTPUT (I/O)

Print Characters

#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c", chr);
return 0;
}
INPUT OUTPUT (I/O)

C Input:
In C programming, scanf() is one of the commonly used function
to take input from the user.
The scanf() function reads formatted input from the standard
input such as keyboards.
INPUT OUTPUT (I/O)
Integer Input/Output
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
INPUT OUTPUT (I/O)
Float and Double Input/Output
#include <stdio.h>
int main()
{
float num1;
double num2;

printf("Enter a number: ");


scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);

printf("num1 = %f\n", num1);


printf("num2 = %lf", num2);

return 0;
}
INPUT OUTPUT (I/O)
Character I/O
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Printing Other Data Types
• We can use printf to output variables as well as strings. Put a
“descriptor/format specifier” in the string you print:

▪ Integer %d
▪ Float %f
▪ Double %lf
▪ Character %c

For declaration: int, float, double, char


Format Specifiers
• The string is followed by variable names we want to print.
• Each descriptor is replaced with a variable’s value.
Format Specifiers
• For fractional values, we can specify the precision or number of
decimal places to be printed.
Examples
• printf(“%f\n”,num);
– 3.141593
• printf(“%.4f\n”,num);
– 3.1416 (4 decimal points of precision, with rounding)
Format Specifiers
Format Specifiers
Printing Special Characters
• Double quotes - \”
• Backslash - \\
• Percentage - %%
• Slash n - \\n
C PROGRAMMING OPERATORS
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

Operator Meaning of Operator

+ addition or unary plus

subtraction or unary
- minus

* multiplication

/ division

remainder after division


% (modulo division)
C PROGRAMMING OPERATORS
Example : Arithmetic Operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, 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("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
C PROGRAMMING OPERATORS
Increment and Decrement Operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf(“a = %d \n", a++);


printf("b = %d \n", b--);
printf("c = %f \n", c++);
printf("d = %f \n", d--);

return 0;
}
C PROGRAMMING OPERATORS
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 PROGRAMMING OPERATORS
Example : Assignment Operators
#include <stdio.h> c *= a; // c is 25
int main() printf("c = %d\n", c);
{ c /= a; // c is 5
int a = 5, c; printf("c = %d\n", c);
c %= a; // c = 0
c = a; // c is 5 printf("c = %d\n", c);
printf("c = %d\n", c);
c += a; // c is 10 return 0;
printf("c = %d\n", c); }
c -= a; // c is 5
printf("c = %d\n", c);
C PROGRAMMING OPERATORS
Relational Operators
Meaning of
Operator Example
Operator

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

Greater than or equal


>= 5 >= 3 is evaluated to 1
to

<= Less than or equal to 5 <= 3 is evaluated to 0


C PROGRAMMING OPERATORS
Example 4: Relational Operators
#include <stdio.h>
int main()
{ int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
C PROGRAMMING OPERATORS
Logical Operators
Operator Meaning Example

If c = 5 and d = 2 then,
Logical AND. True only if
&& expression ((c==5) &&
all operands are true
(d>5)) equals to 0.

Logical OR. True only if If c = 5 and d = 2 then,


|| either one operand is expression ((c==5) ||
true (d>5)) equals to 1.

Logical NOT. True only if If c = 5 then, expression


!
the operand is 0 !(c==5) equals to 0.
C PROGRAMMING OPERATORS
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).
#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(c));
printf("Size of char=%lu byte\n",sizeof(d));

return 0;
}
PROBLEM
1. Write a C Program to Multiply Two Floating-Point Numbers
taken as input from user.

2. Write a C program to find diameter, circumference and area of


circle. Take radius as input.
Properties of circle
Diameter, circumference and area of a circle formula
is given by –
Links

Please Follow this Link for Codeblocks Installation:


https://www.youtube.com/watch?v=aS5_jrIbKmA

You might also like