0% found this document useful (0 votes)
13 views51 pages

Lecture 2 - w1 - HA

This document outlines the fundamentals of computer programming in C, covering topics such as basic syntax, function prototypes, the main() function, preprocessor directives, variables, constants, and input/output functions like printf() and scanf(). It emphasizes the structure of C programs, including the importance of comments, data types, and the use of format specifiers for output. Additionally, it explains how to declare and initialize variables, as well as the significance of constants and user-defined data types.

Uploaded by

mrehan.khan.ceme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views51 pages

Lecture 2 - w1 - HA

This document outlines the fundamentals of computer programming in C, covering topics such as basic syntax, function prototypes, the main() function, preprocessor directives, variables, constants, and input/output functions like printf() and scanf(). It emphasizes the structure of C programs, including the importance of comments, data types, and the use of format specifiers for output. Additionally, it explains how to declare and initialize variables, as well as the significance of constants and user-defined data types.

Uploaded by

mrehan.khan.ceme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

FUNDAMENTALS OF

COMPUTER
PROGRAMMING
WEEK 1: LECTURE # 2

DR. HASIBA ASMA


OUTLINE

• Basics of C Program Syntax


• Function prototype
• Main() function
• Preprocessor directives
• Variables & constants
• Format specifier %
• Printf()
• Scanf()
WHAT THESE LINES OF CODE MEAN
DEALING WITH ERRORS
BASIC STRUCTURE OF C PROGRAMS

#include <stdio.h>
Syntax
void main ( ) • printf is a statement.
• A statement in C is terminated by a semi
{ colon ( ; ) .

printf(“Hello World”);
}
BASIC STRUCTURE OF C PROGRAMS

#include <stdio.h>
Delimiters
void main ( ) • Opening and Closing brace or Curly
brackets marks the start and end of the
{ code
• The start and end of a block ( such as
printf(“Hello World”);
loop, if else statement, switch statement)
} is also identified by the start and end of
curly brackets.
BASIC STRUCTURE OF C PROGRAMS

#include <stdio.h>
Syntax
void main ( ) • C pays no attention to the “whitespace”
characters encountered in a program like
{ space, carriage return(newline) and tab
• You can put as many whitespaces in your
printf(“Hello World”); program as you like; they will be invisible to
the compiler
}
Basic Structure of C programs

#include <stdio.h> Indentation


• Stretching the code vertically makes it
more readable
• Indentation of blocks of code enclosed
void main ( ) in braces is an important aspect for
making the programs readable
{ • e.g. the printf statement that is indented
in the previous example
• The same program below will execute
printf(“Hello World”); perfectly

}
COMMENTS

• Any part of your program that starts with /* and ends with */ is called a comment.
• Look at the first line of code in the preceding example:
• /* Program 1.3 Another Simple C Program - Displaying a Quotation */
• This isn’t actually part of the program code, in that it isn’t telling the computer to do anything.
• It’s simply a comment, and it’s there to remind you, or someone else reading your code, what
the program does.
• Its good to have habit of documenting your programs, using comments as you go along.
• Your programs will, of course, work without comments, but when you write longer programs you
may not remember what they do or how they work.
• Program Output:
• Beware the Ides of March!
UNDERSTANDING THE STRUCTURE
PREPROCESSING DIRECTIVES

• Performed by a program called the preprocessor


• Modifies the source code (in RAM) according to preprocessor directives (preprocessor
commands) embedded in the source code
• Strips comments and white space from the code.
• The source code as stored on disk is not modified.
• Examples:
• # include, macros
PREPROCESSING DIRECTIVES
• The symbol # indicates this is a preprocessing directive, which is an instruction to your
compiler to do something before compiling the source code.
• The compiler handles these directives during an initial preprocessing phase before the
compilation process starts.
• #include <stdio.h>
• In this case, the compiler is instructed to “include” in your program the contents of the file
with the name stdio.h.
• This file is called a header file, because it’s usually included at the head of a program.
PREPROCESSING DIRECTIVES
• In this case the header file defines information about some of the functions that are
provided by the standard C library i.e., printf() function.
• So you have to include the stdio.h header file.
• This is because stdio.h contains the information that the compiler needs to understand what
printf() means, as well as other functions that deal with input and output.
• As such, its name, stdio, is short for standard input/output.
• All header files in C have file names with the extension .h.
• But, in general, header files specify information that the compiler uses to integrate any
predefined functions or other global objects with a program.
The main() Function

