1.12 C Language Overview

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Unit I: Part B

Overview of C Language and


C Language Preliminaries
Presented by
Dr Raghu Indrakanti
Assistant Professor
Department of ECE
Problem Solving using Computers
• Introduction
• Algorithms
• Flowcharts and Pseudo code

Overview of C Language
• Introduction
UNIT I
• Salient Features of C Language
• Structure of a C Program

C Language Preliminaries
• Keywords and Identifiers
• Constants
• Variables
• Data Types
• Input-Output Statements with suitable illustrative C Programs
Overview of C

• Introduction
• Salient Features of C Language
• Structure of a C Program

3
|<<
Introduction
Evolution of C

Year Language Developed by Remarks


1960 ALGOL International Committee Too General
Too Abstract
1963 CPL Cambridge University Hard to Learn
1967 BCPL Martin Richards Too Specific
Cambridge University
1970 B Thompson Too Specific
AT & T Bell Labs
1972 C Dennis Ritchie General Purpose
AT & T Bell Labs Structured Language

ALGOL ALGOrithmic Language


CPL Combined Programming Language
BCPL Basic Combined Programming Language
4
Salient Features of C
• Rich Set of built-in functions and operators
• Many of the C compilers are written in C
• Very Efficient and Fast
• Only 32 Keywords
• Highly Portable
• General Purpose Structured Programming Language
• Ability to Extend itself
• Free-form Language
• Suitable for System Software and Business Package Development
• Strongly Typed Language
• Capabilities of Assembly Language : with the features of High-Level Language
• Robust Language
• Allows Programmer’s Own Function Libraries
• Bitwise Manipulation
• Software Modularisation
• Supports Control Structures for Structured Programming
• Closely Associated with Unix Operating System
• Relatively Low Level Language
5
Advantages and Disadvantages of C

Advantages
• Machine Independence
• Efficient
• Data Structures
• Rich in Operators

Disadvantages
• Difficult to Debug
• Loosely Syntaxed

6
1. Set of Comments the Name of the
Program
2. Provides Instructions to the Computer to
Link System Library Functions
3. Defines all Symbolic Constants
4. Declares all Global Variables used in
No. of Functions
5. Every C Program must have one main
Function
• Declares all the Variables used in the
Executable Part
• At least one Statement

6. User Defined Functions

7
EXECUTING A ‘C’ PROGRAM

Executing a program written in C


involves a series of steps. These
are:

1. Creating the program;

2. Compiling the program;

3. Linking the program with


functions that are needed from
the C library;
8
4. Executing the program.
Standard Headers in C

The following list contains the set of standard headers :

9
Standard Headers in C
The main is a part of every C program. C permits different forms of
main statement. Following forms are
• main()
• int main()
• void main()
• main(void)
• void main(void)
• int main(void)
The empty pair of parentheses indicates that the function has no
arguments. This may be explicitly indicated by using the keyword void
inside the parentheses.
10
We may also specify the keyword int or void before the word main.

The keyword void means that the function does not return any
information to the operating system and int means that the function
returns an integer value to the operating system.
Backslash codes

11
C Language Preliminaries
• Keywords
• Simple C Programs
• Identifiers
• Variables
• Constants
• Data Types
• Input-Output (I/O) Statements
with Suitable Illustrative C Programs

12
Preliminaries of C
Learning C
Data Types
Alphabets
Constants Instructions
Digits Program
Variables
Special Symbols
Keywords
Character Set

13
Character Set
• The characters that can be used to form words, numbers and
expressions depend upon the computer on which the program is run.
However, a subset of characters is available that can be used on most
personal, micro, mini and mainframe computers.
• The characters in C are grouped into the following categories:
• Alphabets
• Digits
• Special Symbols
• Special Characters
• White Spaces

Alphabets
Uppercase
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
Lowercase
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z 14
Character Set
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters
Arithmetic Operators: + - * / %
Relational Operators: = < >
Logical Operators: ! & |
Punctuation: , . ; : ‘ “ ?
Brackets: ( ) { } [ ]
Others: ~ @ # ^ - \
White Spaces
Blank Space
Horizontal Tab
Carriage Return
New Line
Form Feed
15
C Tokens |<<

In a passage of text, individual words and punctuation marks


are called tokens. Similarly, in a C program the smallest
individual units are known as C tokens. C has six types of
tokens as given below.

17
Keywords |<<

• Every C word is classified as either a keyword or an identifier.


• All keywords have fixed meanings and these meanings cannot be
changed.
• Keywords serve as basic building blocks for program statements.

