0% found this document useful (0 votes)
13 views46 pages

Module 1 - Chapter 2 - PPT

The document provides an overview of the C programming language, detailing the structure of a C program, including comment lines, preprocessor directives, global variable declarations, the main function, and user-defined functions. It explains the purpose and syntax of various components such as local variable declarations, header files, and formatted input/output functions like printf() and scanf(). Additionally, it includes examples of basic C programs demonstrating fundamental operations such as input/output, arithmetic calculations, and variable swapping.

Uploaded by

anil-csbs
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)
13 views46 pages

Module 1 - Chapter 2 - PPT

The document provides an overview of the C programming language, detailing the structure of a C program, including comment lines, preprocessor directives, global variable declarations, the main function, and user-defined functions. It explains the purpose and syntax of various components such as local variable declarations, header files, and formatted input/output functions like printf() and scanf(). Additionally, it includes examples of basic C programs demonstrating fundamental operations such as input/output, arithmetic calculations, and variable swapping.

Uploaded by

anil-csbs
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/ 46

BPOPS103/203

Principles Of Programming using C

Module 1: Chapter 2

OVERVIEW OF C

Prof.Rajeshwari R,
Assistant Professor
Dept. of CSE, CMRIT, Bangalore
Structure of C Language program

1 ) Comment line
2) Preprocessor directive
3 ) Global variable declaration
4) main function( )
{ Local variables;
Statements;
}
User defined function
}
}
Structure of C Program

1) Preprocessor directive & header file // #include<stdio.h>


2) Global variable declaration // variable that is used throughout the program, for all the
modules/blocks of the program.
3) main function
// two ways main function can be written .
void main()/ main()/int main()
{
Local variable declaration
Statements  input , processing, output
Return statement // w.r.to main function
}
4) User defined function // user only defines the steps of the function and also defines the name
of the function
5) Comment lines // to explain the meaning of the statement… syntax: //comment or
/*comment*/
Comment line: It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the program. It is useful in
explaining the program and generally used for documentation. It is enclosed
within the decimetres. Comment line can be single or multiple line but should not
be nested. It can be anywhere in the program except inside string constant &
character constant.

Preprocessor Directive: #include<stdio.h> tells the compiler to include information


about the standard input/output library. It is also used in symbolic constant such as
#define PI 3.14(value). The stdio.h (standard input output header file) contains
definition &declaration of system defined function such as printf( ), scanf( ) etc.
Generally printf() function used to display and scanf() function used to read value
Global Declaration: This is the section where variable are declared globally
so that it can be access by all the functions used in the program. And it is
generally declared outside the function.

main(): It is the user defined function and every function has one main()
function from where actually program is started and it is encloses within the pair
of curly braces. The main( ) function can be anywhere in the program , but in
general practice it is placed in the first position.

Syntax : The main( ) function return


value when it declared by data
main() type as:
{ …….. …….. ……..
} int main( )
{ return 0;
}
The main function does not return any value when void (means null/empty) is
used as return type.

void main(void ) or

void main()

printf (“C language”);

Output: C language
Example : /*First c program with return statement*/

#include <stdio.h>
int main ( )
{
printf ("welcome to c Programming language.\n");
return 0;
}

Output: welcome to c programming language


Local variable declaration
Syntax: datatype variable-name;
Example: int a; //a=10,20,30
//variable= a name given to a memory location where any value
is stored. The value can be i/por o/p.inside a variable value is
stored.
//basicdatatype:
⚫ int ( integer value) 3,4,5… size of int= 2 bytes

⚫ float( floating point ) 2.1, 3.2, 5.4… size of float= 4 bytes

⚫ char ( character) ‘a’,‘b’,‘c’,‘1’… size of char=1 byte

⚫ double ( floating point) 2.1,3.2,5.4… size of double=8


bytes
Local variable declaration & initialization
Syntax:datatype variable-name;
Example: int a; //a=10,20,30
-------------------------------------------------
int a=10; //variablea is declared& also initialized here in the same
line
(or)
int a; //variablea is declared first and initialized in next line
//
a=10;
i(notra);
printf(‘’enter value for a”);

