C-C - Programming
C-C - Programming
What is Programming?
"A program is a precise sequence of steps to solve a particular problem.”
OR
These instructions are considered computer programs and help the computer to operate
smoothly.
Programming Language:
As we know that language is a way of communication so with the help of computer
programming language we can communicate with the computer to solve our problem.
What is C/C++:
C/C++ is one of the most powerful, flexible, efficient, modular, general purpose high level
programming language.
It is a versatile language. You can use C/C++ for almost any programming task. It is effective
to develop high level application programs in various fields, such as engineering, business,
science, education, statistics, accounting, database management etc.
History of C/C++:
The C language was developed in late 60’s and early 70’s, in Bell Laboratories. In those days
BCPL(Basic Combined Programming Language) and B languages were developed there. The
BCPL language was developed in 1967 by Martin Richards as a language for writing
operating systems software and compilers. In 1970 Ken Thompson used B language to
create early versions of UNIX operating system.
C was developed by Dennis Ritchie in 1970 at Bell Laboratories while C++ was developed by
Bjarne Stroustrup in early 1980s at Bell Laboratories.
Its purpose was to make the programming process easier and pleasant for the individual
programmer.
High-level computer languages use formats that are similar to English. The purpose of
developing high-level languages was to enable people to write programs easily, in their own
native language environment (English).
High-level languages are basically symbolic languages that use English words and/or
mathematical symbols rather than codes. Each instruction in the high-level language is
translated into many machine language instructions that the computer can understand.
Assembly Language:
Assembly language was advance than machine language. This language some symbolic
codes were used instead of 0’s and 1’s. it was easy to use and understand as compare to
machine language.
These alphanumeric symbols are known as mnemonic codes and can combine in a
maximum of five-letter combinations e.g. ADD for addition, SUB for subtraction, START,
LABEL etc. Because of this feature, assembly language is also known as ‘Symbolic
Programming Language.
Translation Software:
It is application software that is used to convert source code into object code and vice
versa.
Interpreter:
It is translation software that is used to convert a program written in high level language
into the machine language and vice versa. It takes our program as input and translates it
line by line into object code.
Compiler:
It is translation software that is used to convert a program written in high level language
into the machine language and vice versa. It takes our entire program as input and
translates the whole program into object code.
In the same way, C/C++ program is constructed from some material that is discussed below.
Alphabetic characters are upper and lower case letter of the English language (A, B, C
……….Z, a, b, c ………….z).
The special character is period (.). comma, Semicolon(;), Single & double quotes (‘&”). Plus
& Minus sign (+& -). Asterisk (*), Slash (/), Equal Sign (=), Parentheses (), Percent (%), Less
and Greater Sign (< >), Hash or number sign (#), Ampersand (&), Question Mark (?),
Opening and closing braces ({ }), and other special character including the blank character
which is equivalent to a space on the keyboard.
Any character or series of characters that produce horizontal or vertical space is called
whitespace character. Whitespace characters include spacebar, tab (\t), Enter, newline (\n).
C/C++ RESERVED WORD:
Words that have pre-defined meanings in C Language are called reserve words. They
cannot be re-defined by the user inside his program. They must be spelled correctly and
entered in lowercase. Example of reserve words are int, long, float, char, if, else, do, while,
switch, for etc.
Words that are defined or provided by the user inside his program are called user defined
words or identifiers.
During programming programmer needs to store some data to perform some operation on
it so some name must be associated with that data to access it when it is needed.
Both upper and lowercase letters are allowed in identifier names, but case sensitivity
should be taken care of their. For example TaX, tax. taX, TAX are four different identifiers.
The first character of identifier name must be an alphabet or underscore. After alphabet or
underscore you can use numbers and additional alphabets, underscore as well.
Z = 5; Z = 5
The above example, Z is a variable, which hold a value 5. It is important to note that the
value of a variable may change from time to time during the execution of program, but the
name remains the same.
If we say
Z = Z + 5;
Each variable has a name, a type and a value that you assign to it. A variable name must be
unique in a program.
Variable name should be meaningful that imparts some meaning. Meaningful variable’s
names tell you what those variables are for and make it easier to understand the flow of
your program.
DATA TYPES:
Data type actually tells the compiler about the type of the data that you are going to store
into memory location.
Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory.
The following table shows a list of variable types and range that each variable might hold.
It is important to note that the size and ranges are not fixed; as it varies from machine to
machine.
1. NUMERIC CONSTANT
Numeric values that remain fix during the program execution, are called Numeric constant.
These values consist of digits (0 to 9), plus (+) or minus (-) sign and decimal point (.).
Numeric constants are further divided into three sub types.
a) Integer constants: This type of constants consist of only digits (0 to 9) and sign (+ or -
). These constants represent whole values. Example; 15, 576, +420, -750 etc.
b) Floating Point Constants: Floating point constants consist of digits (0 – 9), sing (+ or -)
and decimal point(.). These constants represent fractional values. Examples; 5.7,
25.5, +235.45, -67.3, 0.123 etc.
c) Exponential Real Constants: If floating point constants are represented in the form of
exponential notations, then called as Exponential real constants. These type of
constants are used to represent very large or small numbers. Example; 5.234E+6,
8.0E+9, 9.5E-10 etc.
2. NON-NUMERIC CONSTANTS:
Constants that are not numeric are called No-numeric constants. This type of constants
is divided into two types.
a) Character Constants: A single character constant is called character constant. This type
of constant is enclosed in a single quote. Example; ‘n’, ‘#’, ‘5’, ‘=’, ‘y’ etc.
A Variable is the name of identifier whose value changes during the program execution
while constant is an identifier whose value remains fixed during the program execution.
A constant is must initialized when it is declared while variable is not required to be
initialized during its declaration.
Variable syntax is
data-type variable-name = value;
E.g int number = 50;
Constant syntax is
const data-type constant-name = value;
E.g const float pi = 3.14159;
Example:
Operators that are used to compare two variables or values, are called relational operators.
They form relational expressions whose result can be either true or false. C/C++ support the
following types of relational operators. >, <, >=, <=, ==, !=
Logical Operator:
Operators that are used to combine two or more relational expressions are called logical
operators. The result of these operators will either be true or false. C/C++ supports the
following types of logical operators.
Unary Operator is an operator that operates on single operand to produce a new value.
C/C++ supports two unary operators i.e.
The increment operator causes its operand to be increased by 1, while decrement operator
causes its operand to be decreased by 1. Both the operators may be used with the single
variable as a prefix or postfix.
++ i=1 i ++ 2
-- i=2 i- - 1
while
Statement is an instruction for a computer to cause some action. All expressions may be
valid C/C++ statements, while all statements are not expression. For example got top; or
continue; if , else, switch, is a statement but not an expression.
# Include
It is called Pre-processor directive. It tells the compiler to inset header files into our source
code before the process of compilation.
main ( ) Function
main ( ) is a C or C++ language function. It is the compulsory part of the C or C++ program. It
is the first executable function.
Body of program:
{
Here we can write our code
}
} }
Printf() Function:
Where format string is a message enclosed in double quotes. It may contain escape
sequence characters or/and format specifier. The format specifiers for integer data are %d,
for float data is %f and for character data is %c etc.
cout<< Function:
cout stands for console output. It is a standard output stream use to display output on the
standard device like monitor. It is used with the combination of stream insertion operator
(<<). This stream object is capable to display messages, values, and value of variables or
expression on screen.
cout<<string/variable/constant/expression;
The header file <conio.h> is required to be included in the program for the putch() function.
Example:
char ch;
ch=getche();
putch(ch);
The putchar() is also an output function use to write a single character to the screen.
putchar(character/character_ variable)
INPUT STATEMENTS:
scanf () function:
Its function is to read values for variables from keyboard during program execution.
General syntax is
scanf(“control string”,var1,&var2,….);
Example:
scanf(“%d”,&n);
The getch() function is used to read a single character from keyboard during program
execution without echoing it on screen. There is no need to press the whitespace character
e.g. enter key etc.
getche():
The getche() function is used to input a single character form keyboard during program
execution and also echoes the character on screen. There is also no need to press the
whitespace character e.g. enter key etc.
getchar():
The getchar() function is also used to read a single character from keyboard at run time and
echoes it on screen but after that you need to press enter key.
gets():
This function is used to read an entire string until you press enter key.
Syntax : gets(variable);
cin>> Functiont:
cin stands for console input. It is a standard input stream use to receive input from the
standard input device like keyboard.
This stream object is capable to read values for various kinds of variables from keyboard
during program execution.
General syntax is
cin>>var-1>>var-2>>…..>>var-n;
Write a Program in C to add any two Write a Program in C++ to add any two integer
integer numbers and display the results. numbers and display the results.
#include<stdio.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int num1,num2,sum; int num1,num2,sum;
clrscr( ); clrscr( );
num1=250; num1=250;
num2=135; num2=135;
sum=x+y; sum=x+y;
printf(“Result=%d”,sum); cout<<”Result = ”<<sum<<endl;
getch ( ); getch ( );
} }
Write a Program in C that inputs two Write a Program in C++ that inputs two
numbers at run time, and finds the sum & numbers at run time, and finds the sum &
difference. difference.
#include<stdio.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main()
{
clrscr();
char Name[20];
int Roll_No,Eng,Urdu,Maths,Computer,Obtain_Marks,Total_Marks=400;
float Percentage;
cout<<"ENTER YOUR NAME : "<<endl;
cin>>Name;
cout<<"ENTER YOUR ROLL NO : "<<endl;
cin>>Roll_No;
cout<<"ENTER YOUR ENG MARKS : "<<endl;
cin>>Eng;
cout<<"ENTER YOUR URDU MARKS : "<<endl;
cin>>Urdu;
cout<<"ENTER YOUR MATHS MARKS : "<<endl;
cin>>Maths;
cout<<"ENTER YOUR COMP MARKS : "<<endl;
cin>>Computer;
Obtain_Marks=Eng+Urdu+Maths+Computer;
Percentage=(float)Obtain_Marks*100/Total_Marks;
clrscr();
cout<<"Your Name is "<<Name<<endl;
cout<<"Your Roll No is "<<Roll_No<<endl;
cout<<"YOUR OBTAIN MARKS ARE: "<<Obtain_Marks<<endl;
cout<<"YOUR PERCENTAGE IS: "<<Percentage<<endl;
getch();
}
if statement:
if statement is used to execute a statement or group of statement on the basis of some
condition. If the given condition is true, then the statement in its body is executed,
otherwise not.
General syntax of if
if (condition)
{
Statement(s);
}
if-else statement:
if else statement is used to execute a statement or group of statement on the basis of some
condition. If the given condition is true, then the statement in its body of if is executed, and
if the condition is false then the body of else will execute.
This statement lets us to pick out one choice of statement between two on the basis of a
same condition.
If the given condition is true, then the statements after if clause will execute and
statements after else will skip. But if the condition false, then statements after else will
execute only.
Write a program to check whether the two numbers Write a program to find the Largest number between
are equal or not? two numbers?
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
clrscr(); clrscr();
int number1,number2; int number1,number2;
cout<<"Enter First Number="; cout<<"Enter First Number=";
cin>>number1; cin>>number1;
cout<<"Enter Second Number="; cout<<"Enter Second Number=";
cin>>number2; cin>>number2;
if(number1==number2); if(number1>number2);
{ {
cout<<"Numbers are Equal"; cout<<"Largest Number is "<<number1;
} }
else else
{ {
cout<<"Numbers are not Equal"; cout<<"Largest Number is"<<number2;
} }
getch(); getch();
} }
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1,num2,num3,max;
cout<<"Enter your first number=";
cin>>num1;
cout<<"Enter your second number=";
cin>>num2;
cout<<"Enter your Third Number=";
cin>>num3;
if(num1>num2)
{
max=num1;
}
else
{
max=num2;
}
if(num3>max)
{
max=num3;
}
cout<<"Maximum number is="<<max;
getch();
}
Else if statements:
If & else statements are used when we have to make decisions between two choices but
when we have multiple choices then we use else if statement.
Syntax:
if (condition)
else if (condition)
By using else if statement we can have multiple choices.
{
else if (condition)
else
When an if-statement is embedded (included) inside the body of another if, then it is called
as nested-if statements.
Syntax:
If (condition)
{
If (condition)
{
statement.
}
else
{
}
}
else
{
statement.
#include<iostream.h>
#include<conio.h>
void main()
{
Int marks;
clrscr();
cout<<”enter your marks”;
cin>>marks;
If (marks>=30)
{
If (marks>=50)
{
cout<<”Good;
}
else
{
cout<<”Average;
}
}
else
{
cout<<”Poor”;
}
getch();
}
The switch statement is a special form of multiple-alternative decision making i.e when
multiple choice possibilities are based on a single value.
Syntax:
switch(expression)
{
case value-1: statement;
break;
default: statement;
}
Break in switch statement is used to exit the switch and transfer the control to the next
statement outside the switch body.
getch();
}
One of the main features of programming is looping because in many situations some operations
are performed over and over again.
A loop is used for the purpose of repetitive task when we have to execute same type of
statement again & again we use loops.
Counter or Determined Loop is used in that case when the precise number of repetition is
known in advance.
For Loop:
For loop is used to execute a statement or group of statement for the specified number of times.
This is called a determined loop, because this loop is preferred to use when we know in advance
that how many times the loop will execute.
In initialization, the control variable is given the initial value and this variable will control the
loop.
In condition, the control variable is compared with some limit value to check whether the loop is
continued or not? If it is true, then loop is continued, otherwise not.
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
#include<iostream.h>
#include<conio.h> #include<iostream.h>
#include<conio.h>
void main()
{ void main()
clrscr(); {
int i; clrscr();
for (i=10;i>=1;i--) int i;
{ for (i=0;i<=20;i=i+2)
cout<<i<<endl; {
} cout<<i<<endl;
getch(); }
} getch();
}
Write a program to display even numbers in Write a program to print ODD numbers from 1 to
descending order from 100 to 0. upto 25 on screen?
#include<iostream.h>
#include<iostream.h>
#include<conio.h> #include<conio.h>
While loop is used to execute a single or multiple statements repeatedly until a specified
condition is true. This is called a pre-condition loop because in this loop, the condition is
first evaluated and then it is decided whether the body of loop is executed or not. While
loop is used when the number of repetition is not known in advance.
while (condition)
{
statements;
}
The given condition is first evaluated, if it is true then the body of loop will execute,
otherwise not.
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
ch = 'y';
while(ch=='y')
{
cout<<"PAKISTAN"<<endl;
cout<<"Are you want to continue [y/n]"<<endl;
cin>>ch;
}
getch();
}
The program written above will continuously print the word PAKISTAN until user presses y.
In this situation it is not known in advance that how many times the user will press ‘y’ key to
continue the process.
Do while loop is used to execute a statement of group of statements repeatedly until a given
condition is true.
This is called post condition loop because in this loop, the body of loop will first execute and then
the condition is evaluated at the end.
If the condition is true, the execution of loop will continue, otherwise not, but even after condition
being false the loop will execute once.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
do
{
statements;
}
while (condtion);
#include <iostream.h>
#include<conio.h>
void main () {
int a = 10;
do {
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 10 );
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int number, i, tab;
cout<<"Enter Number for Table "<<endl;
cin>>number;
for(i=1;i<=10;i++)
{
tab = number*i;
cout<<number<<"*"<<i<<"="<<tab<<endl;
}
getch();
}
………………………………………………………………………………………………………………………………………….
Using while Loop
#include<iostream.h>
#include<conio.h>
void main()
{
int number, i, tab;
cout<<"Enter Number for Table "<<endl;
cin>>number;
i=1;
while(i<=10)
{
tab = number*i;
cout<<number<<"*"<<i<<"="<<tab<<endl;
i++;
}
getch();
}
You can divide up your code into separate functions and can assign different task to
functions.
It makes our program easier by writing the same code again and again.
The function is defined once in the program it but can be used several times by just calling
that function when desired.
Declaration of function:
We must have to declare a function before defining function body. The declaration of a
function is called function prototype.
Defining Function:
In function body we define the task that a function is going to perform.
Syntax:
body of function;
#include<conio.h>
void display();
void main()
clrscr();
display();
cout<<"Programming is interesting"<<endl;
display();
getch();
void display()
cout<<"**************"<<endl;
OUTPUT:
**************
Programming is interesting
**************
#include<conio.h>
void main()
int n1,n2;
clrscr();
cout<<"enter first number"<<endl;
cin>>n1;
cout<<"enter second number"<<endl;
cin>>n2;
add(n1,n2);
subtract(n1,n2);
getch();
}
void add(int x,int y)
{
int s;
s=x+y;
cout<<s<<endl;
}
void subtract(int x,int y)
{
int s;
s=x-y;
cout<<s<<endl;
}
Trigonometric Functions:
Functions Purpose
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
double x= 50.0;
clrscr();
x= x*(3.14159/180);
Prepared by:Usama Musharaf For DIT Students Page 36
cout<<"Sin 50 = "<<sin(x)<<endl;
cout<<"Cos 50 = "<<cos(x)<<endl;
cout<<"Tan 50 = "<<tan(x)<<endl;
cout<<"Sin inverse 50 = "<<asin(x)<<endl;
cout<<"Cos inverse 50 = "<<acos(x)<<endl;
cout<<"Tan inverse 50 = "<<atan(x)<<endl;
cout<<"Sin hyperbola 50 = "<<sinh(x)<<endl;
cout<<"Cos hyperbola 50 = "<<sinh(x)<<endl;
cout<<"Tan hyperbola 50 = "<<sinh(x)<<endl;
getch();
}
Arithmetic Functions:
abs(x) Computes the absolute value of an integer.
labs(x) Computes the absolute value of a long integer.
fabs(x) Computes the absolute value of a floating-point value.
fabsl(x) Computes the absolute value of long double value.
Sqrt() Pow()
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
#include<math.h> #include<math.h>
void main() void main()
{ {
double number; int number,power;
clrscr(); clrscr();
number=4; number=4;
cout<<sqrt(number); power=2;
getch(); cout<<pow(number,power);
} getch();
fmod() Function:
Modulus operator only computes the reminder of integer numbers, whereas the fmod()
function computes the reminder of real numbers as well.
#include<iostream.h> Output:
#include<conio.h> Reminder = 2.623
#include<math.h>
void main()
{
double x = 10.123;
double y = 7.5;
cout<<”Reminder = ”<<fmod(x,y);
getch();
}
Sample Output:
The Total Length is = 13
Strlwr() converts the uppercase letters to lower case and strupr() converts the
lowercase letters to upper case.
cout<<strlwr(“MUHAMMAD KHAN”)<<endl;
cout<<strupr(“ ahsan khan”);
Sample Output:
muhammad khan
AHSAN KHAN
Sample Output:
ALI
ALI
Example:
char str1[10]= “ABC”;
char str2[10]= “DEF”;
strcat(str1 , str2)
cout<<str1<<endl;
cout<<str2;
Sample Output:
ABCDEF
DEF