C Programming

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

GETTING STARTED IN C PROGRAMMING

The C programming language is a general-purpose programming language which is developed by


Dennis Ritchie an American computer scientist, Computer Programmer and Mathematician.

General Structure of a Computer and C Program


The most basic form of a C program performs three basic operation:

Input Data #include<stdio.h> Preprocessor directives


#include<conio.h> Preprocessor directives
main ( ) function main(building block)
Process Data { curly bracket (start of program)
Variable declarations…
Display all Results Statements…
} curly bracket (end of program)

An Example C Program
/* This program prints a one-line message */
#include <stdio.h>
#include <conio.h>
main( )
{
printf(" \t Hello World \n");
getch( );
}

/* This program ... */ defines a single line comment. Comments are ignored by the
compiler and are used to provide useful information for humans
that will read the program.
main( ) C programs consist of one or more functions. One and only one of
these functions must be called main. The brackets following the
word main indicate that it is a function and not a variable.
{ } braces surround the body of the function, which consists of one or
more instructions (statements).
printf( ) is a library function that is used to print on the standard output
stream (usually the screen).
"Hello World\n" is a string constant.
\n is the newline character.
\t is the tab character.
; a semicolon denoted the end/terminates a statement.
Identifiers, and I/O Statements

C programming language also uses variable names to represent data in a program. A name represents
the data objects to manipulate the program and produce information. Data objects are composed of a
variable name and a constant name.

Variable names
Data Objects
C PROGRAMMING LANGUAGE Page 1
Constant names

Proper identifying and naming of data objects are very important in a computer program. Naming of
data objects are done through identifiers. Identifier includes variable and constant names.

Variable names indicate that the values of these data changes due to the actions performed by the
program. A variable has a name, a type and stores a value of that type.

Constant names never change or altered in the program. Constant is an entity whose value does not
change and can be numeric or literal constant.
Example: numeric constant literal constant
1 ‘A’
3.1416 “fare”
Character constants are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable
of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'). There
are certain characters in C when they are preceded by a backslash, they will have special meaning and
they are used to represent escape sequence like newline (\n), tab (\t), single line comment (\\),
multiple line comment (\* . . . . . .. *\).

General Rule for Identifiers


1. names are made up of letters and digits.
2. the first character of a name must be a letter.
3. C is a case sensitive. ‘A’ ≠’a’
4. underscore symbol (_) is considered letter to come up with meaningful names.

example: Valid names Invalid names


A 1_ab
salary $money
ComputerGrade Computer-Grade
rate_per_hour xy2_%

Keywords are reserved words may not be used as constant or variable or any other identifier names
that have a special meaning when they appear in a computer program. The ANSI (American National
Standard Institute) has 32 reserved words that cannot be used.

Examples of theses reserved words are:


break else long switch case return
default do char main int string
Data type – is a classification of data which instruct the compiler on how to use the data that can be
assumed by a variable of that type.

C PROGRAMMING LANGUAGE Page 2


C has the following basic built-in datatypes.
Data type Prefix Identifier Description
Integer int %d or % i is used to define whole integer number.
Float float %f used to store single precision signed real numbers.
Double double %f is used to define BIG floating-point numbers.
Character char %c defines single character character data type.
String string %s defines multiple characters

Assignment is the process of storing a value in a variable.


Example: miles = 26;
The variable mile is known as the Left-Hand Side modifiable value.

Syntax Display for Assignment


Syntax: result =expression example: sum = a + b;

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify
where one element in a statement, such as int, ends and the next element begins. There must be at
least one whitespace character (usually a space) between int and age for the compiler to be able to
distinguish them.
Example: int age;

#include Directive for Defining identifiers from Standard Libraries


Syntax: #include<standard header files>
Example: #include<stdio.h> #include<conio.h> #include<math.h>

#include Directives for Creating Constant Macros


Syntax: #define Name Value
Example: #define Pound_per_Kilograms 2.2 #define Days_in_a_Year 365

Using scan and print Function


<stdio.h> library file for the scanf (used for input)- and printf (- used for output).