//variable ‘a’is declared first and then asking the user to initialize
the value for ‘a’
Header Files : When we work with large projects, it is desirable to separate out
some procedures from main() function of the program. Some procedures need to
be used several times in different programs. So one solution is to copy the code of
that procedure from one program to another several times , which results in waste
of time.

So another solution is to make procedures and store them in a different file called
header files. System defined Header files contain the definitions of Library
functions like printf(), scanf(), getch() , puts(), pow(), clrscr()

Conventionally , header files ends with a ‘ . h’ extension and names can use only letters,
digits, dashes , and underscores. Header files can be system define in compiler it self or
programmers can design their own header files too.
Examples :

stdio.h : standard input & output ( functions like printf() ,scanf() are defined.)

conio.h : console input & output. ( getch(), clrscr () are defined.)

string.h : for string handling functions. ( )

math.h : Math functions like pow(), sin(), log() , sqrt() are defined.

stdlib.h : Library functions like exit (),


Formatted Input & output functions :
C language supports two formatting functions : printf () and scanf ().
printf() is used to convert text data stored in the program onto text stream for o/p to the
monitor.
scanf() is used to convert text stream coming from keyboard to data values and stores them in
program variables.

These are called as formatted Input and output functions because they have special format to
read and write The text from streams and then converting them into binary stream.

Syntax of printf() : printf ( “ control string” , var1, var2 …..var n).


Printf (“Hello welcome to C program”)
Printf ( “ %d %d %f ” , a , b , c), where a and b are integer variables and c is float variable.
%d and %f are known as format specifiers.

Syntax of scanf() : scanf ( “ Control string” , & var1, & var2, ……..,& var n).
Format specifiers : For integer variables ------ %d
For float variables -------- %f
For character variables ------- %c
Input Statements ( reading input)

scanf()
// built-in/standard /formatted input function to read input
syntax: scanf(“format specifier”, address of input variable);
//formatspecifier: int-%d, float-%f,char-%c
//& - address operator

Example: scanf(“%d”, &a);

//reading integer input whose value is stored inside variable ‘a’


Output Statement ( displaying output, displaying a message)
printf()
i) To display a message

Syntax: printf(“message”); //displaying any message

ii) To display a value

Syntax: printf(“format specifier”, name of variable holding the value);


//format specifier: int-%d, float-%f, char-%c
Example: printf(“%d”, a);
// displaying integer value which is stored inside variable ‘a’
Basic Programs

Program to Display "Hello, World!"


#include <stdio.h> Output
int main()
{ Hello, World!
printf("Hello, World!");
return 0;
}
How "Hello, World!" program works?

The #include is a preprocessor command that tells the compiler to include the
contents of stdio.h (standard input and output) file in the program.

The stdio.h file contains functions such as scanf() and printf() to take input and display
output respectively.

If you use the printf() function without writing #include <stdio.h>, the program will not
compile.

The execution of a C program starts from the main() function.

printf() is a library function to send formatted output to the screen. In this program,
printf() displays Hello, World! text on the screen.

The return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement.
Executing a C Program

In order to execute or run a C program the following steps needs


to be followed -
1. Edit the program using an editor // gedit programname.c
2. Save the program with a proper name.
3. Compile the program // cc programname.c
4. Run the program.// ./a.out
Basic Programs
1. Print Hello Message
2.C Program to Print an Integer and a character (Entered by
the User)
3. Addition of 2 Numbers
4. Multiplication of 2 Numbers
5. Find Area of Circle
6. Find Area of Rectangle
7. Find Area of square
8. Find Area of triangle
9. Calculate Simple interest
10. calculate the sum & average of five numbers
11. Swap 2 numbers-i) using third variable ii)without using
third variable
12. Program to find Quotient and Remainder
C Program to Print an Integer (Entered by the User)

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: "); //asking the user to enter input. 25

scanf("%d", &number); // reads and stores input


printf("You entered: %d", number); // displays output

return 0;
} Output

Enter an integer: 25
You entered: 25
C Program to Add Two Integers

#include <stdio.h>
int main() {
Output
int number1, number2, sum; Enter two integers: 12
printf("Enter two integers: "); 11
scanf("%d %d", &number1, &number2); 12 + 11 = 23
// calculating sum
sum = number1 + number2;
printf("%d + %d = %d", number1, number2, sum);
return 0;
}
C Program to Multiply Two Floating-Point Numbers

