For loops Increment ,decrement operations

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
1 Chapter 3 Flow of Control. 2 Outline  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound statement.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Chapter 4 Program Control Statements
Fundamentals of C and C++ Programming Control Structures and Functions.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 05 (Part III) Control Statements: Part II.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
CPS120 Introduction to Computer Science Iteration (Looping)
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 4 – C Program Control
CSE 220 – C Programming Loops.
Data Types and Expressions
Data Types and Expressions
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
BASIC ELEMENTS OF A COMPUTER PROGRAM
Lecture 7: Repeating a Known Number of Times
Tokens in C Keywords Identifiers Constants
Week 4 – Repetition Structures / Loops
Chapter 3: Understanding C# Language Fundamentals
Looping.
Arrays, For loop While loop Do while loop
Unit 2 Programming.
- Additional C Statements
Lecture 8.
Introduction to C++ Programming
Chapter 7 Additional Control Structures
Chapter 4 - Program Control
Loops in C.
Lectures on Numerical Methods
elementary programming
C Programming Getting started Variables Basic C operators Conditionals
Chapter 3 Operators and Expressions
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Dale Roberts, Lecturer IUPUI
ECE 103 Engineering Programming Chapter 18 Iteration
Control Statements Paritosh Srivastava.
Chapter 4 - Program Control
An Overview of C.
Flow of Control.
DATA TYPES There are four basic data types associated with variables:
CSC215 Lecture Control Flow.
Getting Started With Coding
Presentation transcript:

For loops Increment ,decrement operations Revision For loops Increment ,decrement operations

Why study C? Helps to understand fundamental aspects of programming. Many popular software tools are written in C Has strongly influenced many other languages. Very concise language.

Simple program

C Data Types There are only a few basic data types in C: char int float double short, long, signed and unsigned are additional qualifiers.

Arithmetic operations in C

Rules of operator precedence

Equality and Relational Operators These operators are having lower priority then mathematical operators. The comma operator is having least priority. And its associativity is left to right . Equality operators have lower priority then logical operators.

Some programmer jargon Source code: The program you are writing. Compile (build): Taking source code and making a program that the computer can understand. Executable: The compiled program that the computer can run. Library: Added functions for C programming which are bolted on to do certain tasks. Header file: Files ending in .h which are included at the start of source code.

Few tips C does not care much about spaces. Statements are considered ending when “;” encountered. 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.

Few tips A character variable - has a single quote not a double quote. Ex char c=‘a’; 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

Few tips ++i means increment i then use it i++ means use i then increment it we can use -- (subtract one) e.g. countdown--; += (add to a variable) e.g. a+= 5; -= (subtract from variable) e.g. num_living-= num_dead; *= (multiply a variable) e.g. no_bunnies*=2; /= (divide a variable) e.g. fraction/= divisor;

Loop A repetition structure allows the programmer to specify that an action is to be repeated while some condition remains true. There are three repetition structures in C, the while loop, the for loop, and the do-while loop.

The while Repetition Structure Note:- The braces are not required if the loop body contains only a single statement. However, they are a good practice. first expr is evaluated. If it is nonzero (true), then statement is executed, and control is passed back to the beginning of the while loop. The body of the while loop, is executed repeatedly until expr is zero (false). At that point control passes to next statement. while ( expr ) { statement(s); } Next statement;

The for Statement for (expr1; expr2; expr3) { statement(s) } next statement Note :- First expr1 is evaluated; typically expr1 is used to initialize the loop. Then expr2 is evaluated; if it is nonzero (true) then statement is executed, expr3 is evaluated, and control passes back to the beginning of the for loop again, except that evaluation of expr1 is skipped. The process continues until expr2 is zero (false), at which point control passes to next statement. Advantage of for loop :- can do initialization, testing and indexing all at once on top of loop. It is used when the programmer knows how many times a set of statements are to be executed. Any or all of the expressions in a for statement can be missing, but the two semicolons must remain.

The do Statement The do statement is a variant of the while statement that tests its condition at the bottom of the loop. do {statement(s) } while (expr); Next statement

The break and continue Statements The break statement causes an exit from the innermost enclosing loop or switch statement. The continue statement causes the current iteration of a loop to stop and the next iteration to begin immediately.

How Break and continue work

Program1 –give output #include<stdio.h> int main(){     int i,j ,m,n;     i=j=2,3;     while(--i && j++)          printf("%d %d",i,j); i=2,3,4; j=(2,3,4); printf(“ \n%d”, i+j);     return 0; }

Output1 1 3 6 Notes:- “The assignment of “3” value has no effect . Actually writing anything without any proper presemble would not have any effect. Like { 3;4;printf(“test”);} here the “3;4; would not give any error but also would not give any output. As they are valid tokens. -The multiple values cant be assigned at declaration time –it would be syntax error Ex int i=2,3, - invalid -When comma used inside the parenthesis , its priority is increased . So the j= (2,3,4) which as two comma , has higher priority to the second comma hence j=4 is assigned. *) variation – if i=j=3 ,Output would be – “ 2 4 and 1 5”

Program 2 #include <stdio.h> int main() { int i=1; for(++ i;i<10;++ i) { printf(“%d ”,i); if (i==5) break; } printf(“\n”); for ( ; ++i ; ++i) { printf(“ %d ”,i ); if (i==8) break; } return 0;

