0% found this document useful (0 votes)
32 views21 pages

C Programming Course

The document provides an overview of the structure and components of a C program. It discusses the following key points in 3 sentences: Every C program consists of functions, with one main function that is called first. Each function contains a function heading with the name, argument declarations, and a compound statement. The document then provides an example C program that converts dollars to taka to demonstrate the structure of functions, use of libraries, input/output statements, and arithmetic assignments.

Uploaded by

Mahfuzul Haque
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views21 pages

C Programming Course

The document provides an overview of the structure and components of a C program. It discusses the following key points in 3 sentences: Every C program consists of functions, with one main function that is called first. Each function contains a function heading with the name, argument declarations, and a compound statement. The document then provides an example C program that converts dollars to taka to demonstrate the structure of functions, use of libraries, input/output statements, and arithmetic assignments.

Uploaded by

Mahfuzul Haque
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

COMPILED BY:

FOYSOL MAHMUD

10TH BATCH

DEPARTMENT OF CIVIL ENGINEERING.

LEADING UNIVERSITY, SYLHET.


Structure of a C Program

Every C program consist of one or more modules called functions. One of the function that must be
called main. The program will always begin by executing the main function, which may access the
other function.
Each function must contain:
1. A function heading, which consists of the function name.
2. A list of argument declarations.
3. A compound statement.
Title (comment)
Here is an example to observe the structure of a C program:
//program to convert the dollars to equivalent taka.
#include <stdio.h> Library file excess
int main() Output Statement
Function Heading
{ Variable declaration
float taka, dollar, ex_rate;
printf("Enter the exchange rate of dollar to equivalent taka: ");
scanf("%f", &ex_rate);
printf("Enter the amount of dollar: "); Input Statement
scanf("%f", &dollar);
taka = dollar*ex_rate; Assignment Statement
printf("The amount of equivalent taka: %.2f\n", taka);
return 0;
}
Output of the progrtam:

The C character set

C uses:
Uppercase letter A to Z.
Lowercase letter a to z.
Digits 0 to 9.
And some certain special character listed below:
+ - * / = % & # ! ?
^ “ ‘ \ | < > ( ) {
} [ ] : ; . _ Space
Identifiers (Variable name/ declaration)

• Both upper case and lower case letter are permitted (using of lowercase letters are
favorable).
• Underscore( _ ) character is also permitted.
• Number is also permitted but not for the first of the variable name

Valid Identifiers
x F14 Fm_14 _num
foysol Smaller_num MATRIX T14

Invalid Identifiers
4 t h The first character must be a
letter.
“x” Illegal characters(“)
order-no Illegal character (-).
error flag Illegal character (blank space).

Keywords

The following keywords we have used in our class are:


char for return while
double if float
else int switch

Data Types:

Data Type Description Typical Memory Requirements


int integer quantity 2 bytes or one word (varies from
one compiler to another)
char single character 1 byte
float floating-point number (i.e., a number containing a 1 word (4 bytes)
decimal point and/or an exponent)
double double-precision floating-point number (i.e., more 2 words (8 bytes)
significant figures, and an exponent which may be
larger in magnitude)

Example of integer Data Type:


integer Data Type
Example of char Data Type: char Data Type

float Data Type


Example of float Data Type:

Arithmetic Operator:

There are five arithmetic operator in C.


Operator Purpose
+ addition
- subtraction
* multiplication
/ division
% remainder after integer division

Example of Arithmetic operator:

Arithmetic operator

Relational and Logical Operator:

Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
&& And
|| Or

Example of logical operator:

Logical operator

LIBRARY FUNCTIONS

The C language is accompanied by a number of library functions that carry out various commonly
used operations or calculations. These library functions are not a part of the language per se, though
all implementations of the language include them. Some functions return a data item to their access
point; others indicate whether a condition is true or false by returning a 1 or a 0, respectively; still
others carry out specific operations on data items but do not return anything. Features which tend to
be computer-dependent are generally written as library functions. For example, there are library
functions that carry out standard input/output operations (e.g., read and write characters, read and write
numbers, open and close files, test for end of file, etc.), functions that perform
operations on characters (e.g., convert from lower- to uppercase, test to see if a character is uppercase,
etc.), functions that perform operations on strings (e.g., copy a string, compare strings, concatenate
strings, etc.), and functions that carry out various mathematical calculations (e.g., evaluate
trigonometric, logarithmic and exponential functions, compute absolute values, square roots, etc.).
Other kinds of library functions are also available.

Example of library functions:


printf(…..)
scanf(……)

THE scanf(……) FUNCTION


Input data can be entered into the computer from a standard input device by means of the C library
function scanf.

Example of scanf function:

scanf function
THE printf(……) FUNCTION

Output data can be written from the computer onto a standard output device using the library
function printf.

Example of printf function:

printf function

