Synapseindia dot net development introduction to programming

Page 1

Introduction to Programming with C


Computer Basics •

CPU: Commonly known as the processor, “runs” everything on the computer.

Memory: All programs and their data are contained in memory –

Main, commonly known as RAM

External, USB, CDs, Hard drives etc.

OS: Interface between the user and the computer’s resources –

We will not be dealing with other types of memory e.g. registers, cache, virtual/page etc.

Mac, Windows, Unix etc.

Compiler: Converts programs written in high level languages into machine instructions / executable programs


C Program Development Cycle

Edit Program Source Code

Compile Object Code

Library Files

Link Object Code

Executable Code


DevC++ IDE •

To accomplish all parts of C program development cycle, we will use the DevC++ IDE (Integrated Development Environment).

http://www.bloodshed.net/dev/devcpp.html

This is a free software under the GNU General Public License.

link to Sourceforge download site.

Use default install options.


A brief history of C •

Created by Dennis Ritchie at Bell Labs in 1972 Originally created to design and support the Unix operating system. C compilers are available for virtually every platform In 1983 the American National Standards Institute (ANSI) standardized C to be called ANSI Standard C. ANSI C programs that you write should work with any ANSI C compiler.


Our First C program /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0;


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { •

This is a comment printf("Hello World! \nThis is the first program of COP

3223H\n"); •

The compiler ignores everything between /* and */

Itsystem("pause"); helps reader to understand what is written in the “code”.

return 0; An essential part of programming.

}


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { • •

printf("Hello World! \nThis is the first program of COP 3223H\n");

This is called a pre-processor directive system("pause");

Pre-processor directives start with a ‘#’ sign return 0;

}

Tells the compiler to “include” a library file called stdio.h for our HelloWorld.c program After it is included, we can use all the features / functionalities provided by stdio.h in our program Notice that there is no space between # and include


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { •

} • •

printf("Hello World! \nThis is the first program of COP 3223H\n");

This is the start of definition of function main, also called the header of system("pause"); function main return 0;

All C programs MUST have a function named “main” Execution of a program starts from the function main Functions return some value, in our program int is the return type of function main. Write “void” of they don’t return any value. () contains a list of parameters passed to a function separated by commas. Parameter list of our program is empty. We can also write “void” in the parameter list but an empty parameter list is automatically considered void.


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { •

} •

printf("Hello World! \nThis is the first program of COP 3223H\n");

The pair of curly braces identifies the start and the end of function main’s system("pause"); definition return 0;

Mandatory for any function definition This pair of curly braces is also used for other code blocks that we will study later


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { • •

printf("Hello World! \nThis is the first program of COP 3223H\n");

This is a call to function named printf which is defined in stdio.h system("pause");

printf function prints a string enclosed within a pair of double quotes return 0;

}

The characters \n are not printed on screen. They are called escape sequences. \n tells the computer go to new line

More on escape sequences later


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { • •

}

printf("Hello World! \nThis is the first program of COP 3223H\n");

The function “system” is also defined in stdio.h file system("pause");

Passing the string “pause” causes the computer to pause execution at this line return 0; until a key is pressed on the keyboard.


Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */

#include <stdio.h>

int main() { •

} • •

printf("Hello World! \nThis is the first program of COP 3223H\n");

This statement tells the computer to exit function main and return 0 to the system("pause"); program from where it was called. return 0;

Returning 0 from main signals successful execution of function main. The returned value of a function must be the same as its return type. If you return a value other than an int in HelloWorld.c, it will cause a compilation error. Finally: Every program specifies instructions for execution in the exact order without ambiguity.


Running HelloWorld.c


Variables •

Almost all programs manipulate data

To process it, a program needs to store data

Different types of variables allow the storing different types of data, hence the name “Data Types” E.g. if you had to store the numbers 10 and 10.0, C provides two different data types.


How do Variables work •

All variables have three components –

A name

An address

A value that it can hold

When we declare a variable like –

int temp;

The compiler gets space for an integer (4 bytes) allocated for this variable

This memory space has an address, which is also accessible to your program

When we initialize this variable like –

temp = 125; The compiler stores the integer number 125 in the memory space allocated for the variable temp Here, “=“ is an assignment operator, which assigns values to variables


After declaration Variable name

temp

After initialization Variable name

temp

int temp; Variable address

2000

Memory address Memory contents

2000

temp = 125; Variable address

2000

Memory address Memory contents

2000

125


Some Naming Conventions •

Names with leading and trailing underscores are generally used for system purposes.

#define constants should be in all CAPS.

Enum constants are Capitalized or in all CAPS

Function, typedef, and variable names, as well as struct, union, and enum tag names should be in lower case.

Avoid names that differ only in case, like sum and Sum.

Avoid names that look like each other. ‘1’ and ‘l’


Variable Names •

Variable names can contain letters, digits and underscores

The first character must be a letter or an underscore –

the underscore can be used as first character but avoid this!!

Case matters! int temp is not the same as int Temp or int TEmp

C keywords cannot be used as variable names. –

mycarname, hello, y2k, r2d3, ...

/* OK */

_2013_tax_return

/* OK but avoid*/

Hello#Cprogrammer

/* illegal */

double

/* will not work */

2lazytocode

/* illegal */


/* Muhammad Faisal Amjad program to try out different types of variable names: see what works and what doesn't COP 3223H - Spring 2014 */ #include <stdio.h> int main() { int my_car_model = 2002; int numberofstudents; int _2013_tax = -1500; int 2lazytocode = 1; int double = 35000; int hello#CProgrammer = 0; printf("Success..... Now I know how to name variables\n");

}

