0% found this document useful (0 votes)
4 views

C_chapter_02

This document serves as an introduction to C programming, covering the basics of writing and running C programs, including the use of printf and scanf functions. It explains the structure of a C program, variable types, and the process of compiling code. Additionally, it discusses operators, expressions, and formatted console output, providing examples for clarity.

Uploaded by

basarenkov
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)
4 views

C_chapter_02

This document serves as an introduction to C programming, covering the basics of writing and running C programs, including the use of printf and scanf functions. It explains the structure of a C program, variable types, and the process of compiling code. Additionally, it discusses operators, expressions, and formatted console output, providing examples for clarity.

Uploaded by

basarenkov
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/ 40

A Quick Introduction to C Programming

&
printf and scanf Functions

Software Systems Lab

2020

1
What is a program
 A sequence of instructions that a computer can
interpret and execute;
 If I tell you the way from Chib Plaza to Executive Block … I
will tell sequence of instructions…. Any wrong instruction
leads to a undesired result.
 A program is something that runs on your computer. In
case of MS Windows program is of .EXE or .COM
extensions
 MS Word, Power point, Excel are all computer
programs
Writing C Programs
 A programmer uses a text editor to create or modify
files containing C code.
 Code is also known as source code.
 A file containing source code is called a source file.
 After a C source file has been created, the programmer
must invoke the C compiler before the program can
be executed (run).
#include <stdio.h>
/* The simplest C Program */
Writing and Running Programs
int main(int argc, char **argv) 1. Write text of program (source code) using an editor such
{ as Netbeans for C/C++ Development, Code::Blocks or
printf(“Hello World\n”); Eclipse CDT
return 0; 2. save as file e.g. my_program.c
}
3. Run the compiler to convert program from source to an
“executable” or “binary”:
$ gcc –Wall –g my_program.c –o my_program
$ gcc -Wall –g my_program.c –o my_program
tt.c: In function `main':
tt.c:6: parse error before `x'
tt.c:5: parm types given both in parmlist and separately
tt.c:8: `x' undeclared (first use in this function)
tt.c:8: (Each undeclared identifier is reported only once
4-N. Compiler gives errors and warnings; edit source file,
tt.c:8: for each function it appears in.)
tt.c:10: warning: control reaches end of non-void function
fix it, and re-compile
tt.c: At top level:
tt.c:11: parse error before `return'

N. Run it and see if it works 


$ ./my_program
my_program Hello World
$▌
4
C Syntax and Hello World

#include inserts another file. “.h” files are called “header”


files. They contain stuff needed to interface to libraries and
code in other “.c” files. Can your program have
What do the < > more than one .c file?
mean?
This is a comment. The compiler ignores this.

#include <stdio.h>
The main() function is always
/* The simplest C Program */ where your program starts
int main(int argc, char **argv) running.
{
Blocks of code (“lexical
printf(“Hello World\n”); scopes”) are marked by { … }
return 0;
}

Return ‘0’ from this function Print out a message. ‘\n’ means “new line”.

5
A Quick Digression About the Compiler

#include <stdio.h>
/* The simplest C Program */
Compilation occurs in two steps:
int main(int argc, char **argv)
{
Preprocess
printf(“Hello World\n”);
return 0;
“Preprocessing” and “Compiling”
}

In Preprocessing, source code is “expanded” into a


