Download presentation
Presentation is loading. Please wait.
Published byLouisa Howard Modified over 6 years ago
1
Module 1 Introduction to C language: Pre-processor directives, header files, data types and qualifiers. Operators and expressions. Data input and output, control statements.
2
Introduction to C language
C is a general-purpose programming language used for wide range of applications from Operating systems like Windows and iOS to software. C programming is highly efficient C programs are portable. The source code written in one system works in another operating system without any change.
3
History of C programming
Developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. C is a successor of B language which was introduced around the early 1970s. The language was formalized in 1988 by the American National Standard Institute (ANSI).
4
C - Program Structure A C program basically consists of the following parts − Preprocessor Commands Functions Variables Statements & Expressions Comments
5
Pre-processor Directories
Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called preprocessing. Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol. Preprocessor Syntax/Description Macro Syntax: #define This macro defines constant value and can be any of the basic data types. Header file inclusion Syntax: #include <file_name> The source code of the file “file_name” is included in the main program at the specified place.
6
Different processes of C programme
7
Header Files A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. Two types of header files: the files that the programmer writes the files that comes with compiler. To use a header file in your program by including it with the C preprocessing directive #include Example : #include<stdio.h>
8
Include Syntax #include <file> #include "file“
This form is used for system header files. It searches for a file named 'file' in a standard list of system directories #include "file“ This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file.
9
C Library Functions Under Different Header File
C Header Files <ctype.h> <locale.h> <math.h> Mathematics functions <setjmp.h> Jump functions <signal.h> Signal handling functions <stdarg.h> Variable arguments handling functions <stdio.h> Standard Input/Output functions <stdlib.h> Standard Utility functions <string.h> String handling functions <time.h> Date time functions
10
C Library Functions Library functions in C language are inbuilt functions which are grouped together and placed in a common place called library. Each library function in C performs specific operation. We can make use of these library functions to get the pre-defined output instead of writing our own code to get those outputs. All C standard library functions are declared in many header files which are saved as file_name.h. To include header files in C program using “#include<file_name.h>” command
11
stdio.h library functions
Description printf() This function is used to print the character, string, float, integer, octal and hexadecimal values onto the output screen scanf() This function is used to read a character, string, numeric data from keyboard. getc() It reads character from file gets() It reads line from keyboard getchar() It reads character from keyboard puts() It writes line to o/p screen putchar() It writes a character to screen remove() deletes a file
12
conio.h library functions
Description clrscr() This function is used to clear the output screen. getch() It reads character from keyboard getche() It reads character from keyboard and echoes to o/p screen textcolor() This function is used to change the text color textbackground() This function is used to change text background
13
string.h library functions
String functions Description strcat ( ) Concatenates str2 at the end of str1 strncat ( ) Appends a portion of string to another strcpy ( ) Copies str2 into str1 strncpy ( ) Copies given number of characters of one string to another strlen ( ) Gives the length of str1 strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2 strlwr ( ) Converts string to lowercase strupr ( ) Converts string to uppercase strrev ( ) Reverses the given string
14
math.h library functions
Description floor ( ) This function returns the nearest integer which is less than or equal to the argument passed to this function. round ( ) This function returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater than the argument. ceil ( ) This function returns nearest integer value which is greater than or equal to the argument passed to this function. sin ( ) This function is used to calculate sine value. cos ( ) This function is used to calculate cosine. exp ( ) This function is used to calculate the exponential “e” to the xth power. log ( ) This function is used to calculates natural logarithm. log10 ( ) This function is used to calculates base 10 logarithm. sqrt ( ) This function is used to find square root of the argument passed to this function. pow ( ) This is used to find the power of the given number.
15
Advantages of using C library functions
Simple and easy to use The functions are optimized for performance It saves considerable development time The functions are portable
16
C – Tokens and keywords C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual units in a C program are known as C tokens. C tokens are of six types. They are, Keywords (eg: int, while), Identifiers (eg: a, total), Constants (eg: 10, 20), Strings (eg: “total”, “hello”), Special symbols (eg: (), {}), Operators (eg: +, /,-,*)
17
Identifiers in C language:
Each program elements in a C program are given a name called identifiers. Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer variable in above program. Rules for constructing identifier name in C: First character should be an alphabet or underscore. Succeeding characters might be digits or letter. Punctuation and special characters aren’t allowed except underscore. Identifiers should not be keywords.
18
Keywords in C language Keywords are pre-defined words in a C compiler.
Each keyword is meant to perform a specific function in a C program. Since keywords are referred names for compiler, they can’t be used as variable name. Ex: int.,float,auto,const,break,if,while etc
19
First C Program #include<stdio.h> #include<conio.h> void main() { printf(“WELCOME”); getch(); }
20
Data types C data types are defined as the data storage format that a variable can store a data to perform a specific operation. Data types are used to define a variable before to use in a program. Size of variable, constant and array are determined by data types.
21
Data Types and qualifiers
Data types simply refers to the type and size of data associated with variables and functions.
22
int - Integer data types
Allows a variable to store numeric values. “int” keyword is used to refer integer data type. The storage size of int data type is 2 or 4 or 8 byte. It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2 byte (16 bit) of memory will be allocated for int data type. Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is allocated for int datatype. int (2 byte) can store values from -32,768 to +32,767 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
23
Character data type: Allows a variable to store only one character.
Storage size of character data type is 1. “char” keyword is used to refer character data type. For example, ‘A’ can be stored using char datatype. can’t store more than one character using char data type.
24
Floating point data type:
Floating point data type consists of 2 types. They are, float double
25
float: Float data type allows a variable to store decimal values. Storage size of float data type is 4. can use up-to 6 digits after decimal using float data type. For example, can be stored in a variable using float data type. double: Double data type is also same as float data type which allows up-to 10 digits after decimal. The range for double datatype is from 1E–37 to 1E+37.
26
sizeof() - sizeof() function is used to find the memory space allocated for each C data types
#include <stdio.h> #include<conio.h> void main() { int a; char b; float c; double d; printf("Storage size for int data type:%d \n",sizeof(a)); printf("Storage size for char data type:%d \n",sizeof(b)); printf("Storage size for float data type:%d \n",sizeof(c)); printf("Storage size for double data type:%d\n",sizeof(d)); getch(); }
27
Enumeration data type Enumeration data type consists of named integer constants as a list. It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list. Enum syntax in C: enum identifier [optional{ enumerator-list }]; enum month { Jan, Feb, Mar }; /* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */ enum month { Jan = 1, Feb, Mar }; /* Feb and Mar variables will be assigned to 2 and 3 respectively by default */ enum month { Jan = 20, Feb, Mar }; /* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */
28
Example #include <stdio.h> int main() {
enum MONTH { Jan = 0, Feb, Mar }; enum MONTH month = Mar; if(month == 0) printf("Value of Jan"); else if(month == 1) printf("Month is Feb"); if(month == 2) printf("Month is Mar"); }
29
Qualifiers A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whethe the value of a variable can be changed. There are two types of qualifiers const volatile
30
const keyword: values can’t be modified by the program once they are defined. They refer to fixed values. They are also called as literals. They may be belonging to any of the data type. Syntax: const data_type variable_name; Example const float pi= ;
31
volatile keyword: When a variable is defined as volatile, the program may not change the value of the variable explicitly. But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile. when any variable has qualified by volatile keyword in declaration statement then value of variable can be changed by any external device or hardware interrupt. Syntax: volatile data_type variable_name; Example : - const volatile int a=6;
32
Operators and Expressions
The symbols which are used to perform logical and mathematical operations in a C program are called C operators. These C operators join individual constants and variables to form expressions. Operators, functions, constants and variables are combined together to form expressions. Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant and A + B * 5 is an expression.
33
Types of C operators Arithmetic operators Assignment operators
Relational operators Logical operators Bit wise operators Conditional operators (ternary operators) Increment/decrement operators Special operators
34
Arithmetic_operators
Types of Operators Description Arithmetic_operators These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus Assignment_operators These are used to assign the values for the variables in C programs. Relational operators These operators are used to compare the value of two variables. Logical operators These operators are used to perform logical operations on the given two variables. Bit wise operators These operators are used to perform bit operations on given two variables. Conditional (ternary) operators Conditional operators return one value if condition is true and returns another value is condition is false. Increment/decrement operators These operators are used to either increase or decrease the value of the variable by one. Special operators &, *, sizeof( ) and ternary operators.
35
Bitwise operators ('A' holds 60 and variable 'B' holds 13)
Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12 i.e., ∣ Binary OR Operator copies a bit if it exists in either operand. (A ∣ B) = 61 i.e., ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49 i.e., ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = -61 i.e., in 2's complement form. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 = 240 i.e., >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 = 15 i.e.,
36
CONDITIONAL OR TERNARY OPERATORS IN C:
Conditional operators return one value if condition is true and returns another value is condition is false. This operator is also called as ternary operator. Syntax : (Condition? true_value: false_value); Example : (A > 100 ? 0 : 1); In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements.
37
Increment and Decrement Operator in C
Increment Operators are used to increased the value of the variable by one. Decrement Operators are used to decrease the value of the variable by one. Syntax ++ // increment operator -- // decrement operator Type of Increment Operator pre-increment post-increment
38
pre-increment (++ variable)
In pre-increment first increment the value of variable and then used inside the expression (initialize into another variable). ++ variable; #include<stdio.h> #include<conio.h> void main() { int x,i; i=10; x=++i; printf("x=: %d",x); printf("i=: %d",i); getch(); } In above program first increase the value of i and then used value of i into expression.
39
post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another variable) and then increment the value of variable. variable ++ int x,i; i=10; x=i++; printf("x: %d",x); printf("i: %d",i); In above program first used the value of i into expression then increase value of i by 1. X=10 i=11
40
Pre decrement Post decrement
41
Data input and output commonly used functions for I/O (Input/Output) are printf() and scanf(). The scanf() function reads formatted input from standard input (keyboard) The printf() function sends formatted output to the standard output (screen).
42
Entering Input Data: the scanf Function
Syntax scanf(control string, arg1, arg2, ,argN) where control string refers to a string containing certain required formatting information, and arg1,arg2,….,argN are arguments that represent the individual data items. The control string consists of the individual group of characters called format specifiers, with one character group for each input data item. Each character group must begin with a per cent sign (%) and be followed by a conversion character which indicates the type of the data item. Within the control string, multiple character groups can be contiguous, or they can be separated by whitespace characters (ie, white spaces, tabs or newline characters).
43
The most commonly used conversion characters are listed below:
Character Data type of input data c character d decimal integer e floating point value f floating point value i decimal, hexadecimal or octal integer o octal integer x hexadecimal integer s string u unsigned decimal integer
44
C Integer Input/Output int testInteger;
printf("Enter an integer: "); scanf("%d",&testInteger); printf("Number = %d",testInteger);
45
getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. The putchar() function prints the character passed to it on the screen and returns the same character. This function puts only single character at a time.
46
Example #include <stdio.h> #include <conio.h> void main( )
{ int c; printf("Enter a character"); c=getchar(); putchar(c); getch(); }
47
gets() & puts() functions
gets() : Reads characters from the standard input and stores them as a string. puts() : prints characters from the standard output.Just like printf statement. Syntax for gets() and puts() gets(char_array_variable); puts(char_array_variable/string);
48
Example char str[81]; puts("Enter a line of text:\n"); gets (str);
puts("You entered:\n") puts(str); Output Enter a line of text: Programming in C language is fun' You entered: Programming in C language is fun!
49
getch() function in C This function waits for any character input from keyboard. But, it won’t echo the input character on to the output screen. #include <stdio.h> #include<conio.h> void main() { printf("Hello World! "); getch(); } After displaying Hello World! in output screen, this program waits for any character input from keyboard. After any single character is typed/pressed, this program returns 0. But, please note that, getch() function will just wait for any keyboard input (and press ENTER). It won’t display the given input character in output screen.
50
Control statements enable us to specify the flow of program control; ie, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another. There are four types of control statements in C: Decision making statements Selection statements Iteration statements Jump statements
51
Decision Making Statement: the if-else Statement
The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test (ie, whether the outcome is true or false). if (condition) { statements } else If the condition specified in the if statement evaluates to true, the statements inside the if-block are executed and then the control gets transferred to the statement immediately after the if-block. Even if the condition is false and no else-block is present, control gets transferred to the statement immediately after the if-block.
52
If -else
53
Nested if and if-else Statements
It is also possible to embed or to nest if-else statements one within the other. Nesting is useful in situations where one of several different courses of action need to be selected. if(condition1) { // statement(s); } else if(condition2) //statement(s); . .. else if (conditionN) /statement(s); else
54
The above is also called the if-else ladder
The above is also called the if-else ladder. During the execution of a nested if-else statement, as soon as a condition is encountered which evaluates to true, the statements associated with that particular if- block will be executed and the remainder of the nested if-else statements will be bypassed. If neither of the conditions are true, either the last else-block is executed or if the else-block is absent, the control gets transferred to the next instruction present immediately after the else-if ladder.
55
while loop in C A while loop in C programming repeatedly executes a target statement as long as a given condition is true. while(condition) { Statemets; } statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
57
Do -while The body of do...while loop is executed once, before checking the test expression. Hence, the do...while loop is executed at least once. do { // codes } while (testExpression); The code block (loop body) inside the braces is executed once. Then the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false). When the test expression is false (nonzero), the do...while loop is terminated
59
switch statement Allows a variable to be tested for equality against a list of values. Each value is called a case The variable being switched on is checked for each switch case. switch (n) { case constant1: // code to be executed if n is equal to constant1; break; case constant2: // code to be executed if n is equal to constant2; . default: // code to be executed if n doesn't match any constant }
60
When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case. suppose the value of n is equal to constant2. The compiler will execute the block of code associate with the case statement until the end of switch block, or until the break statement is encountered. The break statement is used to prevent the code running into the next case.
62
#include <stdio.h> int main () { char grade = 'B'; switch(grade) case 'A' : printf("Excellent!\n" ); break; case 'B' : case 'C' : printf("Well done\n" ); case 'D' : printf("You passed\n" ); case 'F' : printf("Better try again\n" ); default : printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0;
63
Example 2 int main() { int num=2; switch(num+2) case 1: printf("Case1: Value is: %d", num); case 2: case 3: default: printf("Default: Value is: %d", num); } return 0;
64
For loop Allows a code to execute a specific number of times.
for ( init; condition; increment ) { statement(s); } Where The init - declare and initialize any loop control variables condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. increment - to update any loop control variables.
66
Example #include <stdio.h> int main () { int a;
for( a = 10; a < 20; a = a + 1 ){ printf("value of a: %d\n", a); } return 0;
67
nested for loop for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); }
69
void main() { int i,j,k=1,r; clrscr(); printf("enter the no:"); scanf("%d",&r); for(i=0;i<=r;i++ for(j=1;j<=i;j++) printf("%d\t",k); k++; } printf("\n"); getch();
71
Generate pattern
72
Jump statements used to interrupt the normal flow of program.
Types of Jump Statements Break Continue goto
73
Break Statement used inside loop or switch statement.
When compiler finds the break statement inside a loop, compiler will abort the loop and continue to execute statements followed by loop.
74
#include<stdio.h> void main() { int a=1; while(a<=10) if(a==5) break; printf("\nStatement %d.",a); a++; } printf("\nEnd of Program.");
75
Continue Statement The continue statement is also used inside loop.
When compiler finds the break statement inside a loop, compiler will skip all the followling statements in the loop and resume the loop.
76
#include<stdio.h> void main() { int a=0; while(a<10) a++; if(a==5) continue; printf("\nStatement %d.",a); } printf("\nEnd of Program.");
77
Goto Statement The goto statement is a jump statement which jumps from one point to another point within a function. Syntax goto label; label: Where , label is an identifier. When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code after it.
79
#include<stdio.h>
void main() { printf("\nStatement 1."); printf("\nStatement 2."); printf("\nStatement 3."); goto last; printf("\nStatement 4."); printf("\nStatement 5."); last: printf("\nEnd of Program."); }
80
Additional Programs * * * * * * * * * * * * * * *
81
#include <stdio.h> int main() { int i, j, rows; printf("Enter number of rows: "); scanf("%d",&rows); for(i=1; i<=rows; ++i) { for(j=1; j<=i; ++j) printf("* "); } printf("\n"); return 0;
82
Que 2
83
#include <stdio.h>
int main() { int i, j, rows; printf("Enter number of rows: "); scanf("%d",&rows); for(i=1; i<=rows; ++i) { for(j=1; j<=i; ++j) printf("%d ",j); } printf("\n"); return 0;
84
Que * * * * * * * * * * * * * * *
85
* * * * * * * * * * * * * * * * * * * * * * * * *
86
#include <stdio.h> int main() { int row, c, n, temp; printf("Enter the number of rows in pyramid of stars you wish to see "); scanf("%d",&n); temp = n; for ( row = 1 ; row <= n ; row++ ) for ( c = 1 ; c < temp ; c++ ) printf(" "); temp--; for ( c = 1 ; c <= 2*row - 1 ; c++ ) printf("*"); printf("\n"); } return 0;
87
Pascals Triangle 1 1 1
88
Floyds Triangle
89
#include <stdio.h> int main() { int n, i, c, a = 1; printf("Enter the number of rows of Floyd's triangle to print\n"); scanf("%d", &n); for (i = 1; i <= n; i++) for (c = 1; c <= i; c++) printf("%d ",a); a++; } printf("\n"); return 0;
90
C – Tokens and keywords C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual units in a C program are known as C tokens. C tokens are of six types. They are, Keywords (eg: int, while), Identifiers (eg: a, total), Constants (eg: 10, 20), Strings (eg: “total”, “hello”), Special symbols (eg: (), {}), Operators (eg: +, /,-,*)
91
Identifiers in C language:
Each program elements in a C program are given a name called identifiers. Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer variable in above program. Rules for constructing identifier name in C: First character should be an alphabet or underscore. Succeeding characters might be digits or letter. Punctuation and special characters aren’t allowed except underscore. Identifiers should not be keywords.
92
Keywords in C language Keywords are pre-defined words in a C compiler.
Each keyword is meant to perform a specific function in a C program. Since keywords are referred names for compiler, they can’t be used as variable name. Ex: int.,float,auto,const,break,if,while etc
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.