ENTERING INPUT DATA-THE scanf FUNCTION

//program for converting temperature.


#include <stdio.h>
int main()
{
float celsius, fahrenheight;
printf("Enter the temperature in Fahrenheit: ");
scanf("%f", &fahrenheight);
celsius = (5*fahrenheight -160)/9;
printf("Equivalent temperature in Celsius: %.2f\n", celsius);
return 0;
}
•First Type the scanf( function.
• Give “”
•Type % sign then type conversion character.
• give comma.
•Type & sign and then the variable you want to give input.

For Character Input


#include <stdio.h> For integer input
int main() For floating number input
{
char item[20];
int partno;
float cost;
..........
scanf("%s %d %f", &item, &partno, &cost);
......
}
writing output DATA-THE printf FUNCTION

//program for converting temperature.


#include <stdio.h>
int main()
{
float celsius, fahrenheight;
printf("Enter the temperature in Fahrenheit: ");
scanf("%f", &fahrenheight);
celsius = (5*fahrenheight -160)/9;
printf("Equivalent temperature in Celsius: %.2f\n", celsius);
return 0;
}
•Type what you want to print between “”
•Type comma
#include <stdio.h> •Type the variable you want to print the value.
int main()
{
char item[20]; For Character Input
int partno; For integer input
float cost; For floating number input
..........
printf("%s %d %f", &item, &partno, &cost);
......
}

ASSIGNMENTS
//program to convert the dollars to equivalent taka.
#include <stdio.h>
int main()
{
float taka, dollar, ex_rate;

printf("Enter the exchange rate of dollar to equivalent taka: ");


scanf("%f", &ex_rate);
printf("Enter the amount of dollar: ");
scanf("%f", &dollar);

taka = dollar*ex_rate;

printf("The amount of equivalent taka: %.2f\n", taka);

return 0;
}

//program for converting temperature.


#include <stdio.h>
int main()
{
float c,f;

printf("Enter the temperature in Fahrenheit: ");


scanf("%f", &f);

c = (5*f-160)/9;

printf("Equivalent temperature in Celsius: %.2f\n", c);

return 0;
}

//program for finding the real roots of a quadratic


//equation(ax^2+bx+c=0).
#include <stdio.h>
int main()
{
float a, b, c, x, y, z;

printf("Enter the value of a\n");


scanf("%f", &a);
printf("Enter the value of b\n");
scanf("%f", &b);
printf("Enter the value of c\n");
scanf("%f", &c);
z = b*b-4*a*c;
if(z < 0){
printf("There have no real root of this equation\n");
}
else if(z >= 0){
x = -b+sqrt(z);
y = -b-sqrt(z);
printf("The real roots of the equation is %0.5f and %0.5f\n",
x/2*a, y/2*a);
}
return 0;
}

CONTROL STATEMENT

1. Logical selection/ Branching


2. Looping.

BRANCHING: 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 (i.e., whether the outcome is true or false).
The else portion of the if-else statement is optional. Thus, in its simplest general form, the
statement can be written as
if(expression) statement
The expression must be placed in parentheses, as shown. In this form, the statement will be executed
only if the expression has a nonzero value (i.e., if expression is true). If the expression has a value of
zero (i.e., if expression is false), then the statement will be ignored.

if-else ladder:
if(expression 1) statement 1;
else if(expression 2) statement 2;
………
else statement;

expression →Logical expression that are either true or false.

expression
Example: statement

THE switch STATEMENT


The switch statement causes a particular group of statements to be chosen from several available
groups. The selection is based upon the current value of an expression which is included within the
switch statement.
The general form of the switch statement is
switch (expression) statement

Where expression results in an integer value. Note that expression may also be of type char, since
individual characters have equivalent integer values.

switch (exp) statement{


case exp 1: s 1; break;
case exp 2: s 2; break;
……..
case exp n: s n; break;
defult: s;
}

exp → expression
s → statement
ASSIGNMENTS

//program for finding the highest and lowest number


#include <stdio.h>
int main()
{
int x, y, z;

printf("Enter he three integer numbers:\n");


scanf("%d %d %d", &x, &y, &z);

//this part is for finding the maximum value.


if(x>y){
if(x>z)
printf("%d is the greatest number\n", x);
else
printf("%d is the greatest number\n", z);
}
else{
if(y>z)
printf("%d is the greatest number\n", y);
else
printf("%d is the greatest number\n", z);
}

//this part is for finding the minimum number.


if(x<y){
if(x<z)
printf("%d is the lowest number\n", x);
else
printf("%d is the lowest number\n", z);
}
else{
if(y<z)
printf("%d is the lowest number\n", y);
else
printf("%d is the lowest number\n", z);
}

return 0;
}

//program for finding the vowel consonant.


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

printf("Enter any alphabet: ");


ch = tolower(getchar());
if(ch>='a' && ch<='z'){
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'){
printf("\n%c is a Vowel\n", ch);
}
else{
printf("\n%c is consonant\n", ch);
}
}
else{
printf("\nYou have not entered any alphabet\n");
}
return 0;
}