#include <stdio.h>
int main() {
float a, b, product;
printf("Enter two numbers: "); Output
scanf("%f %f", &a, &b); Enter two numbers:
2.4
// Calculating product 1.12
product = a * b; Product = 2.69

// %.2f displays number up to 2 decimal point


printf("Product = %.2f", product);

return 0;
}
Swap 2 Numbers Using Third Variable

#include<stdio.h>
int main()
{
int a,b,temp;
printf(“enter 2 numbers”); // a=10 b=20
scanf(“%d %d”, &a , &b); / / reading values of a and b
printf(“before swapping a= %d b=%d”, a,b); // before swapping a=10 b=20
temp=a; //c=10
a=b; // a=20
b=te mp // b=10
printf(;“after swapping a=%d b=%d”, a,b); // after swapping a=20 b=10
return 0;
}
Swap 2 Numbers without Using Third Variable

#include<stdio.h>
int main()
{
int a,b;
printf(“enter 2 numbers”); // a=10 b=20
scanf(“%d %d”, &a , &b); / / reading values of a and b
printf(“before swapping a= %d b=%d”, a,b); // before swapping a=10 b=20
a=a+b; //a=10+20=30
b=a-b; // b=30-20=10
a=a-b; // a=30-10=20
printf(“after swapping a=%d b=%d”, a,b); // after swapping a=20 b=10
return 0;
}
Swap 3 Numbers Using fourth Variable
#include<stdio.h>
int main()
{
int a,b,c, temp;
printf(“enter 3 numbers”); // a=10 b=20 c=30
scanf(“%d %d %d”, &a , &b, &c); // reading values of a ,b and c
printf(“before swapping a =%d b=%d c=%d”, a,b,c); // before swapping a=10 b=20

temp=a; //temp=10
a=b; // a=20
b=c; //b=30
c=te mp;// c=10

printf(“after swapping a=%d b=%d c=%d”, a,b,c); // after swapping a=20 b=30
c=10
return 0;
}
Swap 3 Numbers without Using fourth Variable

#include<stdio.h>
int main()
{
int a,b,c;
printf(“enter 3 numbers”); // a=10 b=20 c=30
scanf(“%d %d %d”, &a , &b, &c); // reading values of a and b
printf(“before swapping a=%d b=%d c=%d”, a,b,c);
// before swapping a=10 b=20 c=30

a=a+b+c ; //a=10+20+30=60
b=a-b-c ; // b=60-20-30=10
c=a-b-c ; // c=60-10-30 =20
a=a-b-c ; //a=60-10-20=30

printf(“after swapping a=%d b=%d c=%d”, a,b,c); // after swapping a=30 b=10 c=20
return 0;
}
Program to find Quotient and Remainder

#include<stdio.h>
int main()
{
int divisor, dividend, q, r;
printf(“enter divisor, dividend\n”); // divisor=5 dividend=23
scanf(“%d %d”, &divisor, &dividend );
q=dividend/divisor; // q=23/5=4
r=dividend% diviso r;//r=23%5=3
printf(“q=%d r=%d”, q, r);
return 0;
}
Find Area of Circle
#include<stdio.h>
int main()
{
float r, area;
printf(“enter input”);
scanf(“%f”, &r);
area=3.14*r*r;
printf(“area=%f”, area);
return 0;
}
Find Area of rectangle