18
Example
#include <stdio.h>
int main(void)
{
int value1, value2, value3;
float sum, average;

printf("What is the first value? ");


scanf("%d", &value1);
The address of variable value1
printf("What is the second value? ");
Read scanf("%d", &value2);

Indicates that we are


reading an integer
Example

printf("What is the third value? ");


scanf("%d", &value3);
scanf needs the &
sum = value1 + value2 + value3; before the
average = sum / 3; identifier

printf("The average of %d , %d, %d is %f\n", value1, value2,


value3, average);
return(0);
}
Example 1
1. C Program to Print a Message
/* C Program to Print a Message */

#include <stdio.h>
main ( ) {
printf (“This is First C Program/n”);
}

Output:
This is First C Program

/* and */ Comments
#include Preprocessor Directive
stdio.h Standard input-output header file library function
printf Library Function to Output Sequence of Characters
\n Newline Character
; Statement Separator

21
Example 2
/* C Program to Print a Message */
#include <stdio.h>
// program prints hello world
int main() {
printf ("Hello world!");
return 0;
}

Output: Hello world!


Example 3

#include <stdio.h>
// program prints a number of type int
int main() {
int number = 4;
printf (“Number is %d”, number);
return 0;
}

Output: Number is 4

23
Example 4
#include <stdio.h>
// program reads and prints the same thing
int main() {
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %d\n”, number);
return 0;
}

Output : Enter a number: 4


Number is 4

24
|<<
Example 5
C Program to find average of three numbers.
/* C Program to find Average of three numbers */

#include <stdio.h>
main ( ) {
int a, b, c, average; /* Declaration of Variables */
printf(“Input Values of a, b, c /n”);
scanf(%d, %d, %d, &a, &b, &c);
average = (a + b + c) / 3;
printf (“Average of %d, %d, and %d = %d/n”, a, b, c, average);
}

Output:
Average of 100, 120, and 80 = 100
25
|<<
Example 6
C Program to find average of N numbers.
/* C Program to find Average of N numbers */

#include <stdio.h>
main ( ) {
int n, count, number, sum, average; /* Declaration of Variables */
printf(“Input How Many Numbers? /n”);
scanf(%d, &n);
sum = 0;
for (count =1, count <= n, count++) {
printf(“Enter number /n”);
scanf(%d, &number);
sum = sum + number;
}
average = sum / n;
printf (“Average of %d numbers = %d/n”, n, average);
} 26
|<<
Identifiers
• User Defined Names
Examples:
• Refers to
maximum
• Variables minimum
• Functions total_marks
• Arrays average_marks
• Assigns Symbolic Names .....

• Name given to Memory Location


• Denotes any Value referred to a Name
• Underscore
• Used to Improve the Readability

27
|<<
Identifiers
• Identifiers refer to the names of variables, functions and
arrays.

• These are user-defined names and consist of a sequence of


letters and digits, with a letter as a first character. Both
uppercase and lowercase letters are permitted, although
lowercase letters are commonly used.
• The underscore character is also permitted in identifiers.
• It is usually used as a link between two words in long
identifiers.
Examples:
maximum
minimum
total_marks
average_marks
.....
28
|<<
Identifiers
Rules for Identifiers

1. First character must be an alphabet (or underscore).


2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
Example:
int
this_is_a_very_long_identifier_that_definitely_should_be_rena
med = 0;
4. Cannot use a keyword.
5. Do not contain white space.
29
|<<
Example
C Program to find average of three numbers.

/* C Program to find Average of three numbers */

#include <stdio.h>
main ( ) {
int a, b, c, average; /* Declaration of Variables */
printf(“Input Values of a, b, c /n”);
scanf(%d, %d, %d, &a, &b, &c);
average = (a + b + c) / 3;
printf (“Average of %d, %d, and %d = %d/n”, a, b, c, average);
}

Output:
Average of 100, 120, and 80 = 100
30
Variables
• A variable is a data name that may be used to store a data value.
• A variable may take different values at different times during
execution.

Rules for Defining Variables

• Consists of Alphabets, Digits and only Underscore (_)