SYNTAX: scanf(format, input list); SYNTAX: printf(format, print list);


Example: Example:
scanf(“%c%c%c%d”, &short_name,&age_in_years); printf("%f km per hour\n", kilometres);

Format Input list


INTERPRETATION: The scanf function copies into memory data typed at the keyboard
during program execution. The format is a quoted string of placeholders, one placeholder
for each variable in the input list. Input list is variable separated by comma.

C PROGRAMMING LANGUAGE Page 3


Output Formats
Formats are specified using placeholders. The placeholder consists of a size and a letter. The size is a
number that gives you the length of the output while the letter is the type of the output. Example:
printf(“\t %d years old.”, age);

Operators
o allow manipulation of the actual bits held in each byte of a variable.
o each byte consists of a sequence of 8 bits, each of which can store the value 0 or 1.

Arithmetic Operators
o There are following arithmetic operators supported by C language.
o Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30 10+20=30
- Subtracts second operand from the first A - B will give -10 10-20=-10
* Multiply both operands A * B will give 200 10*20=200
/ Divide numerator by denumerator B / A will give 2 20/10=2 r.0
% Modulus Operator and remainder of after B % A will give 0 20%10=0
an integer division 15%7=1

Rules for Evaluation of Arithmetic Expressions

When evaluating a mathematical expression some rules must be obeyed to arrive at consistent and
predictable results.
a. All parenthesized sub-expressions must be evaluated separately. Nested parenthesized
expressions must be evaluated from the inner most parentheses to the outer most.
b. The operator precedence rule. Operators in the same sub-expression are evaluated in the
following order.
1. Positive (+) or Negative (-) 2. *, /, % 3. +, -
c. If the operators in an expression belong to the same priority level, the expression is evaluated
from left to right.

Increment and Decrement Operators


Increment and decrement operators- method of adding/subtracting from an object.
Increment sample decrement sample
++ increment counter++; equivalent to counter--; equivalent to
-- decrement counter = counter+1; counter = counter-1;
x++ x-- example:
A++ will give 11 A-- will give 9
++x --x 10++=11 10--=9

Logical Operator – a function that denotes a logical operation.


The logical operators perform logical-AND (&&) and logical-OR ( || ) operations. Logical operators do
not perform the usual arithmetic conversions. Instead, they evaluate each operand in terms of its
equivalence to 0. The result of a logical operation is either 0 or 1.
C PROGRAMMING LANGUAGE Page 4
The && OPERATOR (and) corresponds to the Boolean logical operation AND, which yields true if
both its operands are true, and false otherwise.

The || OPERATOR (or) corresponds to the Boolean logical operation OR, which yields true if either of
its operands is true, thus being false only when both operands are false.

The ! NOT is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and
inverts it, producing false if its operand is true and true if its operand is false. Basically, it returns the
opposite Boolean value of evaluating its operand.
variable variable (and)* (or)+ not
a b a && b a || b ! (a||b)
false false 0&&0=0 0||0=0 1
false true 0&&1=0 0||1=1 0
true false 1&&0=0 1||0=1 0
true true 1&&1=1 1||1=1 0

Relational Operators

The relational operators compare values to one other. The comparison operators are =, !=, <>, <, >, < =,
and > =. All the relational operators result in a Boolean value.

For example: Let: A = 10 and B = 20

Operator Description Example


Checks if the value of two operands is equal or not, (A == B) is not true.
==
if yes then condition becomes true.
Checks if the value of two operands is equal or not,
!= (A != B) is true.
if values are not equal then condition becomes true.
Checks if the value of left operand is greater than
> the value of right operand, if yes then condition (A > B) is not true.
becomes true.
Checks if the value of left operand is less than the
< value of right operand, if yes then condition (A < B) is true.
becomes true.
Checks if the value of left operand is greater than or
>= equal to the value of right operand, if yes then (A >= B) is not true.
condition becomes true.
Checks if the value of left operand is less than or
<= equal to the value of right operand, if yes then (A <= B) is true.
condition becomes true.