__extension__ typedef unsigned long long int __dev_t; larger form that is simpler for the compiler to
__extension__ typedef
__extension__ typedef
unsigned int
unsigned int
__uid_t;
__gid_t; understand. Any line that starts with ‘#’ is a line that is
__extension__ typedef unsigned long int __ino_t;
__extension__ typedef unsigned long long int __ino64_t; interpreted by the Preprocessor.
__extension__ typedef unsigned int __nlink_t;
__extension__ typedef long int __off_t;
__extension__ typedef long long int __off64_t;
extern void flockfile (FILE *__stream) ;
extern int ftrylockfile (FILE *__stream)
extern void funlockfile (FILE *__stream)
;
; • Include files are “pasted in” (#include)
int main(int argc, char **argv)
{
printf(“Hello World\n”); • Macros are “expanded” (#define)
return 0;
}
• Comments are stripped out ( /* */ , // )
• Continued lines are joined ( \ )
my_program
Compile
The compiler then converts the resulting text into
binary code the CPU can run directly.

6
What is a Variable?
symbol table?

A Variable names a place in memory where you Symbol Addr Value


store a Value of a certain Type. 0
1
You first Define a variable by giving it a name 2
and specifying the type, and optionally an initial 3
value declare vs define? x 4 ?
y 5 ‘e’ (101)
char x; Initial value of x is undefined
6
char y=‘e’;
7
The compiler puts them
Initial value 8
somewhere in memory.
9
Name What names are legal? 10

Type is single character (char) 11

extern? static? const?


12

7
Types of variable
• We must declare the type of every variable we use
in C.
• Every variable has a type (e.g. int) and a name.
• We already saw int, double and float.
• This prevents some bugs caused by spelling errors
(misspelling variable names).
• Declarations of types should always be together at
the top of main or a function (see later).
• Other types are char, signed, unsigned,
long, short and const.
Naming variables
• Variables in C can be given any name made from
numbers, letters and underlines which is not a
keyword and does not begin with a number.
• A good name for your variables is important
int a,b; int start_time;
double d; int no_students;
/* This is double course_mark;
a bit cryptic */ /* This is a bit better */

• Ideally, a comment with each variable name helps


people know what they do.
The char type
• char stores a character variable
• We can print char with %c
• A char has a single quote not a double quote.
• We can use it like so:
int main()
{
char a, b;
a= 'x'; /* Set a to the character x */
printf ("a is %c\n",a);
b= '\n'; /* This really is one character*/
printf ("b is %c\n",b);
return 0;
}
More types: Signed/unsigned,
long, short, const
• unsigned means that an int or char value can
only be positive. signed means that it can be
positive or negative.
• long means that int, float or double have
more precision (and are larger) short means they
have less
• const means a variable which doesn't vary –
useful for physical constants or things like pi or e
short int small_no;
unsigned char uchar;
long double precise_number;
short float not_so_precise;
const short float pi= 3.14;
const long double e= 2.718281828;
Range of The Different Data Types
Basic data type Data type with type qualifier Range
char or signed char -128 to 127
Char
Unsigned char 0 to 255
int or signed int -32768 to 32767
unsigned int 0 to 65535
short int or signed short int -128 to 127
Int
unsigned short int 0 to 255
long int or signed long int -2147483648 to 2147483647
unsigned long int 0 to 4294967295
Float float -3.4E-38 to 3.4E+38
double 1.7E-308 to 1.7E+308
Double
long double 3.4E-4932 to 1.1E+4932
A short note about ++
• ++i means increment i then use it
• i++ means use i then increment it
int i= 6;
printf ("%d\n",i++); /* Prints 6 sets i to 7 */

Note this important difference


int i= 6;
printf ("%d\n",++i); /* prints 7 and sets i to 7 */

It is easy to confuse yourself and others with the difference


between ++i and i++ - it is best to use them only in simple ways.

All of the above also applies to --.


Some simple operations for variables
• In addition to +, -, * and / we can also use +=, -=, *=,
/=, -- and % (modulo)

C provides compact assignment operators that can be used instead.


• x+=1 /∗is the same as x=x+1∗/
• x=-1 /∗is the same as x=x-1∗/
• x∗=10 /∗is the same as x=x∗10 ∗/
• x/=2 /∗ is the same as x=x/2
• x%=2 /∗is the same as x=x%2
Casting between variables
• Recall the trouble we had dividing ints
• A cast is a way of telling one variable type
to temporarily look like another.
int a= 3;
int b= 4; Cast ints a and b to be doubles
double c;
c= (double)a/(double)b;

By using (type) in front of a variable we tell the variable to


act like another type of variable. We can cast between any
type. Usually, however, the only reason to cast is to stop
ints being rounded by division.
Expressions and Evaluation

Expressions combine Values using Operators, according to precedence.

1 + 2 * 2  1 + 4  5
(1 + 2) * 2  3 * 2  6

Symbols are evaluated to their Values before being combined.


int x=1;
int y=2;
x + y * y  x + 2 * 2  x + 4  1 + 4  5

Comparison operators are used to compare values.


In C, 0 means “false”, and any other value means “true”.
int x=4;
(x < 5)  (4 < 5)  <true>
(x < 4)  (4 < 4)  0
((x < 5) || (x < 4))  (<true> || (x < 4))  <true>

Not evaluated because


first clause was true
16
Comparison and Mathematical Operators

== equal to The rules of precedence are clearly


< less than defined but often difficult to remember
<= less than or equal
> greater than or non-intuitive. When in doubt, add
>= greater than or equal parentheses to make it explicit. For
!= not equal
&& logical and
oft-confused cases, the compiler will
|| logical or give you a warning “Suggest parens
! logical not around …” – do it!
+ plus & bitwise and
- minus | bitwise or Beware division:
* mult ^ bitwise xor • If second argument is integer, the
/ divide ~ bitwise not
% modulo << shift left result will be integer (rounded):
>> shift right 5 / 10  0 whereas 5 / 10.0  0.5
• Division by 0 will cause a FPE

Don’t confuse & and &&..


1 & 2  0 whereas 1 && 2  <true>

17
Assignment Operators

x = y assign y to x x += y assign (x+y) to x


x++ post-increment x x -= y assign (x-y) to x
++x pre-increment x x *= y assign (x*y) to x
x-- post-decrement x x /= y assign (x/y) to x
--x pre-decrement x x %= y assign (x%y) to x

Note the difference between ++x and x++:


int x=5; int x=5;
int y; int y;
y = ++x; y = x++;
/* x == 6, y == 6 */ /* x == 6, y == 5 */

Don’t confuse = and ==! The compiler will warn “suggest parens”.
int x=5; int x=5;
if (x==6) /* false */ if (x=6) /* always true */
{ {
recommendation
/* ... */ /* x is now 6 */
} }
/* x is still 5 */ /* ... */ 18
Example-1
Add Two Numbers
Ask to the user to enter two numbers and place the addition of the
numbers in third variable of the same data type and print the third variable
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

int num1, num2, sum;


printf("Enter two number :");
scanf("%d%d",&num1, &num2);
sum=num1+num2;
printf("Sum of the two number is %d",sum);
return 0;
}

19
stdin, stdout, stderr

• When your C program begins to execute, three


input/output devices are opened automatically.
• stdin
– The “standard input” device, usually your keyboard
• stdout
– The “standard output” device, usually your monitor
• stderr
– The “standard error” device, usually your monitor
• Some C library I/O functions automatically use
these devices
Formatted Console Output

• In C formatted output is created using the


printf( ) function.
• printf( ) outputs text to stdout
• The basic function call to printf( ) is of the
form
printf( format, arg1, arg2, … );
where the format is a string containing
– conversion specifications
– literals to be printed
printf( ) conversions
Conversions specifications begin with % and end
with a conversion character.
Between the % and the conversion character MAY
be, in order
• A minus sign specifying left-justification
• The minimum field width
• A period separating the field width and precision
• The precision that specifies
• Maximum characters for a string
• Number of digits after the decimal for a floating point
• Minimum number of digits for an integer
• An h for “short” or an l (letter ell) for long
Common printf( ) Conversions
• %d -- the int argument is printed as a decimal number
• %u -- the int argument is printed as an unsigned number
• %s -- prints characters from the string until ‘\0’ is seen
or the number of characters in the (optional) precision
have been printed (more on this later)
• %f -- the double argument is printed as a floating point
number
• %x, %X -- the int argument is printed as a hexadecimal
number (without the usual leading “0x”)
• %c - the int argument is printed as a single character
• %p - the pointer argument is printed (implementation
dependent)
printf("%4d\n", 1);
printf("%4d\n", 12); Examples For Using a digit
printf("%4d\n", 123); Between % and the format specifier
printf("%4d\n", 1234);

printf("%4.2f\n", 1.0);
printf("%4.3f\n", 12.232432442);
printf("%2.1f\n", 12.232432442);
printf("%8.3f\n", 123.22);

int num1=12345;
int num2=96;
printf("%8d\n",num1);
printf("%08d\n",num1);
printf("%-8d%d\n",num1,num2);
Formatted Output Example

• Use field widths to align output in columns


int i;
for (i = 1 ; i < 5; i++)
printf("%2d %10.6f %20.15f\n",
i,sqrt(i),sqrt(i));

12 1234567890 12345678901234567890
1 1.000000 1.000000000000000
2 1.414214 1.414213562373095
3 1.732051 1.732050807568877
4 2.000000 2.000000000000000
Output Produced on Screen
C command using printf () with
Position: 1 1 1 1 1 1 1 1 1 1 2
various conversion specifiers:
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
printf ("%3c",'A'); A X X X X X X X X X X X X X X X X X
printf ("%-3c",'A'); A X X X X X X X X X X X X X X X X X
printf ("%8s","ABCD"); A B C D X X X X X X X X X X X X
printf ("%d",52); 5 2 X X X X X X X X X X X X X X X X X X
printf ("%8d",52); 5 2 X X X X X X X X X X X X
printf ("%-8d",52); 5 2 X X X X X X X X X X X X
printf ("%f",123.456); 1 2 3 . 4 5 6 0 0 0 X X X X X X X X X X
printf ("%10f",123.456); 1 2 3 . 4 5 6 0 0 0 X X X X X X X X X X
printf ("%10.2f",123.456); 1 2 3 . 4 6 X X X X X X X X X X
printf ("%-10.2f",123.456); 1 2 3 . 4 6 X X X X X X X X X X
printf ("%.2f",123.456); 1 2 3 . 4 6 X X X X X X X X X X X X X X
printf ("%10.3f",-45.8); - 4 5 . 8 0 0 X X X X X X X X X X
printf ("%10f",0.00085); 0 . 0 0 0 8 5 0 X X X X X X X X X X
printf ("%10.2e",123.89); 1 . 2 4 e + 0 0 2 X X X X X X X X X X
Keyboard Input
• In C, keyboard input is accomplished using the scanf( ) function.

• scanf reads user input from stdin.

• Calling scanf( ) is similar to calling printf( )

scanf( format, arg1, arg2, ... )

• The format string has a similar structure to the format string in


printf( ).

• The arguments are the addresses of the variables into which the input
is store.
scanf( ) format string
The scanf( ) format string usually contains
conversion specifications that tell scanf( ) how
to interpret the next “input field”. An input field is
a string of non-whitespace characters.
The format string usually contains
– Blanks or tabs which are ignored
– Ordinary characters which are expected to match the
next (non-whitespace) character input by the user
– Conversion specifications usually consisting
• % character indicating the beginning of the conversion
• An optional h, l (ell) or L
• A conversion character which indicates how the input field
is to be interpreted.
Common scanf( ) conversions
• %d -- a decimal (integer) number
• %u - an unsigned decimal (integer) number
• %x -- a hexadecimal number
– The matching argument is the address of an int
– May be preceded by h to indicate that the argument is the address of a short or
by l (ell) to indicate that the argument is the address of a long rather than an
int
• %f, %e -- a floating point number with optional sign, optional decimal
point, and optional exponent
– The matching argument is the address of a float
– May be preceded by l (ell) to indicate the argument is of the address of a
double rather than a float
• %s -- a word (a string delimited by white space, not an entire line)
– The matching argument is the address of a char or the name of a char array
– The caller must insure the array is large enough to for the input string and the
terminating \0 character
– More on this later
• %c - a single character
– The matching arguments is the address of a char
– Does not skip over white-space
– More on this later
scanf( ) examples

int age;
printf("How old are you? ");
scanf("%d", &age);
printf("OK, you are %d years old\n", age)
In this example,
• The format string “%d” is used, meaning that the program wants an integer
value from the keyboard.
• The value the user types will be stored in the age variable.

Here is possible output from the program when this code is executed (user input is in bold):

How old are you? 155


OK, you are 155 years old
Getting Input From the User by Using scanf
Example: The following code declares variables whose values the user will input,
prompts the user to do the input, and then captures the input values in the variables by
using scanf This printf just prints a string that tells the user that
double x; she is expected to enter some input now – we call
such a string a “prompt”.
int a, b;
float y;
printf("Enter 4 numbers (float, int, int, float: ");
Here is the scanf
scanf("%lf %d %d %f ", &x, &a, &b, &y);
statement that
actually does the
input.

Note that x, which is of type double,


needs %lf, not %f.
Character Constants
 Singular!
 One character defined character set.
 Surrounded on the single quotation mark.
 Examples:
 ‘A’
 ‘a’

 ‘$’

 ‘4’
String Constants
 A sequence characters surrounded by double
quotation marks.
 Considered a single item.
 Examples:
 “UMBC”
 “I like ice cream.”

 “123”

 “CAR”

 “car”
Punctuation
 Semicolons, colons, commas, apostrophes,
quotation marks, braces, brackets, and
parentheses.
 ; : , ‘ “ [ ] { } ( )
Keywords
 Sometimes called reserved words.
 Are defined as a part of the C language.
 Can not be used for anything else!
 Examples: Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Examples-1

Calculate total, average and percentage of marks of five


subjects in C programming.
Note That:
• Input marks of five subjects of a student
• Calculate total, average and percentage of all subjects.
• Not use any array variable
• The output is like below:
Example
Input
Enter marks of five subjects: 36.50 49.75 32.25 11.25 9.750
Output
Total = 139.50
Average = 27.90
Percentage = 27.90
Examples-1
int main(int argc, char *argv[]) {
float n1, n2, n3, n4, n5;
float tot, avrg, perc;

// Read marks of all five subjects


printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &n1, &n2, &n3, &n4, &n5);

// Calculate total, average and percentage one by one


tot = n1 + n2 + n3 + n4 + n5;
avrg = tot / 5.0;
perc = (tot / 500.0) * 100;

// Print the result


printf("Total marks = %.2f\n", tot);
printf("Average marks = %.2f\n", avrg);
printf("Percentage = %.2f", perc);
return 0;
}
Examples-2
Write a program to find square root of any integer number
Note That:
• Define only two variables called as “num” and “sqnum” and their
data types are respectively “integer” and “double”
• The integer number is entered from the user like:
• “Enter A Number =“
• “Square Root of ... = …” for the output.
• You must use the predefined sqrt() function to find square root in
your C program.
• You display the resultant value with 3 decimal places past the
decimal point.
Examples-2
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]) {


int num;
double sqnum;

/* Input a number from user */


printf("Enter A Number= ");
scanf("%d", &num);

/* Calculate square root of num */


sqnum = sqrt(num);

/* Print 3 digits only after decimal */


printf("Square Root of %d = %.3f", num, sqnum);

return 0;
}

You might also like