//program for finding the grade of a student's marks.


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

printf("Enter your mark: ");


scanf("%f", &mark);

if(mark >= 100){


printf("You have entered a wrong value\n");
}
else if(mark >= 80){
printf("\nYour result is A+\n");
}
else if(mark >= 75){
printf("\nYour result is A\n.");
}
else if(mark >= 70){
printf("\nYour result is A-\n.");
}
else if(mark >= 65){
printf("\nYour result is B+\n");
}
else if(mark >= 60){
printf("\nYour result is B\n");
}
else if(mark >= 55){
printf("\nYour result is B-\n");
}
else if(mark >= 50){
printf("\nYour result is C+\n");
}
else if(mark >= 45){
printf("\nYour result is C\n");
}
else{
printf("\nYour result is F\n");
}
return 0;
}

LOOPING

A group of statements is execute repeatedly until some condition has been satisfied.
1. for loop
2. while loop.
3. do-while loop.

THE for STATEMENT

The for statement is the third and perhaps the most commonly used looping statement in C. This
statement includes an expression that specifies an initial value for an index, another expression that
determines whether or not the loop is continued, and a third expression that allows the index to be
modified at the end of each pass.
The general form of the for statement is

for(expression 1; expression2; expression 3) statement

Initialization
Increment/ Decrement
Condition

Example:

THE while STATEMENT

The while statement is used to carry out looping operations, in which a group of statements is
executed repeatedly, until some condition has been satisfied.
The general form of the while statement is

expression 1;
while ( expression 2){
statement
expression 3
}

Initialization Condition Increment/ Decrement

THE do-while STATEMENT


When a loop is constructed using the while statement, the test for continuation of the
loop is carried out at the beginning of each pass. Sometimes, however, it is desirable to have a loop
with the test for continuation at the end of each pass. This can be accomplished by means of the do -
while statement.
The general form of the do - while statement is

expression 1;
do{
statement
expression 3;
} while(expression 2;)

Initialization Condition Increment/ Decrement


ASSIGNMENTS
//program for finding the average of user given numbers.
#include <stdio.h>
int main()
{
int i=0, n;
float sum, average, num;

sum = 0;

printf("How many numbers you want to find sum and average\n");


scanf("%d", &n);

printf("Enter the numbers\n");

do{
scanf("%f", &num);
sum=sum+num;
i++;
}
while(i<n);

average=sum/n;

printf("\nSum=%f\n", sum);
printf("\nAverage=%0.2f\n", average);

return 0;
}

//program for calculate the sum of first n odd integers.