system("pause"); return 0;


Variables – basic data types •

We will study the C data types in detail later. Lets focus on the basics of variables. There are only a few basic data types in C

char: a single byte, holds one character e.g. the letter ‘a’, although they are stored as integer values standardized as ASCII numbers

int: an integer of fixed length, usually 4 bytes / 32 bits. E.g. the number 10 can be stored in a variable of type int.

float: single-precision floating point. e.g. the number 10.67


Variable declaration •

Generic Form –

typename varname1, varname2, ...;

Examples: –

int count;

float a, b, c;

Where declarations appear affects their scope –

Declaration outside of any function are for global variables

e.g., just before the main function


Variable declaration and Initialization •

ALWAYS initialize a variable before using it –

Examples: –

int count; /* This is declaration, sets aside storage space for count */

count = 100; /* This is initialization, stores 100 in the variable count */

Declaration and initialization can be combined: –

Failure to do so in C is asking for trouble, unexpected values

int count = 0, distance = 20;

“Out of range errors”


Practice with variables •

Write a program to practice declaring variables

Write a program to practice initializing variables

Write a program to see the contents and addresses of variables with and without initialization Write a program to practice swapping contents of variables


Simple output and input with printf and scanf


Output with printf() •

As we have seen earlier, printf() function has the following syntax: –

printf(format string, arg1, arg2, …);

E.g. printf("Hello World! \nThis is the first program of COP 3223H\n");

The text including the pair of double quotes is the format string

We can print the values of variables using conversion specifiers and their corresponding arguments in the arguments’ list

The format string contains: –

Literal text: is printed as is

Escaped sequences: special characters preceded by \ e.g. \n

Conversion specifiers: % followed by a single character •

Indicates (usually) that a variable is to be printed at this location in the output stream.

The variables to be printed must appear in the parameters to printf following the format string, in the order that they appear in the format string.


Common C escape sequences Escape sequence \a \b \n \t \\ \' \" \0

Meaning

alarm or a beep Backspace New line Horizontal tab Backslash Single quotation mark Double quotation mark ASCII 0x00 (null terminator)


Common C conversion specifiers Specifier %c %d %x %f %e %s %u %% %ld, %lld

Meaning Single character Signed decimal integer Hexadecimal number Decimal floating point number Floating point in “scientific notation� Character string (more on this later) Unsigned decimal integer Just print a % sign long, and long long


Input with scanf() •

The scanf() function is the input equivalent of printf defined in the <stdio.h> library file

Takes a format string and parameters, much like printf

The format string specifiers are the same as printf

Examples: –

printf(“Enter the number of days");

scanf(“%d", &days);

/* prompt user for input */

/* reads a decimal integer */

The ampersand (&) is used to get the “address” of the variable

The printf() prints the string “Enter the number of days ”

And then scanf() waits for the user to input an integer

Stores the input value at the address of the variable days

One scanf() function call can read more than one values


/* Muhammad Faisal Amjad program to try out printf and scanf functions COP 3223H - Spring 2014 */ #include <stdio.h> int main() { int days = 0; float dist_to_work = 0; float weekly_travel = 0; printf("Enter the distance in miles from your home to work place: "); scanf("%f", &dist_to_work); printf("Enter the number of days you go to work: "); scanf("%d", &days); weekly_travel = days * dist_to_work; printf("You travel %.3f miles to and from work in a week\n\n", weekly_travel);

}

system("pause"); return 0;


Practice with variables, printf and scanf •

Write a program to calculate the amount of interest paid for house mortgage. Ask user to input –

Loan amount

Interest rate (assume simple interest)

Output: Interest paid, total amount paid to bank.


Programming Style and structure •

A good time to have a look at how your code “looks”

Programming style refers to the layout of your code

A program will be read by someone

It should be easy to read with appropriate white spaces

Use indentation

Arrange your code in appropriate code blocks contained within a matching pair of curly braces { and }

Be careful about variable within code blocks, the scope of variables matters

Variable should be given meaningful names –

E.g. consider

int n;

and int num_of_students;

Use comments at appropriate places –

Beginning of your program called header comment


#include <stdio.h> int main(void) {printf("Hello, World!\n");return 0;} #include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; }

#include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; }

/* Muhammad Faisal Amjad program to print “Hello World!� on standard output COP 3223H - Spring 2014 */ #include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; }


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.