36
Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Introduction to ICT & Programming LAB : C Basics, Variables, Data types

  • View
    246

  • Download
    6

Embed Size (px)

Citation preview

Page 1: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Introduction to ICT & Programming

LAB : C Basics, Variables,

Data types

Page 2: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Agenda

C Basics Variables / Data Types Input / Out Put Functions

Page 3: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics All C programs are made up of one or more functions, and

main( ) will always represent the starting point of execution By definition, a function is a subprogram within a program

designed to carry out a particular task and perhaps return a value to the calling function.

A function can call other functions which may also call other functions

main( ) will always be included and will begin program execution

All programs written in C follow a general structure. Include statements and other global identifiers ( constants,

user-defined types ) will be placed at the beginning of a C source file.

Page 4: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics The include statements are pre-precessor directives that

"include" code stored in other source files to be used in the program.

This provides for a convenient way of "including" the same code in many programs rather than writing the same code for each program that needs it.

Immediately following the global section of a source file, the mandatory main( ) function will appear.

This marks the beginning of program execution and the flow of the program will branch out and be generally controlled by main( ).

The definitions of additional functions that the program needs and uses will be placed after the main( ) function definition.

Inside both main( ) and additional user-defined functions are executable statements that are terminated by a semi-colon.

Page 5: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics

C terminates every executable statement with a semi-colon to simply denote that it is a executable statement that gives an instruction to the CPU (central processing unit) of a computer

C's syntax, which is the rules governing the formation of statements in a programming language

By syntax we mean the specific language (code) used to turn algorithms into programs and specific rules followed when programming in C.

A programming language's syntax is critical because programs will not compile until code is syntax-error free

