C PROGRAMMING LANGUAGE
SOME THINGS ABOUT C
Case matters, white space does not
Comments go between /* and */
Each statement is followed by a semicolon
Execution begins in the main function:
int main(int argc, char* argv[]) { /* ignore this */
/* start here */
return 0; /*end here */
WHAT ARE C LIBRARIES?
C is a lightweight language. Most of its intelligence is compartmentalized in
libraries.
Almost all c programs use the “stdio” or standard input/output library. Many also
use the “math” library.
To use a library, include the header file (I.e., “stdio.h”) at the top of the file.
For most special purpose libraries (I.e., math) you need to include the library on
the link line. In Visual C++, go to project->settings->object/module libraries.
C VARIABLE TYPES
The most common types are: char, int, float, and double.
Strings are arrays of characters (we’ll cover arrays later).
Declare a variable before you use it:
int x; /* declares an integer called x. Its value is not assigned. */
float y, z = 3.14159; /* declares two floating point numbers. z is set equal to pi */
1
z = 4; /* now z is equal to 4 */
myVal = 2; /* This would be an error, because myVal was not yet declared */
LOGICAL OPERATORS
C defines these logical operators: <, >, <=, >= and == (the equivalence operator)
You can compare any variable. Characters are compared based on their ASCII
values.
All answers will be true (not zero) or false (0)
You can extend the logic with && (and), ~ (not) and || (or).
THE IF STATEMENT
Syntax: if (expression) statement;
If the expression is true (not zero), the statement is executed. If the expression is
false, it is not executed.
You can group multiple expressions together with braces:
if (expression) {
statement 1;
statement 2;
statement 3;
THE IF/ELSE STATEMENT
Syntax: if (expression) statement_1; else statement_2;
If the expression is true, statement_1 will be executed, otherwise, statement_2
will be.
if (myVal < 3) printf(“myVal is less than 3.\n”);
else printf(“myVal is greater than or equal to 3.\n”);
2
THE FOR LOOP
Syntax: for (initialization; test; increment) {statements;}
The for loop will first perform the initialization. Then, as long is test is TRUE, it
will execute statements. After each execution, it will increment.
for (cntr = 0; cntr < 3; cntr = cntr + 1) {
printf(“ Counter = %d\n”, cntr);
Counter = 0;
Counter = 1;
Counter = 2;
3
C is a procedural programming language.Computer program are set of instructions that
tells the computer how to carry out some computations and perform some other
functions. The instructions that constitute a program have to be expressed in one of the
many computer programming languages and C is one of such languages. C programming
language is one of the widely use programming languages at the present time.
The components of the above structure are:
1. Header Files Inclusion: The first and foremost component is the inclusion of the
Header files in a C program.
A header file is a file with extension .h which contains C function declarations
and macro definitions to be shared between several source files.
Syntax to include a header file in C:
#include <(header_file_name).h>
4
2. Main Method Declaration: The next part of a C program is to declare the main ()
function. The syntax to declare the main function is:
Syntax to Declare main method:
int main()
{}
3. Variable Declaration: The next part of any C program is the variable declaration. It
refers to the variables that are to be used in the function.
4. Body: Body of a function in C program, refers to the operations that are performed in
the functions. It can be anything like manipulations, searching, sorting, printing,
etc.
5. Return Statement: The last part in any C program is the return statement. The
return statement refers to the returning of the values from a function.
Functions
- C program is made up of one or more functions
- One of the functions must be named main
- Other functions, if any, are named by the programmer
- The main function indicates to the system the point to start program execution at run
time
○ COMMENT
- Comments are used to add clarifying messages to a program
- Comments are inserted in a C- program for users and not for the underlying machine
- Hence, comments are removed from the program during compilation
- Anywhere in a C-program where a space is allowed, a comment can be inserted there
- Comments are non-executable statements in C
5
- Format is:
/* comment */
● ADVANTANGES OF C
- It offers the flexibility of a high level language i.e. simpler for human operator to
understand and program
- It offers also the functionality of a low-level language i.e. manipulation of bits,
bytes, and direct access to CPU registers
● APPLICATIONS OF C WITH JUSTIFICATION
○ System Programming and Application Packages 5
- It is widely used to develop Operating Systems; and Application packages such as
language Compilers, Assemblers, Databases, Utilities, Network
Drivers, Text Editors, Word Processors, language Interpreters, etc
○General Purpose Programming
-It is now becoming a de-facto language for teaching structured computer
programming
○ JUSTIFICATIONS
- It is relatively faster than other high level languages
- It has direct control of i/o
- It supports memory management functions
- It can directly manipulate bits, bytes, and registers
- It is easier to program than Assembler
- It is becoming a de-facto programming language
● CHARACTERISTICS OF C – LANGUAGE
- It is highly modular (made up of functions)
- Function in C is made up of building blocks
6
- It is strong Typing
- It is case sensitive
- C is a very portable language because it has no in-built i/o functions
- i/o functions are usually machine dependent
- Hence, i/o functions in C are provided by library functions
o SYMBOLS IN C
- Just like natural language have symbols used for forming words and sentences, C
has acceptable symbols for forming words (tokens) and statements.
- The symbols consist of alphabet, numerals, and special characters.
ALPHABETS:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
NUMERAL: 0 1 2 3 4 5 6 7 8 9
SPECIAL CHARACTERS :
! % ^ & ( ) - + = { } | [ ] \ ; „ . / -> ++ -- .* ->* <<>>
<= >= != && || *= /= %= += -= <<= >>= &= ^= |= :: #
SAMPLE C PROGRAM I
PROGRAM TO DISPLAY HELLO WORLD
#include <stdio.h>
int main()
7
Printf("Goodbye, World!");
return 0;
Exercise Type a code to display “WELCOME TO C PROGRAMMING CLASS”
Data types
C has several types of variables, but there are a few basic types:
Integers - whole numbers which can be either positive or negative.
Defined using char, int, short, long or long long.
Unsigned integers - whole numbers which can only be positive. Defined
using unsigned char, unsigned int, unsigned short, unsigned long or unsigned lo
ng long.
Floating point numbers - real numbers (numbers with fractions). Defined
using float and double.
SAMPLE C PROGRAM
PROGRAM TO SUM UP THREE NUMBERS
#include <stdio.h>
int main() {
int a = 3;
float b = 4.5;
double c = 5.25;
float sum;
sum = a + b + c;
/* Your code goes here */
8
printf("The sum of a, b, and c is %f.", sum);
return 0;
SAMPLE C PROGRAM
PROGRAM TO CAL AREA OF TRIANGLE
#include<stdio.h> //library file access
#define HALF 0.5
/* program to cal. area of triangle */
void main()
//main program starts here
float height,base,area; /* var declaration*/
printf(“Enter value for the base:\n”);
scanf(“%f”,&base); //the value will be stored in base. & indicates d address of the data item
printf(“Enter value for the height:\n”);
scanf(“%f”,&height);
area= HALF * base * height; //HALF is the global constant declaration
printf(“Area=%f\n”,area);
FLOW OF PROGRAMMING CONTROL
FLOW OF CONTROL -The normal sequencing of a program flow is for the
computer to execute the first statement and then moves to the next statement until
the end of the program
- A change in this normal sequencing of program statements is often desired
9
- A set of statements for effecting different sequencing than the normal is called
flow of control statements
- C‟s flow of control statements are:
if ~ else, switch, the ? alternative, for , while , do ~ while, break ,
continue, goto , exit()
The if statement allows us to check if an expression is true or false, and execute different
code according to the result.
If Sytax
if (condition)
statement;
int foo =1;
int bar =2;
if (foo < bar){
printf("foo is smaller than bar.");
}
if (foo > bar){
printf("foo is greater than bar.");
}
IF ELSE Syntax
IF else statement are use for statement that contains one condition and two
possible action.condition may be true or false
IF(Condition)
{
Statament1;
Statement2;
}
Else
{
Statement1;
10
Statement2;
}
We can use the else keyword to execute code when our expression evaluates to false.
int foo = 1;
int bar = 2;
if (foo < bar) {
printf("foo is smaller than bar.");
} else {
printf("foo is greater than bar.");
}
Exercise
Write a program using if else statement to check if a number is
even or odd.
Nested If Else Statements
Syntax
If (condition)
if(condition);
Else
Statement2;
Statement3;
When there are another if else statement it is called nested if statement
int peanuts_eaten = 22;
intpeanuts_in_jar=100;
intmax_peanut_limit=50;
if(peanuts_in_jar>80){
if(peanuts_eaten<max_peanut_limit){
printf("Take as many peanuts as you want!\n");
}
11
}else{
if(peanuts_eaten>peanuts_in_jar){
printf("You can't have anymore peanuts!\n");
}
else{
printf("Alright, just one more peanut.\n");
}
}
FOR LOOPS
For loops in C are straightforward. They supply the ability to create a loop - a
code block that runs multiple times. For loops require an iterator variable, usually notated
as i.
For loops give the following functionality:
Initialize the iterator variable using an initial value
Check if the iterator has reached its final value
Increases the iterator
For example, if we wish to iterate on a block for 10 times, we write:
FORSyntax
For(exp1;exp2;exp3)
Statement;
inti;
for(i=0;i<10;i++){
printf("%d\n",i);
}
This block will print the numbers 0 through 9 (10 numbers in total).
12
For loops can iterate on array values. For example, if we would want to sum all the
values of an array, we would use the iterator I as the array index:
intarray[10]={1,2,3,4,5,6,7,8,9,10};
int sum =0;
inti;
for(i=0;i<10;i++){
sum += array[i];
}
/* sum now contains a[0] + a[1] + ... + a[9] */
printf("Sum of the array is %d\n", sum);
NESTING OF LOOP
When a loop written inside the body of another loop then it is know as nesting
of loopp.Any type of loop can be nested in any type such as while’do while,for
Void main()
{
Inti,j;
For(i=0;i<2;i++)
For(j=0;j<5;i++)
Printf(“%d%d”,i,j);
}
Output;
J=01234
i=1
j=01234
BREAK STATEMENT (BREAK)
Break statement is used inside loop and switch statement. It causes immediate exit
from that loop in which it appears .and it is written with condition. It is written with the
keyword break
Example:
13
Voic main()
Int j=0;
For(j=0;j<6;j++)
If(j==4)
Break;
Output
0123
CONTINUE STATEMENT
Continue statement is used for continuing next iteration of loop after skipping
some statement of loop. When it encountered control automatically passes through the
beginning of the loop. It is usually associated with the if statement. It is useful when we
want to continue the program without executing any part of the program.
The difference between break and continue is, when the break encountered loop is
terminated and it transfer to the next statement and when continue is encounter control
come back to the beginning position.
Example:-
void main()
int n;
for(n=2; n<=9; n++)
if(n==4)
14
continue;
printf(“%d”, n);
Printf(“out of loop”);
Output: 2 3 5 6 7 8 9 out of loop
WHILE LOOPS
While loops are similar to for loops, but have less functionality. A while loop
continues executing the while block as long as the condition in the while remains true.
For example, the following code will execute exactly ten times:
int n =0;
while(n <10){
n++;
}
While loops can also execute infinitely if a condition is given which always evaluates as
true (non-zero):
while(1){
/* do something */
}
Program to display number in ascending order using while loop
#include <stdio.h>
int main() {
int number =1;
while (number<=100){
15
printf(“The number is %d\n”,number);
return 0;
Multiplication table of 12
#include <stdio.h>
int main() {
int n,i=1
printf(“Enter any number\n”);
scanf(“%d’’,&n);
while(i<=10)
Printf(“%d*%d=%d\n”,n,I,n*i)
i=i+1;
ARRAYS
Arrays are special variables which can hold more than one value under the same
variable name, organized with an index. Arrays are defined using a very straightforward
syntax:
Accessing a number from the array is done using the same syntax. Notice that arrays in C
are zero-based, which means that if we defined an array of size 10, then the array cells 0
through 9 (inclusive) are defined. Numbers [10] is not an actual value.
Example 1
intnumbers[10];
/* populate the array */
16
numbers[0]=10;
numbers[1]=20;
numbers[2]=30;
numbers[3]=40;
numbers[4]=50;
numbers[5]=60;
numbers[6]=70;
/* print the 7th number from the array, which has an index of 6 */
printf("The 7th number in the array is %d", numbers[6]);
Example 2
Program To Calculate Factorial of 10
# include <stdio.h>
int main(){
int array[]={1,2,3,4,5,6,7,8,9,10};
int factorial=1;
int i=0;
for(i=0;i<10;i++){
factorial*= array[i];
Printf(‘’10 is %d\n”, factorial);
PROGRAM TO CALCULATE THE SUM OF 10 ARRAY
# include <stdio.h>
int main() {
Int array[]={1,2,3,4,5,6,7,8,9,10};
17
Int Sum=0;
Int i;
For(i=0; i<10; i++){
Sum+=array[i];
Printf(“Sum of the array is %d\n”,Sum);
return 0;
# include<stdio.h>
Int main() {
Int i=0;
Int array[]={1,7,4,5,9,3,5,11,6,3,4};
While(i<10){
Printf(“%d\n,array[i]);
18