C PROGRAMMING LANGUAGE Page 5


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 6


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 7


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 8


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 9


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 10


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

Name: __________________________________________________ Section: ________________________

Filename:_________________________ Date Started:____________ Date Finished:________

Date Checked: ___________________ CBY: ______________________ Score: __________________

C PROGRAMMING LANGUAGE Page 11


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 12


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 13


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

C PROGRAMMING LANGUAGE Page 14


GETTING STARTED IN C PROGRAMMING

Direction: As your assignment, make first the program design of the given source code and output
below in the left page before the coding.

Note: Code the general structure of C programming first then insert the below code snippet in the
body of the program.

int a,b;
printf(“\t\tPlease enter first integer:\t ”);
scanf(“%d”,&a);
printf(“\n\n\t\t Please enter second integer:\t ”);
scanf(“%d”,&b);
a=a+10;
b=a+b*2-5;
printf(“\n\n \t\t new value of a=%d \n\new value of b=%d” ,a ,b);

Output:

C PROGRAMMING LANGUAGE Page 15


CONDITIONS HANDLING
Control structures – programs must be written in step-by-step instructions to obtain a successful
result. The three basic control structures in virtually every procedural language are:
o Sequence- is the default control structure; instructions are executed one after another.
o Conditional - The IF-THEN or IF-THEN-ELSE control structure allows a program to follow
alternative paths of execution.
o Iterative- Iteration, or looping, gives computers much of their power. They can repeat a
sequence of steps as often as necessary and appropriate repetitions of quite simple steps can
solve complex problems.

Data structures specify types of data, and thus which operations can be performed on them, while
eliminating the need for a programmer to keep track of memory addresses. Simple data structures
include integers, real numbers, Booleans (true/false), and characters or character strings. Compound
data structures are formed by combining one or more data types.

Control Flow Statements


The term flow of control refers to the order in which a program's statements are executed. Following
are the control flow statements in C language, which can be used to control the flow of a program.

o if-else-if o break
o switch o continue

Conditional Branching – if/ if –else

if statements take the following form:


if (expression)
if (expression) {
statement; or block of statements;
}

The else part of the statement is optional. Note (especially Pascal programmers) that the
semicolon terminating the first statement is required, even if the else part is present;
if (a < b)
statement1;
if (c < d)
statement2;
else
statement3;
Conditional Selection — switch

Switch is a mechanism for jumping into a series of statements, the exact starting point
depending on the value of the expression. It can be an alternative to the nested if statement
because in the switch statement, we have several options.

Syntax:
switch ( expression)
{
case value : statement; statement; ...
C value
case PROGRAMMING
: statement;LANGUAGE
statement; ... Page 16
..
default : statement; statement; ...
}
case 4: printf ("four ");
with
case 4: printf ("four ");
break;

This process of executing statements in subsequent case clauses is called fall through. To
prevent fall through, break statements can be used, which cause an immediate exit from the
switch statement. In the example above, replacing and adding break statements to the
statements for the other labels, will result in a program that prints only one string depending
on the value of the integer input by the user. The values listed in the case part of the switch
statement must be constant integer values; integer expressions can be used if the value can
be determined at compile time.

DEFAULT - If none of the conditions is met, then default condition is executed.

LOOPS - To execute a set of instructions repeatedly until a particular condition is being


satisfied. Three types of looping statements are for loop, while loop and do while loop.

For Loop - for loop statement allows several lines represent until the condition is satisfied. A
for loop is made up of 3 parts inside its brackets which are separated by semi-colons.

Syntax: Example:
for (initialization; condition; iteration) {
{ int i;
Statement1; for (i = 1;i <= 12;i++)
Statement2; printf("\t%d\n",i);
} }

Initialization- the first part initializes the loop variable. The loop variable controls
and counts the number of times a loop runs. In the example the loop variable is called i
and is initialized to 1.

Condition - the second part is the condition a loop must meet to keep running. In the
example the loop will run while i is less than or equal to 12 or in other words it will
run 12 times.