However, a program will run even though it may contain logic errors; these errors occur during program execution (but don't cause a crash) and must be recognized during testing

Page 6: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics Curly braces are used to mark the beginning and end of "block"

statements or function definitions. For example, consider:

main( ){     /* beginning curly brace */

}     /* end curly brace */

A function will always be given a name, either user-defined or "built-in", and will have a pair of parentheses attached to the end of its name

The parentheses actually make up a function's argument list Variables that need to be "passed" into or "sent" to the function

are placed inside the argument list

Page 7: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics Programmer comments are placed within program code using the /*      */

statement with programmer remarks inserted between the start and end backslash / asterick grouping

Comments allow for documentation within a source file. Using comments is extremely crucial when developing well-structured

complex programs, and it is good programming practice to always place comments in program code

All executable statements will be made up of user-defined elements and "built-in" elements.

User-defined elements refer to statements that you as the programmer create to handle and solve particular problems.

"Built-in" elements refer to statements and functions previously defined in C, normally by the compiler developers, that the programmer can use by simply "calling" or specifying in programs.

There are many "built-in" functions in C. There are also "built-in" keywords that have meaning in C to handle certain conditions.

Keywords allow for the definition of data types, control structures, and much more

Page 8: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics ANSI C KEYWORDS

autobreakcasecharconstcontinuedefaultdodoubleelseenumstruct

externfloatforgotoifintlongregisterreturnshort

signedsizeofstaticswitchtypedefunionunsignedvoidvolatilewhile

Page 9: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

C Basics

Common Programming ErrorsThere are basically two types of errors in programming:– syntax – Logic

Syntax errors occur when programs fail to compile because the programmer has mistakenly ignored a rule that must be followed with writing code statements– An example would be not terminating a executable statement

with a semi-colon or giving a variable the same name as a keyword

Logical errors Logical errors occur when programs successfully compile but do not behave or solve a particular problem correctly – Logical errors are harder to find and correct simply because you

will not notice them until performing program testing

Page 10: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types Data types are fundamental to any programming language Knowing how to create variables and name them wisely is

important, but so is knowing how to use them.

What exactly is a data type? Remember that variables and the information you want them to

hold are formatted in a way that makes it easy for you to read, understand, and use.

The computer is not concerned with the names or values associated with your variables.

It operates with specific memory locations and the bits and bytes stored there, nothing more.

When you tell the computer to print a variable that holds 'a', you are instructing it to access a particular memory location, retrieve the binary data stored there, and present it to you as the ASCII character 'a'.

Page 11: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types If you want to access the same memory location, but have

it print just the hexadecimal value of the data. Understand that the computer doesn't care how you wish

to see what's returned to you. All you have to do is tell it what you want, and it'll do it Since you don't want to do that every single time you need

a variable, programming languages build it in by using data types.

Data types are a way of imposing order on the way data is handled when the computer has to present it to you.

Every variable has a type, such as 'numeric' or 'string', and those types are broken down even further.

(Objects and arrays are also data types but they're a little different, so we won't be covering them here.) .

Page 12: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Data types are critical because they each have specific rules and expectations associated with them.

If you want to use them correctly, you need to understand how they work

Data types are not set by programmers, they are given to you by the language you use.

Some languages do allow you to create your own data types.

But even if the language does allow it, any data types you create are based on fundamental types specified by the language

Page 13: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Identifiers– Identifiers are the names used when you program. They can be

variable or function names, and are set by programmers.

Literals– A literal is another name for raw data. A string such as "hello

world" is a string literal. The number 77 is a number literal. – When we're talking about literals, its "What You See Is What

You Get". Literally.

Constants– A constant is a value that never changes. Its easy to understand

that when you think of things like the value of pi (approximately 3.14), When you declare a constant, you are declaring that its value shall remain unchanged within your script.

Page 14: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Variable Names

– Valid names can consist of letters, numbers and the underscore, but may not start with a number.

– A variable name may not be a C keyword such as if, for, else, or while.

– Variable names are case sensitive. So, Age, AGE, aGE and AgE could be names for different variables, although this is not recommended since it would probably cause confusion and errors in your programs.

Page 15: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Which of the following are valid variable names?

int idnumber;      Valid

int transaction_number;      Valid

int __my_phone_number__;     Valid

float 4myfriend;     Not valid, variable names cannot start with a number

float its4me;     Valid

double VeRyStRaNgE;     Valid

float while;    Not valid, "while" is a C++ keyword

float myCash;     Valid

Page 16: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

These three are valid variable names. However, it is recommended to avoid using names that differ only in case since this practice leads to confusion and program errors.

int CaseNo;int CASENO;int caseno;

Page 17: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Numbers and Strings

Strings– A string holds textual information and includes anything within

quotation marks, even if they're numbers. – In other words, “hello", "2.409", and "2 + 2" are all considered to

be strings. – However, in some cases you may get unexpected results

Numbers– Numbers are "the stuff you do math with". Yeah, OK, you knew

that. But numerics are broken down into several types, so lets see what they are.

Page 18: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types Integers Floats Booleans

Page 19: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types Every program works with some form of data, either

numerical or character; Computers are capable of working with data through the use of variables.

Variables have an associated memory location inside a computer, and their value can be modified. It is important to note that the memory location of a variable stays constant throughout program execution; its value can change, and the memory location allows the computer to "look up" the variable in order to manipulate it. For example, consider a program used to calculate the average of three

numbers. In the program code, there should be four variables: num1, num2, num3, and average. During execution of the program, the compiler will give each of the variables a memory location in the memory of the computer. If the variables are not set to a default value in the program, as they are placed into memory they will be assigned some type of garbage value until that value is changed during execution of the program

Page 20: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types In order to use a variable in a program, you must tell the computer

which type of data it will be used to store (using a declaration statement).

Here are three basic C types: int, float, and char. – int is used for whole numbers without decimal points, – float is used for real numbers with decimal points, – and char is used for keyboard character or letter values.

When declaring variables, you will need to specify a data type. You are letting the compiler know what type of data it is going to

be working with In C, data is either integral (integers and characters) or floating-

point. Characters are considered integral because character values will

eventually be converted into an ASCII (American Standard Code for Information Interchange), which is a system designed to associate character values with numerical values, value.

There is also a bool (boolean) type. Boolean types can be used when using logical data; when something can be either true or false

Page 21: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types There are several possible sizes and for some of these data types

there is a choice of unsigned or signed types. Signed simply means that the data can be negative or positive. Unsigned means the data will be strictly positive. In the following list, the sizes are representative only (compiler dependent).

Char 1 byte -128 to 127 unsigned char 1 byte 0 to 255 int 2 bytes -32,768 to 32,767 unsigned int 2 bytes 0 to 65,535 long or (long int) 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295 float 4 bytes 3.4 x 10^-38 to 3.4 x 10^38 double 8 bytes 1.7 x 10^-308 to 1.7 x 10^308 long double 10 bytes 3.4 x 10^-4932 to 3.4 x 10^4932

Page 22: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Variable names must be begin with a letter, and then continue to be letters, digits, and underscores.

Variable names should always be very descriptive and relate to the data it is used to store– For example, suppose I need a variable to store the grade of a student in a

class; a possible descriptive variable name would be studentGrade.

Descriptive names allow for easier program logic and easier updating routines, and they are critical when developing complex programs.

C's standard library (preprocessor directives) defines variable names using an initial underscore so try to stay away from giving variables names beginning with underscores.

Page 23: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

ValidstarTrekstu_First_MathtestScore1

Invalidzook$     /* no dollar signs */1dude     /* must begin with letter */my Name     /* cannot contain spaces */

You must declare a variable before using it in a program. The form for declaring a variable is as follows:

data-type identifier;

** where data-type is a data type from the listing above and identifier is the name of the variable

Page 24: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types The declaration statement simply defines the "type" of the

variable and lets the compiler know the "type" of data it will be used to store.

After declaration, the variable will hold a garbage value, which is an extreme value given by the CPU whose only use is to occupy memory storage until the variable is given a "true" value during program execution

Few declaration examples, consider:

        int num1;        float num2;        char letter;

Page 25: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types

Initialization is different from declaration because you will declare the variable and also give it an initial value. The initialization statement form is as follows:

    data-type identifier = value; Where data-type is naturally one of the data types

described above, identifier is the name of the variable, and value is the variable's initial value. For a few initialization examples, consider:

        int num1 = 123;        float num2 = 56.78;        char letter = 'a';

Page 26: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Variables & Data Types You can also initialize a variable constant. The form for named

constants is: const data-type identifier = value; (where value is a literal)

The initializing is the same except for the preceding const keyword

When defining a variable as const, the variable's value cannot change during program execution.

If the program tries to change its value, an error will occur Constants are commonly used when sharing the same data

for many different elements in a program. They also allow for easier program updating.

– For an example, consider:

    const int MAXSIZE = 450;

If we ever need to change MAXSIZE, which may be designed for numerous structures, we could simply change the value one time instead of manipulating each structure.

Page 27: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Preprocessor Capabilities

The preprocessor provides for very efficient instructions to take place before any program code is actually compiled

They are also considered to be executed during compile time rather than during run-time execution. The form of a preprocessor statement is as follows:

    #define variableName value

where variableName is the name given to the constant value, and value is the value assigned to variableName

The pound symbol ( # ) is a giveaway that it is a preprocessor statement.

The above form is used to define symbolic constants in programs.

Page 28: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Preprocessor Capabilities Symbolic constants specify values which cannot change during

program execution. The basic idea of using symbolic constants is to give descriptive

names to constant values that are normally used many times throughout the program. In turn, this makes updating the values of the constants very easy to accomplish in the future

We have previously used the preprocessor statement to "include" or "link" other C files through the use of an #include statement at the very beginning of a program.

The #include preprocessor statement searches a specified number of directories in search of the "target" file to be "linked" with the program.

The #include statement provides a convenient way of using practical functions with programs without the need to write the code for each program; "include" the file containing the practical code and then use the needed functions. There are two forms for the #include statement:

   

Page 29: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Preprocessor Capabilities  #include <file>

 #include "file“ The angle brackets form < > represent files that are

normally created by the compiler developers and only search for the file in specified directories.

The quotes " " form is normally used for user-defined header files and normally only search for the file in the current directory

Page 30: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Input / Output Statements Getting input from the user of a program and displaying output by the program This involves using two "built-in" member functions: printf( ) and scanf( ). printf( ) and scanf( ) allow for the interaction between the user and the actual

program printf( ) is used to "print" information or "send" information to the output stream scanf( ) is used to "grab" or "store" information inputted by the user during

program execution

printf( ) printf( ) function is used to display information (output). This is done by placing the information to be displayed inside the parentheses

of the function using a list of arguments. The printf( ) will interpret the arguments and display results accordingly. The

form of the printf( ) function is as follows:

    printf( controlString, [argument1, argument2, ...] );

where controlString is a string made up of characters to be printed and conversion specifiers describing variables that need to be printed in specific regions, and [argument1, argument2, ...] is a list of arguments, which may be variables, constants, or expressions, ordered in the way they should appear in controlString; the way they will eventually appear in the true form of output.

Page 31: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Input / Output Statements For a first example, consider:

#include <stdlib.h> #include <stdio.h> int main( ) { printf("Hi, do only geeks master C?"); return EXIT_SUCCESS; } Output produced: Hi, do only geeks master C?

Notice that the data to be displayed was sent to printf as an argument string

Situations arise when a programmer needs to display the values of variables using the printf function.

This requires a different form and use of format or conversion specifiers

Page 32: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Input / Output Statements#include <stdlib.h> #include <stdio.h> int main( ) { int number1 = 115; printf("The value of variable number1 is: %d", number1); return EXIT_SUCCESS; }

Output produced:

The value of variable number1 is: 115

Changes made in the above code segment to handle the variable named number1. The control string still remains in quotes (as a string) but %d was placed inside, and number1 was placed as a second argument succeeding the control string argument with separation between the two arguments using a comma

This general form will be used when needing to display the values of variables using the prinf( ) function

Page 33: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Input / Output Statements Conversion Specifiers

    %d   --> display digit    %f    --> display floating point number (decimal point values)    %c   --> display character value    %s   --> display string    %u   --> display unsigned types    %ld  --> display digit of type long    %i    --> display signed decimal integer    %p   --> display pointer

Since printf( ) is a function, it must return a value. It actually returns the value of the number of characters it printed or a negative value if an error occurred. When using the printf( ) function, there are certain ASCII characters that are considered "nonprinting", which mean they cannot be explicitly included in code. Examples are backspacing, dropping to next line, generating a horizontal tab, etc. To use these "nonprinting" character values in your programs, you will have to make use of a set of C escape symbols.

Page 34: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Input / Output Statements

The following is a listing of escape symbols:

\a     --> sounds an alert\b     --> backspace\n     --> newline character\r     --> carriage return\t     --> horizontal tab\v     --> vertical tab\\     --> displays backslash\'     --> displays single quote character\"     --> displays double quote character

Page 35: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Example#include <stdlib.h>

#include <stdio.h>

int main( )

{

int stuId = 115;

char stuGrade = 'A';

float stuScore = 93.45;

printf("Student %d earned a total score of %f and received a letter grade of %c.", stuId, stuScore, stuGrade);

return EXIT_SUCCESS;

}

Output Produced:

Student 115 earned a score of 93.45 and received a grade of A

Page 36: Introduction to ICT & Programming LAB : C Basics, Variables, Data types

Thank You

Thank you