• Underscore Embedded (Connecting Words)
• May begin with an Underscore
• First Character must be an alphabet or Underscore
• It should not be a keyword.
• White space is not allowed
• Recognises up to 31 Characters (in ASCII Standard)
ASCII : American Standard Code for Information Interchange
EBCDIC : Extended Binary-Coded Decimal Interchange Code
31
Example
/*Program to Print ASCII Value*/
#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);
// %d displays the integer value of a character
// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
Example
#include<stdio.h> for (int i = 0; i <= 25; i++)
int main () {
{ printf ("%c : %d\n", b + i, b + i);
int a = 65, b = 97; }
printf ("Alphabets with their ascii return 0;
value :\n");
}
for (int i = 0; i <= 25; i++)
{
printf ("%c : %d\n", a + i, a + i);
}
What is ASCII code?
How many types of ASCII are there?
How many characters are in extended ASCII?
What is the difference between ASCII and
Unicode?
Variables

35
Variables
Declaration of Variables

General Format:
data-type variable-1, variable-2, …, variable-n;

Examples:
int x, y, z;
float a, b;
char m, n;
double p, q, r;

36
• Assigning Values to Variables
General Format
variable = constant;
x = 100, b = 12.25, m = ‘F’;

• Value assigned at the time of declaring a Variable


General Format
data-type variable = constant;
int x = 100;
float b = 12.25;
char m = ‘F’;

• Allows to initialise No. of Variables at a time using multiple


assignment operators
x = y = z = 100;
37
|<<
• Declaring a Variable as Constant
const int x = 100;

• Declaring a Variable as Volatile


Variable’s Value may be Changed at any time by Some External
sources from Outside the Program
volatile int x;

If the Value must not be modified by the Program may be


modified by Some Other Process Variable may be declared as
both const and volatile
volatile const int x = 100;

38
Constants
• Fixed Values
Not Changed during Execution of a Program
• Categories
• Numeric
• Character
• Numeric
• Represents Numbers
• Commas (,) and Blank Spaces Not Included
• Preceded by Minus (–) Sign for Negative Value
• Integers
• Decimal Integers
• Octal Integers
• Hexadecimal Integers
• Unsigned Integers
• Long Integers
39
Numeric Constants
1. Real / Floating Point
2. Decimal
3. Scientific / Exponential Notation
4. Single Character
5. String
6. Backslash Character / Escape Sequences
• Integer Constants
• Whole Number
• Sequence of Digits
• Decimal (base 10)
• Octal (base 8)
• Hexadecimal (base 16)
• Decimal Integer Constants
Combination of Digits ( 0 – 9)
Preceded by Optional – or + Sign
245 +378 –910 0 …
40
Numeric Constants
• Octal Integer Constants
Combination of Digits ( 0 – 7) with a leading Zero (0)
052 0 0666 …
• Hexadecimal Integer Constants
• Combination of Digits ( 0 – 9) and Alphabets a thru f (or A thru
F) with a leading 0x or 0X

• Alphabets a thru f (or A thru F) represent 10 thru 15 respectively


0x52 0x 0x1c02 0X9F …
• Unsigned Integer Constants
May exceed the Magnitude of Integer by 2 times
Identified by Appending by the alphabet U or u to the end
• 12345U Decimal Unsigned
• 077777u Octal Unsigned
• 0xFFFU Hexadecimal Unsigned
41
Numeric Constants
• Long Integer Constants
Identified by Appending by the alphabet L or l to the end
12345678L Decimal Long
012233L Octal Unsigned

• Unsigned Long Integer Constants


Identified by Appending by the alphabet UL or ul to the end
12345678UL Decimal Unsigned Long
0XFFFFFUL Hexadecimal Unsigned Long

42
Numeric Constants
Decimal Notation
Represented by Integer by Decimal Point and Fractional (Decimal)
Part

1. 15.25
2. .75
3. 30
4. –9.52
5. +.64
Scientific / Exponential Notation
General Format: mantissa e exponent
mantissa: Real/floating No in Decimal Notation
exponent: Integer No with Optional Sign
e e/E
1.5E–2
–2.05e2
100e+3 43
Numeric Constants
• Character Constants
Single Character Constants
String Constants
Backslash (\) Constants / Escape Sequences
• Single Character Constants
• Single Character Enclosed within a Pair of Single Quotes
• Have Integer Values
• Determined by Computer’s Character Set
• Possible to Perform Arithmetic Operations
‘9’
‘F’
‘$’
• String Constants
Group of Characters Enclosed in Double Quotes
“This is a Valid String Constant”
“B” “10+4–2” “!@#$”
44
“” “2021” “WELCOME”
Numeric Constants
• Backslash Character Constants / Escape Sequences
Certain Nonprinting Characters
Double Quote (“)
Single Quote (‘)
Question Mark (?)
Backslash (\)
Begins with Backward Slash (\)
Followed by One or More Special Characters
Character Escape Character Escape
Sequence Sequence
Bell or Alert \a Backspace \b
Form feed \f New line \n
Carriage return \r Horizontal tab \t
Vertical tab \v Single quote \’
Double quote \” Question mark \?
Backslash \\ Null \0
45
Symbolic Constants |<<
Constants used no. of places in a Program
• Defining Symbolic Constants
#define symbolic-name constant-value
#define PI 3.142
#define HUNDRED 100
• Rules for defining Symbolic Constants
• Symbolic Names Same as Variables
• No blank spaces allowed between # and define
• Starts with #
• No Semicolon at the end of #define Statement
• Symbolic name data type depends on the type of constant
• #define must be given anywhere, before referenced in the
program
• Conventionally
• Symbolic names written in Capitals to distinguish from
normal variables
• Defined in the beginning of the program 46
Example 1
#include <stdio.h>
#define PI 3.14
int main()
{

float PI = 3.0; //The value of pi is set as constant


float area, r;
printf("Enter the radius of the circle : ");
scanf("%f", &r);
area = PI * r * r;
printf("\nThe area of the circle is %f", area);

return 0;
}

47
Example 2
#include <stdio.h>

int main()
{
const float pi = 3.14; //The value of pi is set as constant
float area, r;
printf("Enter the radius of the circle : ");
scanf("%f", &r);
area = pi * r * r;
printf("\nThe area of the circle is %f", area);
return 0;
}
Example 3
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main ()
{
printf ("value of height : %d \n", height);
printf ("value of number : %f \n", number);
printf ("value of letter : %c \n", letter);
printf ("value of letter_sequence : %s \n", letter_sequence);
printf ("value of backslash_char : %c \n", backslash_char);
}

49
Example 4
#include <stdio.h>
#define pi 3.14
int main() {
float radius;
scanf("%f", &radius);
printf("The area of circle is: %f", pi * radius * radius);
return 0;
}

50
Example 5
#include<stdio.h>
int main(){
//const int a = 5;
int a = 5;
a = 25; //modifying a true constant: NOT POSSIBLE
printf("The value of a=%d",a);
}

51
Example 6
#include <stdio.h>
#define STUDENT_ID 27
//#define STUDENT_ID 207 //redefinition of a #define constant.
#define COURSE_CODE 502

int main()
{
printf("Student ID: %d is taking the class %d\n", STUDENT_ID,COURSE_CODE);

return 0;
}

52
Example 7
#include <stdio.h>

int main()
{
const int STUDENT_ID = 27;
const int COURSE_CODE = 502;
printf("Student ID: %d is taking the class %d\n", STUDENT_ID, COURSE_CODE);

return 0;
}

53
Data Types
• The type, or data type, or a variable determines a set of values that
a variable might take and a set of operations that can be applied to
those values.
• Data types can be broadly classifi ed as shown in Figure

54
Primary / Fundamental Data Types
• integer data types
int
signed int
short int
signed short int
long int
signed long int
unsigned int
unsigned short int
unsigned long int
• character data types
char
signed char
unsigned char
• floating point data types
float
double
long double 55
Data type Size Range
(bits)
char / signed char 8 –128 .. 127
unsigned char 8 0 .. 255
int / signed int 16 –32768 .. 32767
unsigned int 16 0 .. 65535
short int / signed short int 8 –128 .. 127
unsigned short int 8 0 .. 255
long int / signed long int 32 –2147483648 ..
214783647
unsigned long int 32 0 .. 4294967295
float 32 3.4E–38 .. 3.4E+38
double 64 1.7E–308 .. 1.7E+308
long double 64 3.4E–4932 .. 1.1E+4932 56
• User Defined Data Types
type definition (typedef)
enumerated data type (enum)
• Enumerated (enum) Data Type
Enumeration Constants represented by Identifiers
enum identifier {variable 1, variable 2, …, variable n};
After defining the enumerated data type,
Variables are declared as
enum identifier v 1, v2, …, vn;
enum colours {red, yellow, green, blue, white, black};
enum first_colour, last_colour;
Definition and Declaration of enumerated data type variables
can be combined as
enum colours {red, yellow, green, blue, white, black}
first_colour, last_colour;
57
|<<

• Derived Data Types


Complex Structures
Built using Standard Data Types
pointer
enumerated
union
array
structure

• Void Type / Empty Data Set


Supported by ANSI C
ANSI American National Standards Institute
Empty Set of Values
Function doesn’t return any value
Empty argument list to a function
void func (void)
58
#include <stdio.h> Example
int main() {
printf("short int is %2d bytes \n", sizeof(short int));
printf("int is %2d bytes \n", sizeof(int));
printf("int * is %2d bytes \n", sizeof(int *));
printf("long int is %2d bytes \n", sizeof(long int));
printf("long int * is %2d bytes \n", sizeof(long int *));
printf("signed int is %2d bytes \n", sizeof(signed int));
printf("unsigned int is %2d bytes \n", sizeof(unsigned int));
printf("\n");
printf("float is %2d bytes \n", sizeof(float));
printf("float * is %2d bytes \n", sizeof(float *));
printf("double is %2d bytes \n", sizeof(double));
printf("double * is %2d bytes \n", sizeof(double *));
printf("long double is %2d bytes \n", sizeof(long double));
printf("\n");
printf("signed char is %2d bytes \n", sizeof(signed char));
printf("char is %2d bytes \n", sizeof(char));
printf("char * is %2d bytes \n", sizeof(char *));
printf("unsigned char is %2d bytes \n", sizeof(unsigned char));
return 0; 59
Example
#include <stdio.h>

int main()
{
const int a = 10; //integer constant
const float b = 12.3f; // float constant
const char c = 'X'; // character constant
const char str[] = "Hello, world!"; // string constant

// printing the values


printf("a = %d\n", a);
printf("b = %f\n", b);
printf("c = %c\n", c);
printf("str = %s\n", str);

return 0;
}

60
Input / Output Statements
Input / Output Functions
Transfer of information between Computer and Standard Input
/ Output Devices
• getchar
• putchar
• gets
• puts
• scanf
• printf
stdio.h: Header file
• Accessed from anywhere within a C program
• Function Name : followed by List of arguments in Parentheses

61
• getchar (Single Character Input) Function
• To enter Single Characters
• Returns Single Character from Standard Input Device
(Keyboard)
• Doesn’t require any arguments
General Format:
character_variable = getchar ( );
character_variable Previously Declared Character Variable
Example:
char c;

c = getchar ( );

62
• putchar (Single Character Output) Function
• To Display Single Characters
• Complementary to getchar Function
• Transfers Character Variable to Standard Output Device
• Expressed as argument in parentheses to the function

General Format:
putchar (character_variable)

char c;

putchar ( );

63
Example
// including stdio.h which contains the definition of getchar() function
#include <stdio.h>
int main () {

char character; // declaring the char variable


printf("Enter the character: ");

// taking input of single character using getchar() function


character = getchar();
printf("Character entered is: ");

// printing the entered character using putchar() function used to output


the single character
putchar(character);
return(0);
}
• gets / puts Functions
Transfer of Strings : between Computer and Standard Input /
Output Devices
Accepts Single Argument
Argument: Data item representing String (Character Array)
Alternatives to scanf and printf for Reading and Displaying Strings
char line[80];
gets (line);
puts (line);

65
Example
#include<stdio.h>

int main ()
{
char str[20]; //character array
printf("Enter a String: ");
gets(str); // take input for str
//printf(str);
puts(str);
return 0;
}
Example
# include<stdio.h>
int main(){
// initializing the string
char string[] = "puts() function in C";
// writing our string to stdout
puts(string);
return 0;
}
Example
# include<stdio.h>
int main(){
// initializing the string
char string1[] = "This is the";
char string2[] = "puts() function in C";
// writing our strings to stdout
puts(string1);
puts(string2);
return 0;
}
Example
# include<stdio.h>
int main(){
// initializing the string
char string1[] = "This is the";
char string2[] = "puts() function in C";
// writing our strings to stdout
puts(string1);
puts(string2);
return 0;
}
• scanf Function
• To Enter Input Data into Computer from Standard Input / Output
Devices

• To Enter Combination of
• Numerical Values
• Single Characters
• Strings

General Format:
scanf (“control string”, arg1, arg2, …, argn);
control string Formatting Information
arg1, arg2, …, argn Individual Input Data Items

70
Scanf function:
Data Items must Correspond to the arguments in number, in type and in
order
• Octal Values Not Preceded by 0
• Hexadecimal Values Not Preceded by 0x / 0X
• Floating Point Values Decimal Point / Exponent / Both
• Data Items must be Separated by White Space Characters
• Data Items May Continue onto two or more lines
char item [25];
int partno;
float cost;

Scanf (“%s %d %f”, item, &partno, &cost);
Input: pencil 12345 1.5
or pencil
12345
1.5
or pencil
12345 1.5
or pencil 12345 71

You might also like