• Every C program consists of one or more functions, and every C program must contain a function called
main()—the reason being that a program will always start execution from the beginning of this function.
• So imagine that you’ve created, compiled, and linked a file called progname.exe.
• When you execute this program, the operating system calls the function main() for the program.

• int main(void)
• This defines the start of the function main().
• Notice that there is no semicolon at the end of the line.
• The first line identifying this as the function main() has the word int at the beginning.
• What appears here defines the type of value to be returned by the function, and the word int signifies that the
function main() returns an integer value.
The main() Function

• You end execution of the main() function and specify the value to be returned in the statement:
• return 0; /* This returns control to the operating system */
• This is a return statement that ends execution of the main() function and returns that value 0 to the operating
system.
• You return a zero value from main() to indicate that the program terminated normally; a nonzero value would
indicate an abnormal return.

• The parentheses that immediately follow the name of the function, main, enclose a definition of what
information is to be transferred to main() when it starts executing.
• In this example, however, you can see that there’s the word void between the parentheses, and this
signifies that no data can be transferred to main().
BASIC STRUCTURE OF C PROGRAMS

#include <stdio.h> void main ( )


• Every C program consists of one or more
functions.
• main ( ) is a function. It is the first function to
void main ( ) which control is passed from OS when a program
is executed
{ • void indicates that the main function does not
return any value
printf (“Hello World”);
}
FUNCTION PROTOTYPE & DEFINITION

• A function prototype provides the C compiler with the name and arguments of the functions contained in a program.
• It must appear before the function is used.
• Syntax:
• return_type function_name(arg_name1,…..);

• A function definition is actual function. An independent, self contained section of code that is written to perform a certain
task.
• Syntax:
• return_type function_name( arg_name1,……)
• {
• /*statements*/
• }
• Every function has a name, and the code in each function is executed by including that function’s name in a program statement.
• This execution is known as calling a function.
FUNCTION PROTOTYPE & DEFINITION

• A function prototype provides the C compiler with the name and arguments of the functions contained in a program.
• It must appear before the function is used.
• Syntax:
• return_type function_name(arg_name1,…..);

• A function definition is actual function. An independent, self contained section of code that is written to perform a certain
task.
• Syntax:
• return_type function_name( arg_name1,……)
• {
• /*statements*/
• }
• Every function has a name, and the code in each function is executed by including that function’s name in a program statement.
• This execution is known as calling a function.
Keywords & Identifiers

• Keywords are the reserved words used in programming. Each keywords has fixed meaning and that
cannot be changed by user. They are also known as reserved words.
• As, C programming is case sensitive, all keywords must be written in lowercase. Here is the list of all keywords
predefined by ASCII C.
• Identifiers
• In C programming, identifiers are names given to C entities, such as
variables, functions, structures etc.
• Identifier are created to give unique name to C entities to identify it during
the execution of program.
VARIABLES & DATA TYPES
VARIABLES

• A variable is a named data storage location in your computer’s memory.


• By using a variable’s name in your program, you are, in effect, referring to the data stored
there.

• Rules for naming variables:


• The name can contain letters (upper & lower case), digits, and underscore character (_) only.
• The first character of the name must be a letter. The underscore is also legal first character,
but its use in not recommended.
• C keywords cant be used as variables names.
DATA TYPES

• In C, variable(data) should be declared before it can be used in program.

• Data types are the keywords, which are used for assigning a type to a variable.

• Data types in C
• Fundamental Data Types
• Integer types
• Floating Type
• Character types
• Double
• Void

• Derived Data Types


• Arrays
• Pointers
• Function

• User defined Data types


• Structure
• Enumeration
• Union
INTEGER VARIABLES

• An integer is any whole number without a decimal point.