#include<stdio.h>
int main()
{

float l, b, area;
printf(“enter input”);
scanf(“%f%f”, &l,&b);
area=l*b;
printf(“area=%f”, area);
}
Find Area of triangle
#include<stdio.h>
int main()
{

float b,h, area;


printf(“enter input”);
scanf(“%f%f”, &b,&h);
area=(b*h)/2;
printf(“area=%f”, area);
return 0;
}
Find sum and average of 5 numbers
#include<stdio.h>
int main()
{
float a,b,c,d,e,sum;
float avg;
printf(“enter input”);// a=1.1,b=2.0,c=1.1,d=2.0,e=1.1
scanf(“%f%f%f%f%f”, &a,&b,&c,&d,&e);
sum= a+b+c+d+e;
avg= sum/5; // a+b+c+d+e/5
printf(“sum=%f avg=%f”, sum, avg);
return 0;
}
Calculate Simple interest
#include<stdio.h>
int main()
{
float p,t,r,si;
printf(“enter input”);
scanf(“%f%f%f”, &p,&t,&r);
si=p*t*r/100;
printf(“result=%f”, si);
return 0;
}
Calculate Simple & Compound interest
#include <stdio.h>
#include <math.h>
int main( ) {
float p,r,t,si,ci;
printf("Enter principle, rate and time : ");
scanf("%f%f%f", &p, &r, &t);
/* Calculating simple interest */
si = (p * t * r)/100.0;
/* Calculating compound interest */
ci = p * (pow(1+r/100, t) - 1);
//as built-in function pow is used, <math.h> header file is written in the beginning of the
program

printf("Simple interest = %.2f\n", si);


printf("Compound interest = %.2f\n", ci);
return 0; }
In scanf() in between multiple format
specifiers we cannot use comma operator. If we
use comma operator, then after comma whichever
format specifier is mentioned for that
corresponding variable’s value will be read
wrongly.

In printf() along with message , in between


multiple format specifiers using comma operator
is allowed. The same way will be displayed in
the screen.
Example program where in scanf() in between multiple format specifiers we have used
comma operator. After comma whichever format specifier is mentioned for that
corresponding variable’s value is not read correctly, & therefore the value also not
displayed correctly ( here for b value is not read & displayed properly)
C Token
Data Types
 Basic Data Types
int

Integers are whole numbers that can have both zero, positive and negative values
but no decimal values. For example, 0, -5, 10
We can use int for declaring an integer variable.
int id=8; //valid
int id=1.8; //invalid

float and double


float and double are used to hold real numbers.
float salary=10.1;//valid
double price;
char
Keyword char is used for declaring character type variables. For example,
char test = ‘10’; // invalid
char test = ‘1’; // valid
char test = 10; // invalid
signed and unsigned

There are 2 types of qualifiers :

Sign qualifier- signed & unsigned


Size qualifier- short & long

• signed - allows for storage of both positive and negative numbers


• unsigned - allows for storage of only positive numbers

short- size of data is less / occupied memory space is less


long- size of data is more/ occupied memory space is more
signed int a=10; //valid
signed int a=-10; //valid
unsigned int a=10; //valid
unsigned int a=-10; //invalid
void

void is an incomplete type. It means "nothing" or "no type". You can


think of void as absent. For example, if a function is not returning
anything, its return type should be void.

Note that, you cannot create variables of void type.

void vname; //invalid

void function-name(); //valid


 Variable
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily


identified.

Variable Declaration:

the syntax to declare a variable:

type variable_list;

The example of declaring the variable is given below:


1. int a;
2. float b;
3. char c;
Here, a, b, c are variables. The int, float, char are the data types.
Variable Initialization/Definition

We can also provide values while declaring the variables as given


below:
1. int a=10,b=20;//declaring 2 variable of integer type
2. float f=20.8;
3. char c='A';
Rules for declaring variables
o A variable can have alphabets, digits, and underscore.
oA variable name can start with the alphabet, and underscore
only. It can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g.
int, float, for, while, do-while, if, else, etc.
o A variable is case sensitive : a, A, aA, Aa, AA, aa  all are different
variables.
o Variable cannot use special characters: Ex: %, &, #, @, $, “, : , ;
Variable Initialization/Definition Example
(or)

#include<stdio.h>
#include<stdio.h> int main()
int main() {
{ int a;
int a=10; // when variable is initialized printf(“enter value for a”); // a=50
by the programmer, without any user scanf(“%d”,&a); //when programmer
input, no need to use scanf() to read the is asking the user to enter initial value
value as the programmer only specified for a variable, we need to use scanf() to
the initial value. read that input value, as programmer is
printf(“value of a=%d”, a); // a=10 not aware of the value entered by the
return 0; user.
} printf(“value of a=%d”, a); //a=50
return 0;
}
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Types of Files

You might also like