Iteration- the third part is the loop variable incrementer. In the example i++ has been
used which is the same as saying i = i + 1. This is called incrementing. Each time the
loop runs i has 1 added to it. It is also possible to use i-- to subtract 1 from a variable
in which case it is called decrementing.

While Loop - The most basic loop in C is the while loop. While statement is like a repeating if
statement. Like an if statement if the test condition is true: the statements get executed. The
difference is that after the statements have been executed, the test condition is checked
again. If it is still true, the statements get executed again. This cycle repeats until the test
condition evaluates to false.
C PROGRAMMING LANGUAGE Page 17
Syntax:
while ( expression )
{
single statements;
Or
block statements;
}

do...while loop - is just like a while loop except that the test condition is checked at the end
of the loop rather than the start. This has the effect that the content of the loop is always
executed at least once.
Syntax:
do
{
Single statement
or
Block of statements;
}
While
(expression);

break and continue statements - C provides two commands to control how we loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.

C PROGRAMMING LANGUAGE Page 18


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho11

A. If the answer is TRUE

B. If the answer is FALSE

C PROGRAMMING LANGUAGE Page 19


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho12.

C PROGRAMMING LANGUAGE Page 20


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho13.

C PROGRAMMING LANGUAGE Page 21


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho14.

C PROGRAMMING LANGUAGE Page 22


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho15.

C PROGRAMMING LANGUAGE Page 23


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho16.

C PROGRAMMING LANGUAGE Page 24


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho17.

C PROGRAMMING LANGUAGE Page 25


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho18.

C PROGRAMMING LANGUAGE Page 26


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho19.

C PROGRAMMING LANGUAGE Page 27


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho20.

For Loop explanation of the above program.

Displayed
New value of
Loop Value of Result of Output is
Condition variable
number variable Condition the value of
(incrementing)
variable
1st 0 0<5 True 0 1
2nd 1 1<5 True 1 2
3rd 2 2<5 True 2 3
4th 3 3<5 True 3 4
5th 4 4<5 True 4 5
6th 5 5<5 False end
7th
8th

C PROGRAMMING LANGUAGE Page 28


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho21.

C PROGRAMMING LANGUAGE Page 29


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho22.

Direction: complete the For-loop table.

Displayed
New value of
Loop Value of Result of Output is
Condition variable
number variable Condition the value of
(decrementing)
variable
1st 10 10>0 True Hello 10 9
2nd 9 9>0 True Hello 9 8
3rd 8 8>0 True Hello 8 7
4th 7 7>0 True Hello 7 6
5th 6 6>0 True Hello 6 5
6th 5 5>0 True Hello 5 4
7th 4 4>0 True Hello 4 3
8th 3 3>0 True Hello 3 2
9th 2 2>0 True Hello 2 1
10th 1 1>0 True Hello 1 0
11th 0 0>0 false
12th

C PROGRAMMING LANGUAGE Page 30


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho23.

C PROGRAMMING LANGUAGE Page 31


CONDITIONS HANDLING

Direction: Run the source code of the output given below. Save as LASTNAME ho24.

C PROGRAMMING LANGUAGE Page 32


ARRAYS AND STRINGS
C programming language provides a data structure called the array, which can store
a fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables
of the same type.

Array is a collection of homogenous data stored under unique name. The values in an
array are called as elements of an array. These elements are accessed by numbers called as
subscripts or index numbers. Arrays may be of any variable type. Array is also called as
subscripted variable.

Types of an Array:
1. Single - dimensional array
2. Two - dimensional array

Single / One Dimensional Array:


The array which is used to represent and store data in a linear form is called as 'single- or
one-dimensional array. The array Size must be an integer constant greater than zero
and type can be any valid C data type.
Syntax: <data-type> <array_name> [size];
Example: int deposit [4];
deposit [0] = 500.00;
deposit [1] = 700.00;
deposit [2] = 1000.00;
deposit [3] = 1500.00;