output2 2 3 4 5 6 8 Note:- in for loop – - the first part assignment operation is needed ,if any comparison like i>12 , is used , it would simply ignore it and not do any change in the value of the loop variable used . The middle should be expression which on evaluation should return true (non zero value). If any assignment statement used here, it would execute that statement and return true and would enter the loop. If nothing mentioned , it would by default consider status true and would enter loop. The last part should be increment or decrement , if it is any other format , it would simply ignore it and not do any change in the value of the loop variable used.

Problem 3 #include <stdio.h> int main() { int i=1; for(i=0;i=-1;i=1) { printf(“%d”,i); if (i!=1) break; } return 0;

Output3 -1

Problem 6 #include <stdio.h> int main() { for(; ;) { printf(“%d”, 10); } return 0;

Output 6 10 10 10 ………infinite times

Problem 7 #include <stdio.h> int main() { int I; for(i=0;i<=5 ;i++); printf(“%d”,i); return 0; }

Output 7 6

Problem 8 #include<stdio.h> int main(){ int i; for(i=5;i<=15;i++) { while (i) if(i=i-1) { printf("i is %d \n ",i); continue; } } break; return 0;

Output 8 i is 4 i is 3 i is 2 i is 1

Problem 9 #include<stdio.h> void main(){ int k,num=30; k=(num>5 ? (num<=10? 100:200):500); printf(“%d”\n”, num); return 0; }

Output 9 30

Problem 10 #include < stdio.h > int main() { int tally=0;     for(;;)     {         if(tally==10)             break;         printf("%d ",++tally);     }     return 0; }

Solution 10 1 2 3 4 5 6 7 8 9 10 

P12 #include <stdio.h> void main() { int cnt=1; do {     {         printf("%d,",cnt);         cnt+=1;     }while(cnt>=10);     printf("\nAfter loop cnt=%d",cnt);     printf("\n"); }

S12 1, After loop cnt=2

p13 #include <stdio.h> void main() { int cnt=1;     while(cnt>=10)     {         printf("%d,",cnt);         cnt+=1;     }     printf("\nAfter loop cnt=%d",cnt);     printf("\n"); }

S13 After loop cnt=1

p14 #include <stdio.h> int main() { int i=1;     while(i<=10 && 1++)         printf("Hello"); }

s14 Error: lvalue required as increment operand (for the increment , we cannot have constant we need variable).

p15 #include <stdio.h> void main() { int a=10; switch(a){ {      int a=10;     switch(a){         case 5+5:             printf("Hello\n");         default:             printf("OK\n");     } }

s15 Hello OK

p16 #include <stdio.h> void main() { short day=2; switch(day) {     {         case 2: || case 22:             printf("%d nd",day);         break;         default:             printf("%d th",day);         break;      } }

s16 Syntax Error We can not use || operator between case statements, case 2:||case 22: invalid

p17 #include <stdio.h> void main() { int x=12,y=7,z; z=x!=4 || y==2;   printf(“z= %d”, z);   }

s17 1

P18- #include <stdio.h> void main(){      enum status {pass ,fail, rem}; enum status std1,std2,std3; std1=pass; std2=rem; std3=fail; printf(“ %d % d %d”, std1,std2,std3); }

s18 0 2 1

p19 #include <stdio.h> int main() { int i;     for(i=0; i< 5; i++)     {         if(i*i > 30 )             goto lbl;         else             printf("%d",i);     lbl:         printf("IHelp ");       }     return 0; }

s19 0IHelp 1IHelp 2IHelp 3IHelp 4IHelp (lbl label is declared within the for() body just after the if else statement and lbl label is executed after if or else body.)

P20 #include <stdio.h> int main() { int x; float y=7.0;     switch(x=y+1)     {         case 8: printf("It's Eight."); break;         default: printf("Oops No choice here!!!");     } }

s20 It's Eight. (Here, x=y+1 will be 8 – because x is an integer variable so final value that will return through this expression is 8.)

s21 #include <stdio.h> int main() { int a=10; if(a==10) {     {         printf("Hello...");         break;         printf("Ok");     }     else         printf("Hii");     return 0; }

021 Error : illegal break. A break statement can be used with looping and switch statements.

s22 #include <stdio.h> int main() { int pn=100; if(pn>20)             printf("Heyyyyy");     else         printf("Hiiiii");     return 0; }

O22 Hiiiii printf("Hiiiii"); that is written after else , is treated as else part of inner if condition if(pn<20).

s23 Which of the following are incorrect statements? If int a=10. 1)  if( a==10 )   printf("IncludeHelp"); 2)  if( 10==a )   printf("IncludeHelp"); 3)  if( a=10  )   printf("IncludeHelp"); 4)  if( 10=a  )   printf("IncludeHelp");

023 4 only.

S 24 char ch; ch=‘A’; printf(“The letter is”); printf(“%c”,ch>=‘A’ && ch<=‘Z’ ? ch+’a’-’A’ : ch); printf(“Now the letter is “); printf(“%c\n”,ch>=‘A’ && ch<=‘Z’? ch : ch+’a’-’A’);

O24 The letter is a Now the letter is A

p25 int i=2; int j=i + (1,2,3,4,5); printf(“%d”,j);

025 7 Reason:- comma operator has left –right associativity .the left operand is evaluated first and result is discarded before right operand is evaluated .

Steps to implement “c” program Writing a C code. {editors like gedit, vi} Compiling a C code. {gcc –c test.c –o test} Executing the object code. {./test}