• int salary; /* Declare a variable called salary */
• This statement is called a variable declaration because it declares the name of the variable. The
name, in this program, is salary.
• The variable declaration also specifies the type of data that the variable will store.
• int x,y,z; /* Variables declaration in single line */
UNSIGNED INTEGER TYPES

• Unsigned integer types are used when you are dealing with values that cannot be
negative.
FLOATING-POINT VALUES

• Floating-point variables are used to store floating-point numbers. Floating-point numbers


hold values that are written with a decimal point.
INITIALIZING VARIABLES

• When you declare a variable, you instruct the compiler to set aside storage space for the variable.
• However, the value stored in that variable isnt defined.
• It might be zero, or it might be some random “garbage” value.

• Before using a variable, you should always initialize it to known value.


• You can do this independently of variable declaration
• int count; /* Set aside storage space for count */
• count = 0;

• Or along with it.


• int count=0;
INITIALIZING VARIABLES

• Examples
• int num=2;
• int char=‘d’,
• float length=34.5677;
• By initializing a variable we provide:
• Declaration of variable
• Definition of a variable
• Initial value loaded in the variable
CONSTANT

• Like a variable, a constant is a data storage location used by your program.


• Unlike a variable, the value stored in a constant can’t be changed during program execution.
• C has two types of constants:
• Literal Constants: It is a value that is typed directly into the source code where ever it is needed.
e.g.
• int count = 20;
• float tax_rate=0.20;
• Symbolic Constants: It is a constant that is represented by name (symbol) in your program.
• Like a literal constant, a symbolic constant can’t change.
• The actual value of the symbolic constant needs to be entered only once, when it is first defined.
CONSTANT

• A constant starting with any digit other than 0 is interpreted as a decimal integer.
• A constant starting with the digit 0 is interpreted as an octal integer (the base 8). e.g. 015
• A constant starting with 0x or 0X is interpreted as a hexadecimal constant (bas 16). e.g. 0x1ae

• Long constants are written with a trailing L e.g. 890L.

• C has two methods for defining a symbolic constant.


• The #define directive
• Syntax:
• #define constname literal
• #define PI 3.14159
• const keyword:
• const is a modifier that can be applied to any variable declaration.
• const char count =‘Z’;
• const long debt= 1200000, float tax_rate=0.2;
User Input and output functions

• The printf() function is used to display output on the


screen

• The scanf() function is used to read input from the


keyboard

• printf() and scanf() both are defined in stdio.h called


header file which we include using:
# include <stdio.h>
THE PRINTF() FUNCTION

• Printf() is a function like main()


• It caused the string written within the quotes “ ” inside printf() function on the screen
• The string which is phrase in quotes is the function argument passed to printf()
• “Hello World” is a string of characters. C compiler recognizes a string when it is
enclosed within quotes.
THE DEFINITION OF PRINTF() AND SCANF()
FUNCTIONS
• We have called the function printf() but have not defined it anywhere
• The declaration is done in the header file called stdio.
• Its definition is is provided in a standard Library which we will study later on.
• The linker links our program with the ***.lib file at the time of linking. This happens for all
C library functions
• Remember the name of a function is like variable name also called an identifier.
EXPLORING THE PRINTF() FUNCTION

• Printing numbers (integers)


void main (void)
{
printf (“Printing number: %d”, 10);
}
Here printf took two arguments:
Printing number --- argument 1
10 ( what is that ? )--- argument 2
what is %d ---- Format specifier
DISPLAYING OUTPUT

• The printf() Function:


• The printf() function is part of the standard C library.
• Two arguments are passed to printf().
• The first argument is enclosed in double quotation marks and is called the format string.
• The second argument is the name of variable containing the value to be printed.

• Here are the three possible components of a format string:


• Literal text: is displayed exactly as entered in the format string. e.g. printf(“An error has
occurred!”);
• An escape sequence provides special formatting control. An escape sequence consists of a backslash
followed by a single character. e.g. printf(“The value of x is 10\n”);
DISPLAYING OUTPUT

• Common escape sequences are:

• A conversion specifier consists of the percent sign followed by a character. e.g. %d is used for integers.
• printf(“\n The value of y is %d”, y);
/* DEMONSTRATION USING PRINTF() TO DISPLAY
NUMERICAL VALUE */
• #include <stdio.h>
• int a=2, b=10, c=50;
• float f=1.05, g= 25.5, h= -0.1;
• int main ()
• {
• printf(“\nDecimal values without tabs: %d %d %d”, a, b, c);
• printf(“\nDecimal values with tabs: \t%d \t%d \t%d”, a, b, c);
• printf(“\nThree floats on 1 line: \t%f\t%f\t%f”, f, g, h);
• printf(“\nThree floats on 3 line: \n\t%f\n\t%f\n\t%f”, f, g, h);
• printf(“\nThe rate is %f%%”,f);
• printf(“\nThe result of %f/%f=%f\n”, g, f, g/f);
• return 0;
• }
/* DEMONSTRATION USING PRINTF() TO DISPLAY
NUMERICAL VALUE: OUTPUT */
• Decimal values without tabs: 2 10 50
• Decimal values with tabs: 2 10 50
• Three floats on 1 line: 1.05000 25.00000 -0.100000
• Three floats on 3 lines:
• 1.050000
• 25.50000
• -0.100000
• The rate is 1.05000%
• The result of 25.500000/1.050000= 24.285715
FORMAT SPECIFIERS

• Tells the compiler where to put the value in string and what format to use for printing
the value

• %d tells the compiler to print 10 as a decimal integer

• Why not write 10 directly inside the string?


• Possible !! However, to give printf() more capability of handling different values, we use format
specifiers and variables
Specifier Meaning Types Converted
%c Single Character char
%d Signed decimal integer int, short
%ld Signed long decimal integer long
%f Decimal floating- point number float, double
%s Character string char arrays
%u Unsigned decimal integer unsigned int, unsigned
short
%lu Unsigned long decimal integer unsigned long
FIELD WIDTH SPECIFIERS

Format specifier: %(-)w.nf


• f is a format specifier used for float data type
e.g %f
• .n means number of digits after decimal point
e.g %.2f 27.25 & %.3f means 27.250
• The digit (w) preceding the decimal point specifies the amount of space that number will use to get
displayed:

e.g printf (“Age is % 2d” 33); 33


printf (“Age is % 4d” 33); - - 33
printf (“Age is % 6d” 33); - - - - 33
PRINTING STRINGS USING PRINTF () FUNCTION

• void main (void)


• {
• printf(“%s is %d years old”,”Ahmed”,22);
• }
PRINTING CHARACTERS USING PRINTF ()
FUNCTION
• void main (void)
• {
• printf(“%c is pronounced as %s”, ’j’, ”jay”);
• }

• Single quotes are for character whereas the %c is format specifier

• Double quotes are for strings whereas the %s is format specifier


INPUTTING DATA WITH SCANF()

• The scanf() function is another function that requires the <stdio.h> header file to be
included.
• This function reads data from the keyboard according to a specified format and assign
the input data to one or more program variables.
• Syntax of scanf function is
scanf (“format string”, argument list);
• scanf(“%d”, &x); /*Takes int value of x from keyboard*/
• The & symbol is C’s address of operator.
SCANF() FUNCTION

void main (void)


{
int userAge;
printf(“Enter the the age: ”);
scanf(“ %d”, &userAge);
}

• scanf() reads in data and stores it in one or more variables.


• The first argument (the control string), contains a series of placeholders
• The remaining arguments to scanf() is a variable name proceed with & sign called address
operator
scanf() can read data into multiple variables

int a, b,
float c;
char d;
scanf(“ %d %d %f %c” , &a, &b, &c, &d);

• Input is stored in these variables. Each variable name is preceded


by & , &a means “the memory address associated with variable a”

• It uses any whitespace (space, newline or tab) character to delimit


inputs in case of multiple inputs

• Format specifiers are like the ones that printf() uses


e.g. %d = int, %f = float, %c = char, etc.
COMMENTS

• /* --------------------*/ multiline comments

• // single line comments

You might also like