#include<stdio.h>
int main()
{
int i, n, sum=0;
printf("Enter the value of n.\n");
scanf("%d", &n);

if(n>=1){
for(i=1;i<=n;i++){
if(i%2==1){
sum=sum+i;
}
}
printf("\nsum of all odd numbers between %d is %d.\n\n", n, sum);
}
else
printf("You have entered a wrong value. Please enter a positive
integer number.\n");

return 0;
}

THE break STATEMENT

Is used to terminate loops exit from a switch.

Output will be: 0, 1, 2, 3, 4

THE continue STATEMENT

Is used to bypass the reminder of the current pass through a loop.

Output will be: 1, 2, 3, 4, 6, 7, 8, 9, 10

THE nested loop CONTROL


Loops, like if-else statements, can be nested, one within another. The inner and outer loops need
not be generated by the same type of control structure. It is essential, however, that one loop be
completely embedded within the other-there can be no overlap. Each loop must be controlled by a
different index.
Moreover, nested control structures can involve both loops and if - else statements. Thus, a loop can
be nested within an if-else statement, and an if-else statement can be nested within a loop. The
nested structures may be as complex as necessary, as determined by the program logic.
One loop inside
another loop

Output will be:1 2 3 4 5


12345
12345
12345
12345

ASSIGNMENTS

//program for printing a given pattern.


#include <stdio.h>
int main()
{
int i, j, z;

printf("Enter the value of n\n");


scanf("%d", &z);
for(i=1;i<=z;i++){
printf("\n");
for(j=1;j<=10;j++)
printf("%d x %d = %d\n", i, j, j*i);
}
return 0;
}
Output:
//program for printing the star pattern.
#include <stdio.h>
int main()
{
int i, space, rows=5, k;

for(i=1;i<=rows;i++){
for(space=1;space<=rows-i;space++){
printf(" ");
}
for(k=0;k!=2*i-1;k++){
printf("* ");
}
printf("\n");
}
return 0;
}

Output:

Functions
We have already seen that C supports the use of library functions, which are used to carry out a number
of commonly used operations or calculations. However, C also allows programmers to define their
own functions for carrying out various individual tasks.

How it works:
A function is a self-contained program segment that carries out some specific, well-defined task. Every
C program consists of one or more functions. One of these functions must be called main. Execution
of the program will always begin by carrying out the instructions in main. Additional functions will be
subordinate to main, and perhaps to one another.
If a program contains multiple functions, their definitions may appear in any order, though they must
be independent of one another. That is, one function definition cannot be embedded within another. A
function will carry out its intended action whenever it is accessed (i.e., whenever the function is
"called") from some other portion of the program. The same function can be accessed from several
different places within a program. Once the function has carried out its intended action, control will
be returned to the point from which the function was accessed.
Generally, a function will process information that is passed to it form the calling portion of the
program, and return a single value. Information is passed to the function via special identifiers called
arguments (also called parameters), and returned via the return statement. Some functions, however,
accept information but do not return anything (as, for example, the library function printf) , whereas
other functions (e.g., the library function scanf) return multiple values.

Function

ASSIGNMENTS

//program to find x^n by using a function


#include <stdio.h>

//function to calculate the x^n


int power_function(int num, int pow)
{
int sum=1;

for(;pow;pow--){
sum=sum*num;
}

return sum;
}
//main function
int main()
{
int x, y, result;

printf("Enter the base: ");


scanf("%d", &x);
printf("\nEnter the exponential: ");
scanf("%d", &y);

result = power_function(x, y);

printf("\n%d to the power %d is: %d\n\n", x, y, result);

return 0;
}

//program to made function which returns the smallest of three smallest


floating point numbers.
#include <stdio.h>
//function to find the smallest number.
float minimum_value (float x, float y, float z)
{
float minimum;

if(x<y){
if(x<z){
minimum = x;
}
else{
minimum = z;
}
}
else{
if(y<z){
minimum = y;
}
else{
minimum = z;
}
}

return minimum;
}
//main function.
int main()
{
float x, y, z, smallest_number;

printf("Enter the three numbers\n");


scanf("%f%f%f", &x, &y, &z);

smallest_number = minimum_value (x, y, z);

printf("The smallest number is %lf ", smallest_number);


return 0;
}

Array
Many applications require the processing of multiple data items that have common characteristics (e.g.,
a set of numerical data, represented by x1, x2, . . . ,xn). In such situations it is often convenient to place
the data items into an array.
The number of subscripts determines the dimensionality of the array. For example, x [ i ] refers to an
element in the one-dimensional array x . Similarly, y[ i ][ j ] refers to an element in the two dimensional
array y. (We can think of a two-dimensional array as a table, where y [ i ][ j ] is the jth element of the
ith row.) Higher-dimensional arrays can be also be formed, by adding additional subscripts in the same
manner (e.g., z [ i ] [ j ] [ k ] ) .

A one-dimensional array definition may be expressed as


Storage-class data-type array[expression];

Where storage-class refers to the storage class of the array, data-type is the data type,
array is the array name, and expression is a positive-valued integer expression which indicates
the number of array elements. The storage-class is optional; default values are automatic for arrays
that are defined within a function or a block, and external for arrays that are defined outside of a
function.

Data type

Number of array elements


int matrix_1[20][20]

Array name

ASSIGNMENTS

//finding the summation of matrix by array


#include <stdio.h>
int main()
{
int m, n, c, d, matrix_1[20][20], matrix_2[20][20], sum[20][20];

printf("Enter the number of rows and columns of first matrix:\n");


scanf("%d %d", &m, &n);

printf("\nEnter the elements of first matrix (between 1 and 20):\n");


for(c=1; c<=m; c++)
for(d=1; d<=n; d++){
printf("Enter element a%d%d : ", c, d);
scanf("%d", &matrix_1[c][d]);
}

printf("\nEnter the element of second matrix (between 1 and 20):\n");


for(c=1; c<=m; c++)
for(d=1; d<=n; d++){
printf("Enter element b%d%d : ", c, d);
scanf("%d", &matrix_2[c][d]);
}

printf("\nSum of two matrix:\n");


for(c=1; c<=m; c++){
for(d=1; d<=n; d++){
sum[c][d] = matrix_1[c][d] + matrix_2[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

//Finding average by array


#include <stdio.h>
int main()
{
float avg, sum = 0.0;
int num[ 20], n, x;

printf("Enter the number of elements: ");


scanf("%d", &n);
printf("\n\n");
//for loop for receiving inputs and calculating sum.
for (x=1; x<=n; x++){
printf( "Enter element no %d: ", x);
scanf( "%d" , &num[x]);
sum = sum+num[x];
}

avg = sum/n;
printf("\n\nSum : %0.2f\n", sum);
printf( "Average: %0.2f\n" , avg);
return 0 ;
}

You might also like