Declaring Arrays
Another way is to initialize some or all the values at the time of declaration:
type arrayName [ arraySize ];
int arr[4] = { 6, 0, 9, 6 };
Sometimes it is more convenient to leave out the size of the array and let the compiler
determine the array's size for us, based on how many elements we give it:
int arr[] = { 6, 0, 9, 6, 2, 0, 1, 1 };

Features:
o Array size should be positive number only.
o String array always terminates with null character ('\0').
o Array elements are countered from 0 to n-1.
o Useful for multiple reading of elements (numbers).

Disadvantages:
o There is no easy method to initialize large number of array elements.
o It is difficult to initialize selected elements.

C PROGRAMMING LANGUAGE Page 33


Memory Allocation for one- dimensional array:
/* Program to demonstrate one dimensional array.

#include <stdio.h>
#include <conio.h>
void main()
{
int a[3], i;;
clrscr();
printf("\n\t Enter three numbers : ");
for(i=0; i<3; i++)
{
scanf("%d", &a[i]); // read array
}
printf("\n\n\t Numbers are : ");
for(i=0; i<3; i++)
{
printf("\t %d", a[i]); // print array
}
getch();
}
Output:

Enter three numbers : 9 4 6


Numbers are : 9 4 6_

Two-Dimensional Array:
The array which is used to represent and store data in a tabular form is called as 'two-
dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two-dimensional array:

Syntax: <data-type> <array_nm> [row_subscript][column-subscript];


Example: int a[3][3];

In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The
total size would be 3 * 3 * 2 = 18 bytes.
It is also called as 'multidimensional array.'

Limitations of two-dimensional arrays:


o We cannot delete any element from an array.
o If we don’t know that how many elements have to be stored in a memory in
advance, then there will be memory wastage if large array size is specified.

C PROGRAMMING LANGUAGE Page 34


Memory Allocation for two-dimensional array:

/* Program to demonstrate two dimensional array.


#include <stdio.h>
#include <conio.h>
void main()
{
int a[3][3], i, j;
printf("\n\t Enter matrix of 3*3 : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
printf("\n\t Matrix is : \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("\t %d",a[i][j]); //print 3*3 array
}
printf("\n");
}
getch();
}

C PROGRAMMING LANGUAGE Page 35


ARRAYS AND STRINGS

Direction: Run the source code of the output given below. Save as LASTNAME ho25.

C PROGRAMMING LANGUAGE Page 36


ARRAYS AND STRINGS

Direction: Run the source code of the output given below. Save as LASTNAME ho26.

C PROGRAMMING LANGUAGE Page 37


ARRAYS AND STRINGS

Direction: Run the source code of the output given below. Save as LASTNAME ho27.

/*C program to read in four integer numbers into an array and find the
* average of largest two of the given numbers without sorting the array.
* The program should output the given four numbers and the average.
*/
#include <stdio.h>
#include <conio.h>
#define MAX 4

main()
{
int array[MAX], i, largest1, largest2, temp;

printf("Enter %d integer numbers \n", MAX);


for (i = 0; i < MAX; i++)
{
scanf("%d", &array[i]);
}

printf("\nInputted integers are \n");


for (i = 0; i < MAX; i++)
{
printf("%5d", array[i]);
}
printf("\n");
/* assume first element of array is the first larges t*/
largest1 = array[0];
/* assume first element of array is the second largest */
largest2 = array[1];
if (largest1 < largest2)
{
temp = largest1;
largest1 = largest2;
largest2 = temp;
}
for (i = 2; i < 4; i++)
{
if (array[i] >= largest1)
{
largest2 = largest1;
largest1 = array[i];
}
else if (array[i] > largest2)
C PROGRAMMING LANGUAGE Page 38
{
largest2 = array[i];
}
}
printf("\n%d is the first largest \n", largest1);
printf("\n%d is the second largest \n", largest2);
printf("\nAverage of %d and %d = %d \n", largest1, largest2,
(largest1 + largest2) / 2);
getch();
}

C PROGRAMMING LANGUAGE Page 39

You might also like